Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 5a9a96445c49166a0ae015ad02cef900142e6ba5 (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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
/*******************************************************************************
 * Copyright (c) 2011, 2013 Wind River Systems, 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:
 * Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.tcf.te.tcf.core.internal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.tcf.core.AbstractPeer;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IPeer;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.IPathMap;
import org.eclipse.tcf.services.IPathMap.PathMapRule;
import org.eclipse.tcf.te.runtime.callback.Callback;
import org.eclipse.tcf.te.runtime.services.ServiceManager;
import org.eclipse.tcf.te.tcf.core.activator.CoreBundleActivator;
import org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager;
import org.eclipse.tcf.te.tcf.core.interfaces.IPathMapService;
import org.eclipse.tcf.te.tcf.core.interfaces.tracing.ITraceIds;
import org.eclipse.tcf.te.tcf.core.nls.Messages;
import org.eclipse.tcf.te.tcf.core.peers.Peer;
import org.eclipse.tcf.te.tcf.core.va.ValueAddManager;
import org.eclipse.tcf.te.tcf.core.va.interfaces.IValueAdd;


/**
 * TCF channel manager implementation.
 */
public final class ChannelManager extends PlatformObject implements IChannelManager {
	// The map of reference counters per peer id
	/* default */ final Map<String, AtomicInteger> refCounters = new HashMap<String, AtomicInteger>();
	// The map of channels per peer id
	/* default */ final Map<String, IChannel> channels = new HashMap<String, IChannel>();

	/**
	 * Constructor.
	 */
	public ChannelManager() {
		super();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager#openChannel(org.eclipse.tcf.protocol.IPeer, java.util.Map, org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager.DoneOpenChannel)
	 */
	@Override
	public void openChannel(final IPeer peer, final Map<String, Boolean> flags, final DoneOpenChannel done) {
		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
			try {
				throw new Throwable();
			} catch (Throwable e) {
				CoreBundleActivator.getTraceHandler().trace("ChannelManager#openChannel called from:", //$NON-NLS-1$
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
				e.printStackTrace();
			}
		}

		DoneOpenChannel innerDone = null;
		boolean noPathMap = flags != null && flags.containsKey(IChannelManager.FLAG_NO_PATH_MAP) ? flags.get(IChannelManager.FLAG_NO_PATH_MAP).booleanValue() : false;
		if (noPathMap) {
			innerDone = done;
		} else {
			innerDone = new DoneOpenChannel() {
				@Override
				public void doneOpenChannel(final Throwable error, final IChannel channel) {
					// If open channel failed, pass on to the original done
					if (error != null || channel == null || channel.getState() != IChannel.STATE_OPEN) {
						done.doneOpenChannel(error, channel);
					} else {
						// Take care of the path map
						final IPathMapService service = ServiceManager.getInstance().getService(peer, IPathMapService.class);
						final IPathMap svc = channel.getRemoteService(IPathMap.class);
						if (service != null && svc != null) {
							// Get the configured path maps
							final PathMapRule[] configuredMap = service.getPathMap(peer);
							if (configuredMap != null && configuredMap.length > 0) {
								// Get the old path maps first. Keep path map rules not coming from us
								svc.get(new IPathMap.DoneGet() {
                                    @Override
									public void doneGet(IToken token, Exception e, PathMapRule[] map) {
										// Merge the maps to a new list
										List<PathMapRule> rules = new ArrayList<PathMapRule>();

										if (map != null && map.length > 0) {
											for (PathMapRule rule : map) {
												if (rule.getID() == null || !rule.getID().startsWith(service.getClientID())) {
													rules.add(rule);
												}
											}
										}

										rules.addAll(Arrays.asList(configuredMap));
										if (!rules.isEmpty()) {
											svc.set(rules.toArray(new PathMapRule[rules.size()]), new IPathMap.DoneSet() {
												@Override
												public void doneSet(IToken token, Exception e) {
													done.doneOpenChannel(error, channel);
												}
											});
										}
									}
								});
							} else {
								done.doneOpenChannel(error, channel);
							}
						} else {
							done.doneOpenChannel(error, channel);
						}
					}
				}
			};
		}
		final DoneOpenChannel finInnerDone = innerDone;

		Runnable runnable = new Runnable() {
			@Override
            public void run() {
				Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

				// Check on the value-add's first
				internalHandleValueAdds(peer, flags, new DoneHandleValueAdds() {
					@Override
					public void doneHandleValueAdds(final Throwable error, final IValueAdd[] valueAdds) {
						// If the error is null, continue and open the channel
						if (error == null) {
							// Do we have any value add in the chain?
							if (valueAdds != null && valueAdds.length > 0) {
								// There are value-add's -> chain them now
								internalChainValueAdds(valueAdds, peer, flags, finInnerDone);
							} else {
								// No value-add's -> open a channel to the target peer directly
								internalOpenChannel(peer, flags, finInnerDone);
							}
						} else {
							// Shutdown the value-add's launched
							internalShutdownValueAdds(peer, valueAdds);
							// Fail the channel opening
							finInnerDone.doneOpenChannel(error, null);
						}
					}
				});
			}
		};
		if (Protocol.isDispatchThread()) runnable.run();
		else Protocol.invokeLater(runnable);
	}

	/**
	 * Internal implementation of {@link #openChannel(IPeer, org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager.DoneOpenChannel)}.
	 * <p>
	 * Reference counted channels are cached by the channel manager and must be closed via {@link #closeChannel(IChannel)} .
	 * <p>
	 * Method must be called within the TCF dispatch thread.
	 *
	 * @param peer The peer. Must not be <code>null</code>.
	 * @param flags Map containing the flags to parameterize the channel opening, or <code>null</code>.
	 * @param done The client callback. Must not be <code>null</code>.
	 */
	/* default */ void internalOpenChannel(final IPeer peer, final Map<String, Boolean> flags, final DoneOpenChannel done) {
		Assert.isNotNull(peer);
		Assert.isNotNull(done);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		// The channel instance to return
		IChannel channel = null;

		// Get the peer id
		final String id = peer.getID();

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
			CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_message, id, flags),
														0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
		}

		// Extract the flags of interest form the given flags map
		boolean forceNew = flags != null && flags.containsKey(IChannelManager.FLAG_FORCE_NEW) ? flags.get(IChannelManager.FLAG_FORCE_NEW).booleanValue() : false;
		boolean noValueAdd = flags != null && flags.containsKey(IChannelManager.FLAG_NO_VALUE_ADD) ? flags.get(IChannelManager.FLAG_NO_VALUE_ADD).booleanValue() : false;
		// If noValueAdd == true -> forceNew has to be true as well
		if (noValueAdd) forceNew = true;

		// Check if there is already a channel opened to this peer
		channel = !forceNew ? channels.get(id) : null;
		if (channel != null && (channel.getState() == IChannel.STATE_OPEN || channel.getState() == IChannel.STATE_OPENING)) {
			// Increase the reference count
			AtomicInteger counter = refCounters.get(id);
			if (counter == null) {
				counter = new AtomicInteger(0);
				refCounters.put(id, counter);
			}
			counter.incrementAndGet();

			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
				CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_reuse_message, id, counter.toString()),
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
			}
		} else if (channel != null) {
			// Channel is not in open state -> drop the instance
			channel = null;
			channels.remove(id);
			refCounters.remove(id);
		}

		// Opens a new channel if necessary
		if (channel == null) {
			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
				CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_new_message, id),
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
			}

			try {
				channel = peer.openChannel();

				if (channel != null) {
					if (!forceNew) channels.put(id, channel);
					if (!forceNew) refCounters.put(id, new AtomicInteger(1));

					// Register the channel listener
					final IChannel finChannel = channel;
					channel.addChannelListener(new IChannel.IChannelListener() {

						@Override
						public void onChannelOpened() {
							// Remove ourself as listener from the channel
							finChannel.removeChannelListener(this);

							if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
								CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_success_message, id),
																			0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, ChannelManager.this);
							}

							// Channel opening succeeded
							done.doneOpenChannel(null, finChannel);
						}

						@Override
						public void onChannelClosed(Throwable error) {
							// Remove ourself as listener from the channel
							finChannel.removeChannelListener(this);
							// Clean the reference counter and the channel map
							channels.remove(id);
							refCounters.remove(id);

							if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
								CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_failed_message, id, error),
																			0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
							}

							// Channel opening failed
							done.doneOpenChannel(error != null ? error : new OperationCanceledException(), finChannel);
						}

						@Override
						public void congestionLevel(int level) {
							// ignored
						}
					});
				} else {
					// Channel is null? Something went terrible wrong.
					done.doneOpenChannel(new Exception("Unexpected null return value from IPeer#openChannel()!"), null); //$NON-NLS-1$
				}
			} catch (Throwable e) {
				if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
					CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_failed_message, id, e),
																0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
				}

				// Channel opening failed
				done.doneOpenChannel(e, channel);
			}
		} else {
			// Wait for the channel to be fully opened if still in "OPENING" state
			if (channel.getState() == IChannel.STATE_OPENING) {
				final IChannel finChannel = channel;
				channel.addChannelListener(new IChannel.IChannelListener() {

					@Override
					public void onChannelOpened() {
						done.doneOpenChannel(null, finChannel);
					}

					@Override
					public void onChannelClosed(Throwable error) {
						done.doneOpenChannel(error != null ? error : new OperationCanceledException(), finChannel);
					}

					@Override
					public void congestionLevel(int level) {
					}
				});
			}
			else {
				done.doneOpenChannel(null, channel);
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager#openChannel(java.util.Map, java.util.Map, org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager.DoneOpenChannel)
	 */
	@Override
	public void openChannel(final Map<String, String> peerAttributes, final Map<String, Boolean> flags, final DoneOpenChannel done) {
		Runnable runnable = new Runnable() {
			@Override
            public void run() {
				Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
				internalOpenChannel(peerAttributes, flags, done);
			}
		};
		if (Protocol.isDispatchThread()) runnable.run();
		else Protocol.invokeLater(runnable);
	}

	/**
	 * Internal implementation of {@link #openChannel(Map, org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager.DoneOpenChannel)}.
	 * <p>
	 * Method must be called within the TCF dispatch thread.
	 *
	 * @param peerAttributes The peer attributes. Must not be <code>null</code>.
	 * @param flags Map containing the flags to parameterize the channel opening, or <code>null</code>.
	 * @param done The client callback. Must not be <code>null</code>.
	 */
	/* default */ void internalOpenChannel(final Map<String, String> peerAttributes, final Map<String, Boolean> flags, final DoneOpenChannel done) {
		Assert.isNotNull(peerAttributes);
		Assert.isNotNull(done);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		// Call openChannel(IPeer, ...) instead of calling internalOpenChannel(IPeer, ...) directly
		// to include the value-add handling.
		openChannel(getOrCreatePeerInstance(peerAttributes), flags, done);
	}

	/**
	 * Tries to find an existing peer instance or create an new {@link IPeer}
	 * instance if not found.
	 * <p>
	 * <b>Note:</b> This method must be invoked at the TCF dispatch thread.
	 *
	 * @param peerAttributes The peer attributes. Must not be <code>null</code>.
	 * @return The peer instance.
	 */
	private IPeer getOrCreatePeerInstance(final Map<String, String> peerAttributes) {
		Assert.isNotNull(peerAttributes);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		// Get the peer id from the properties
		String peerId = peerAttributes.get(IPeer.ATTR_ID);
		Assert.isNotNull(peerId);

		// Check if we shall open the peer transient
		boolean isTransient = peerAttributes.containsKey("transient") ? Boolean.parseBoolean(peerAttributes.remove("transient")) : false; //$NON-NLS-1$ //$NON-NLS-2$

		// Look the peer via the Locator Service.
		IPeer peer = Protocol.getLocator().getPeers().get(peerId);
		// If not peer could be found, create a new one
		if (peer == null) {
			peer = isTransient ? new Peer(peerAttributes) : new AbstractPeer(peerAttributes);

			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
				CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_createPeer_new_message, peerId, Boolean.valueOf(isTransient)),
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
			}
		}

		// Return the peer instance
		return peer;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager#getChannel(org.eclipse.tcf.protocol.IPeer)
	 */
	@Override
	public IChannel getChannel(final IPeer peer) {
		final AtomicReference<IChannel> channel = new AtomicReference<IChannel>();
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
				channel.set(internalGetChannel(peer));
			}
		};
		if (Protocol.isDispatchThread()) runnable.run();
		else Protocol.invokeAndWait(runnable);

	    return channel.get();
	}

	/**
	 * Returns the shared channel instance for the given peer.
	 * <p>
	 * <b>Note:</b> This method must be invoked at the TCF dispatch thread.
	 *
	 * @param peer The peer. Must not be <code>null</code>.
	 * @return The channel instance or <code>null</code>.
	 */
	public IChannel internalGetChannel(IPeer peer) {
		Assert.isNotNull(peer);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		// Get the peer id
		String id = peer.getID();

		// Get the channel
		IChannel channel = channels.get(id);
		if (channel != null && !(channel.getState() == IChannel.STATE_OPEN || channel.getState() == IChannel.STATE_OPENING)) {
			// Channel is not in open state -> drop the instance
			channel = null;
			channels.remove(id);
			refCounters.remove(id);
		}

		return channel;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager#closeChannel(org.eclipse.tcf.protocol.IChannel)
	 */
	@Override
	public void closeChannel(final IChannel channel) {
		Runnable runnable = new Runnable() {
			@Override
            public void run() {
				Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
				internalCloseChannel(channel);
			}
		};
		if (Protocol.isDispatchThread()) runnable.run();
		else Protocol.invokeLater(runnable);
	}

	/**
	 * Closes the given channel.
	 * <p>
	 * If the given channel is a reference counted channel, the channel will be closed if the reference counter
	 * reaches 0. For non reference counted channels, the channel is closed immediately.
	 * <p>
	 * <b>Note:</b> This method must be invoked at the TCF dispatch thread.
	 *
	 * @param channel The channel. Must not be <code>null</code>.
	 */
	/* default */ void internalCloseChannel(IChannel channel) {
		Assert.isNotNull(channel);
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		// Get the id of the remote peer
		String id = channel.getRemotePeer().getID();

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
			CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_closeChannel_message, id),
														0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
		}

		// Get the reference counter
		AtomicInteger counter = refCounters.get(id);

		// If the counter is null or get 0 after the decrement, close the channel
		if (counter == null || counter.decrementAndGet() == 0) {
			channel.close();

			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
				CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_closeChannel_closed_message, id),
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
			}

			// Clean the reference counter and the channel map
			refCounters.remove(id);
			channels.remove(id);
		} else {
			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
				CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_closeChannel_inuse_message, id, counter.toString()),
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager#shutdown(org.eclipse.tcf.protocol.IPeer)
	 */
	@Override
	public void shutdown(final IPeer peer) {
		Runnable runnable = new Runnable() {
			@Override
            public void run() {
				Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
				internalShutdown(peer);
			}
		};
		if (Protocol.isDispatchThread()) runnable.run();
		else Protocol.invokeLater(runnable);
	}

	/**
	 * Shutdown the communication to the given peer, no matter of the current
	 * reference count. A possible associated value-add is shutdown as well.
	 *
	 * @param peer The peer. Must not be <code>null</code>.
	 */
	/* default */ void internalShutdown(IPeer peer) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(peer);

		// Get the peer id
		String id = peer.getID();

		// Get the channel
		IChannel channel = internalGetChannel(peer);
		if (channel != null) {
			// Reset the reference count (will force a channel close)
			refCounters.remove(id);

			// Close the channel
			internalCloseChannel(channel);

			// Get the value-add's for the peer to shutdown
			IValueAdd[] valueAdds = ValueAddManager.getInstance().getValueAdd(peer);
			if (valueAdds != null && valueAdds.length > 0) {
				internalShutdownValueAdds(peer, valueAdds);
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.tcf.core.interfaces.IChannelManager#closeAll(boolean)
	 */
	@Override
	public void closeAll(boolean wait) {
		if (wait) Assert.isTrue(!Protocol.isDispatchThread());

		Runnable runnable = new Runnable() {
			@Override
            public void run() {
				Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
				internalCloseAll();
			}
		};

		if (Protocol.isDispatchThread()) runnable.run();
		else if (wait) Protocol.invokeAndWait(runnable);
		else Protocol.invokeLater(runnable);
	}

	/**
	 * Close all open channel, no matter of the current reference count.
	 * <p>
	 * <b>Note:</b> This method must be invoked at the TCF dispatch thread.
	 */
	/* default */ void internalCloseAll() {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		IChannel[] openChannels = channels.values().toArray(new IChannel[channels.values().size()]);

		refCounters.clear();
		channels.clear();

		for (IChannel channel : openChannels) internalCloseChannel(channel);

		internalShutdownAllValueAdds();
	}

	/**
	 * Shutdown the given value-adds for the given peer.
	 *
	 * @param peer The peer. Must not be <code>null</code>.
	 * @param valueAdds The list of value-adds. Must not be <code>null</code>.
	 */
	/* default */ void internalShutdownValueAdds(final IPeer peer, final IValueAdd[] valueAdds) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(peer);
		Assert.isNotNull(valueAdds);

		// Get the peer id
		final String id = peer.getID();

		if (valueAdds.length > 0) {
			doShutdownValueAdds(id, valueAdds);
		}
	}

	/**
	 * Shutdown the given value-adds for the given peer id.
	 *
	 * @param id The peer id. Must not be <code>null</code>.
	 * @param valueAdds The list of value-add's. Must not be <code>null</code>.
	 */
	/* default */ void doShutdownValueAdds(final String id, final IValueAdd[] valueAdds) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(id);
		Assert.isNotNull(valueAdds);

		for (IValueAdd valueAdd : valueAdds) {
			valueAdd.shutdown(id, new Callback() {
				@Override
				protected void internalDone(Object caller, IStatus status) {
				}
			});
		}
	}

	/**
	 * Shutdown all value-add's running. Called from {@link #closeAll(boolean)}
	 */
	/* default */ void internalShutdownAllValueAdds() {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$

		// Get all value-add's
		IValueAdd[] valueAdds = ValueAddManager.getInstance().getValueAdds(false);
		for (IValueAdd valueAdd : valueAdds) {
			valueAdd.shutdownAll(new Callback() {
				@Override
				protected void internalDone(Object caller, IStatus status) {
				}
			});
		}
	}

	/**
	 * Client call back interface for internalHandleValueAdds(...).
	 */
	interface DoneHandleValueAdds {
		/**
		 * Called when all the value-adds are launched or the launched failed.
		 *
		 * @param error The error description if operation failed, <code>null</code> if succeeded.
		 * @param valueAdds The list of value-adds or <code>null</code>.
		 */
		void doneHandleValueAdds(Throwable error, IValueAdd[] valueAdds);
	}

	/**
	 * Check on the value-adds for the given peer. Launch the value-adds
	 * if necessary.
	 *
	 * @param peer The peer. Must not be <code>null</code>.
	 * @param flags Map containing the flags to parameterize the channel opening, or <code>null</code>.
	 * @param done The client callback. Must not be <code>null</code>.
	 */
	/* default */ void internalHandleValueAdds(final IPeer peer, final Map<String, Boolean> flags, final DoneHandleValueAdds done) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(peer);
		Assert.isNotNull(done);

		// Get the peer id
		final String id = peer.getID();

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
			CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_valueAdd_check, id),
														0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
		}

		// Extract the flags of interest form the given flags map
		boolean forceNew = flags != null && flags.containsKey(IChannelManager.FLAG_FORCE_NEW) ? flags.get(IChannelManager.FLAG_FORCE_NEW).booleanValue() : false;
		boolean noValueAdd = flags != null && flags.containsKey(IChannelManager.FLAG_NO_VALUE_ADD) ? flags.get(IChannelManager.FLAG_NO_VALUE_ADD).booleanValue() : false;
		// If noValueAdd == true -> forceNew has to be true as well
		if (noValueAdd) forceNew = true;

		// Check if there is already a channel opened to this peer
		IChannel channel = !forceNew ? channels.get(id) : null;
		if (noValueAdd || channel != null && (channel.getState() == IChannel.STATE_OPEN || channel.getState() == IChannel.STATE_OPENING)) {
			// Got an existing channel or a channel without value-add decoration
			// got requested -> drop out immediately
			done.doneHandleValueAdds(null, null);
			return;
		}

		internalHandleValueAdds(peer, done);
	}

	/* default */ final Map<IPeer, List<DoneHandleValueAdds>> inProgress = new HashMap<IPeer, List<DoneHandleValueAdds>>();

	/**
	 * Check on the value-adds for the given peer. Launch the value-adds
	 * if necessary.
	 *
	 * @param peer The peer. Must not be <code>null</code>.
	 * @param done The client callback. Must not be <code>null</code>.
	 */
	/* default */ void internalHandleValueAdds(final IPeer peer, final DoneHandleValueAdds done) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(peer);
		Assert.isNotNull(done);

		// Get the peer id
		final String id = peer.getID();

		// If a launch for the same value add is in progress already, attach the new done to
		// the list to call and drop out
		if (inProgress.containsKey(peer)) {
			List<DoneHandleValueAdds> dones = inProgress.get(peer);
			Assert.isNotNull(dones);
			dones.add(done);
			return;
		}

		// Add the done callback to a list of waiting callbacks per peer
		List<DoneHandleValueAdds> dones = new ArrayList<DoneHandleValueAdds>();
		dones.add(done);
		inProgress.put(peer, dones);

		// The "myDone" callback is invoking the callbacks from the list
		// of waiting callbacks.
		final DoneHandleValueAdds myDone = new DoneHandleValueAdds() {

			@Override
			public void doneHandleValueAdds(Throwable error, IValueAdd[] valueAdds) {
				// Get the list of the original done callbacks
				List<DoneHandleValueAdds> dones = inProgress.remove(peer);
				for (DoneHandleValueAdds done : dones) {
					done.doneHandleValueAdds(error, valueAdds);
				}
			}
		};

		// Do we have applicable value-add contributions
		final IValueAdd[] valueAdds = ValueAddManager.getInstance().getValueAdd(peer);
		if (valueAdds.length == 0) {
			// There are no applicable value-add's -> drop out immediately
			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
				CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_valueAdd_noneApplicable, id),
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
			}
			myDone.doneHandleValueAdds(null, valueAdds);
			return;
		}

		// There are at least applicable value-add contributions
		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
			CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_valueAdd_numApplicable, Integer.valueOf(valueAdds.length), id),
														0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
		}

		final List<IValueAdd> available = new ArrayList<IValueAdd>();

		final DoneLaunchValueAdd innerDone = new DoneLaunchValueAdd() {
			@Override
			public void doneLaunchValueAdd(Throwable error, List<IValueAdd> available) {
				myDone.doneHandleValueAdds(error, available.toArray(new IValueAdd[available.size()]));
			}
		};

		doLaunchValueAdd(id, valueAdds, 0, available, innerDone);
	}

	/**
	 * Client call back interface for doLaunchValueAdd(...).
	 */
	interface DoneLaunchValueAdd {
		/**
		 * Called when a value-add has been chained.
		 *
		 * @param error The error description if operation failed, <code>null</code> if succeeded.
		 * @param available The list of available value-adds.
		 */
		void doneLaunchValueAdd(Throwable error, List<IValueAdd> available);
	}

	/**
	 * Test the value-add at the given index to be alive. Launch the value-add if necessary.
	 *
	 * @param id The peer id. Must not be <code>null</code>.
	 * @param valueAdds The list of value-add's to check. Must not be <code>null</code>.
	 * @param i The index.
	 * @param available The list of available value-adds. Must not be <code>null</code>.
	 * @param done The client callback. Must not be <code>null</code>.
	 */
	/* default */ void doLaunchValueAdd(final String id, final IValueAdd[] valueAdds, final int i, final List<IValueAdd> available, final DoneLaunchValueAdd done) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(id);
		Assert.isNotNull(valueAdds);
		Assert.isTrue(valueAdds.length > 0);
		Assert.isNotNull(available);
		Assert.isNotNull(done);

		// Get the value-add to launch
		final IValueAdd valueAdd = valueAdds[i];

		// Check if the value-add to launch is alive
		valueAdd.isAlive(id, new Callback() {
			@Override
			protected void internalDone(Object caller, IStatus status) {
				boolean alive = ((Boolean)getResult()).booleanValue();

				if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
					CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_valueAdd_isAlive, new Object[] { Integer.valueOf(i), valueAdd.getLabel(), Boolean.valueOf(alive), id }),
																0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, ChannelManager.this);
				}

				if (!alive) {
					// Launch the value-add
					valueAdd.launch(id, new Callback() {
						@Override
						protected void internalDone(Object caller, IStatus status) {
							Throwable error = status.getException();

							if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
								CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_valueAdd_launch, new Object[] { Integer.valueOf(i), valueAdd.getLabel(),
												(error == null ? "success" : "failed"), //$NON-NLS-1$ //$NON-NLS-2$
												(error != null ? error.getLocalizedMessage() : null),
												id }),
												0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, ChannelManager.this);
							}

							// If we got an error and the value-add is optional,
							// log the error as warning and drop the value-add
							if (error != null && valueAdd.isOptional()) {
								status = new Status(IStatus.WARNING, CoreBundleActivator.getUniqueIdentifier(),
												NLS.bind(Messages.ChannelManager_valueAdd_launchFailed, valueAdd.getLabel(), error.getLocalizedMessage()),
												error);
								Platform.getLog(CoreBundleActivator.getContext().getBundle()).log(status);

								// Reset the error
								error = null;
							} else {
								available.add(valueAdd);
							}

							// If the value-add failed to launch, no other value-add's are launched
							if (error != null) {
								done.doneLaunchValueAdd(error, available);
							} else {
								// Launch the next one, if there is any
								if (i + 1 < valueAdds.length) {
									DoneLaunchValueAdd innerDone = new DoneLaunchValueAdd() {
										@Override
										public void doneLaunchValueAdd(Throwable error, List<IValueAdd> available) {
											done.doneLaunchValueAdd(error, available);
										}
									};
									doLaunchValueAdd(id, valueAdds, i + 1, available, innerDone);
								} else {
									// Last value-add in chain launched -> call parent callback
									done.doneLaunchValueAdd(null, available);
								}
							}
						}
					});
				} else {
					// Already alive -> add it to the list of available value-add's
					available.add(valueAdd);
					// Launch the next one, if there is any
					if (i + 1 < valueAdds.length) {
						DoneLaunchValueAdd innerDone = new DoneLaunchValueAdd() {
							@Override
							public void doneLaunchValueAdd(Throwable error, List<IValueAdd> available) {
								done.doneLaunchValueAdd(error, available);
							}
						};
						doLaunchValueAdd(id, valueAdds, i + 1, available, innerDone);
					} else {
						// Last value-add in chain launched -> call parent callback
						done.doneLaunchValueAdd(null, available);
					}
				}
			}
		});
	}

	/**
	 * Client call back interface for doChainValueAdd(...).
	 */
	interface DoneChainValueAdd {
		/**
		 * Called when a value-add has been chained.
		 *
		 * @param error The error description if operation failed, <code>null</code> if succeeded.
		 * @param channel The channel object or <code>null</code>.
		 */
		void doneChainValueAdd(Throwable error, IChannel channel);
	}

	/**
	 * Chain the value-adds until the original target peer is reached.
	 *
	 * @param valueAdds The list of value-add's to chain. Must not be <code>null</code>.
	 * @param peer The original target peer. Must not be <code>null</code>.
	 * @param flags Map containing the flags to parameterize the channel opening, or <code>null</code>.
	 * @param done The client callback. Must not be <code>null</code>.
	 */
	/* default */ void internalChainValueAdds(final IValueAdd[] valueAdds, final IPeer peer, final Map<String, Boolean> flags, final DoneOpenChannel done) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(valueAdds);
		Assert.isNotNull(peer);
		Assert.isNotNull(done);

		// Get the peer id
		final String id = peer.getID();

		if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
			CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_valueAdd_startChaining, id),
														0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
		}

		// Extract the flags of interest form the given flags map
		boolean forceNew = flags != null && flags.containsKey(IChannelManager.FLAG_FORCE_NEW) ? flags.get(IChannelManager.FLAG_FORCE_NEW).booleanValue() : false;
		boolean noValueAdd = flags != null && flags.containsKey(IChannelManager.FLAG_NO_VALUE_ADD) ? flags.get(IChannelManager.FLAG_NO_VALUE_ADD).booleanValue() : false;
		boolean noPathMap = flags != null && flags.containsKey(IChannelManager.FLAG_NO_PATH_MAP) ? flags.get(IChannelManager.FLAG_NO_PATH_MAP).booleanValue() : false;
		// If noValueAdd == true or noPathMap == true -> forceNew has to be true as well
		if (noValueAdd || noPathMap) forceNew = true;

		// Check if there is already a channel opened to this peer
		IChannel channel = !forceNew ? channels.get(id) : null;
		if (channel != null && (channel.getState() == IChannel.STATE_OPEN || channel.getState() == IChannel.STATE_OPENING)) {
			// Increase the reference count
			AtomicInteger counter = refCounters.get(id);
			if (counter == null) {
				counter = new AtomicInteger(0);
				refCounters.put(id, counter);
			}
			counter.incrementAndGet();

			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
				CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_reuse_message, id, counter.toString()),
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
			}
			// Got an existing channel -> drop out immediately if the channel is
			// already fully opened. Otherwise wait for the channel to be fully open.
			if (channel.getState() == IChannel.STATE_OPENING) {
				final IChannel finChannel = channel;
				channel.addChannelListener(new IChannel.IChannelListener() {
					@Override
					public void onChannelOpened() {
						done.doneOpenChannel(null, finChannel);
					}
					@Override
					public void onChannelClosed(Throwable error) {
						done.doneOpenChannel(error != null ? error : new OperationCanceledException(), finChannel);
					}
					@Override
					public void congestionLevel(int level) {
					}
				});
			}
			else {
				done.doneOpenChannel(null, channel);
			}
			return;
		} else if (channel != null) {
			// Channel is not in open state -> drop the instance
			channels.remove(id);
			refCounters.remove(id);
		}

		// No existing channel -> open a new one
		final DoneChainValueAdd innerDone = new DoneChainValueAdd() {
			@Override
			public void doneChainValueAdd(Throwable error, IChannel channel) {
				done.doneOpenChannel(error, channel);
			}
		};

		doChainValueAdd(id, peer.getAttributes(), forceNew, valueAdds, innerDone);
	}

	/* default */ void doChainValueAdd(final String id, final Map<String, String> attrs, final boolean forceNew, final IValueAdd[] valueAdds, final DoneChainValueAdd done) {
		Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
		Assert.isNotNull(id);
		Assert.isNotNull(attrs);
		Assert.isNotNull(valueAdds);
		Assert.isNotNull(done);

		// The index of the currently processed value-add
		final AtomicInteger index = new AtomicInteger(0);

		// Get the value-add to chain
		final AtomicReference<IValueAdd> valueAdd = new AtomicReference<IValueAdd>();
		valueAdd.set(valueAdds[index.get()]);
		Assert.isNotNull(valueAdd.get());
		// Get the next value-add in chain
		final AtomicReference<IValueAdd> nextValueAdd = new AtomicReference<IValueAdd>();
		nextValueAdd.set(index.get() + 1 < valueAdds.length ? valueAdds[index.get() + 1] : null);

		// Get the peer for the value-add to chain
		final AtomicReference<IPeer> valueAddPeer = new AtomicReference<IPeer>();
		valueAddPeer.set(valueAdd.get().getPeer(id));
		if (valueAddPeer.get() == null) {
			done.doneChainValueAdd(new IllegalStateException("Invalid value-add peer."), null); //$NON-NLS-1$
			return;
		}

		// Get the peer for the next value-add in chain
		final AtomicReference<IPeer> nextValueAddPeer = new AtomicReference<IPeer>();
		nextValueAddPeer.set(nextValueAdd.get() != null ? nextValueAdd.get().getPeer(id) : null);
		if (nextValueAdd.get() != null && nextValueAddPeer.get() == null) {
			done.doneChainValueAdd(new IllegalStateException("Invalid value-add peer."), null); //$NON-NLS-1$
			return;
		}

		IChannel channel = null;
		try {
			// Open a channel to the value-add
			channel = valueAddPeer.get().openChannel();
			if (channel != null) {
				if (!forceNew) channels.put(id, channel);
				if (!forceNew) refCounters.put(id, new AtomicInteger(1));

				// Attach the channel listener to catch open/closed events
				final IChannel finChannel = channel;
				channel.addChannelListener(new IChannel.IChannelListener() {
					@Override
					public void onChannelOpened() {
						if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
							CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_valueAdd_redirect_succeeded,
																				 new Object[] { valueAddPeer.get().getID(), finChannel.getRemotePeer().getID(), Integer.valueOf(index.get()) }),
																		0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, ChannelManager.this);
						}

						// Channel opened. Check if we are done.
						if (nextValueAdd.get() == null) {
							// Remove ourself as channel listener
							finChannel.removeChannelListener(this);

							// No other value-add in the chain -> all done
							done.doneChainValueAdd(null, finChannel);
						} else {
							// Process the next value-add in chain
							index.incrementAndGet();

							// Update the value-add references
							valueAdd.set(nextValueAdd.get());
							valueAddPeer.set(nextValueAddPeer.get());

							if (valueAddPeer.get() == null) {
								// Remove ourself as channel listener
								finChannel.removeChannelListener(this);
								// Close the channel
								finChannel.close();
								// Invoke the callback
								done.doneChainValueAdd(new IllegalStateException("Invalid value-add peer."), null); //$NON-NLS-1$
								return;
							}

							nextValueAdd.set(index.get() + 1 < valueAdds.length ? valueAdds[index.get() + 1] : null);
							nextValueAddPeer.set(nextValueAdd.get() != null ? nextValueAdd.get().getPeer(id) : null);
							if (nextValueAdd.get() != null && nextValueAddPeer.get() == null) {
								// Remove ourself as channel listener
								finChannel.removeChannelListener(this);
								// Close the channel
								finChannel.close();
								// Invoke the callback
								done.doneChainValueAdd(new IllegalStateException("Invalid value-add peer."), null); //$NON-NLS-1$
								return;
							}

							// Redirect the channel to the next value-add in chain
							finChannel.redirect(nextValueAddPeer.get() != null ? nextValueAddPeer.get().getAttributes() : attrs);
						}
					}

					@Override
					public void onChannelClosed(Throwable error) {
						// Remove ourself as channel listener
						finChannel.removeChannelListener(this);

						if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
							CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_valueAdd_redirect_failed, valueAddPeer.get().getID(),
																				 nextValueAddPeer.get() != null ? nextValueAddPeer.get().getID() : id),
																		0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, ChannelManager.this);
						}

						// Clean the reference counter and the channel map
						channels.remove(id);
						refCounters.remove(id);
						// Channel opening failed -> This will break everything
						done.doneChainValueAdd(error, finChannel);
					}

					@Override
					public void congestionLevel(int level) {
					}
				});

				// Redirect the channel to the next value-add in chain
				// Note: If the redirect succeeds, channel.getRemotePeer().getID() will be identical to id.
				channel.redirect(nextValueAddPeer.get() != null ? nextValueAddPeer.get().getAttributes() : attrs);
			} else {
				// Channel is null? Something went terrible wrong.
				done.doneChainValueAdd(new Exception("Unexpected null return value from IPeer#openChannel()!"), null); //$NON-NLS-1$

			}
		} catch (Throwable e) {
			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) {
				CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.ChannelManager_openChannel_failed_message, id, e),
															0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this);
			}

			// Channel opening failed
			done.doneChainValueAdd(e, channel);
		}
	}
}

Back to the top