Skip to main content
summaryrefslogtreecommitdiffstats
blob: 6ffeb3c1561ba1bd888886d95da09ade7e3623e2 (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
1107
/*******************************************************************************
 * 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.generic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import org.eclipse.ecf.core.IOSGIService;
import org.eclipse.ecf.core.ISharedObject;
import org.eclipse.ecf.core.ISharedObjectConfig;
import org.eclipse.ecf.core.ISharedObjectContainer;
import org.eclipse.ecf.core.ISharedObjectContainerConfig;
import org.eclipse.ecf.core.ISharedObjectContainerListener;
import org.eclipse.ecf.core.ISharedObjectContainerTransaction;
import org.eclipse.ecf.core.ISharedObjectManager;
import org.eclipse.ecf.core.SharedObjectAddException;
import org.eclipse.ecf.core.SharedObjectContainerJoinException;
import org.eclipse.ecf.core.SharedObjectDescription;
import org.eclipse.ecf.core.SharedObjectInitException;
import org.eclipse.ecf.core.comm.AsynchConnectionEvent;
import org.eclipse.ecf.core.comm.ConnectionEvent;
import org.eclipse.ecf.core.comm.DisconnectConnectionEvent;
import org.eclipse.ecf.core.comm.IConnection;
import org.eclipse.ecf.core.comm.ISynchAsynchConnectionEventHandler;
import org.eclipse.ecf.core.comm.SynchConnectionEvent;
import org.eclipse.ecf.core.events.IContainerEvent;
import org.eclipse.ecf.core.events.SharedObjectContainerDisposeEvent;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.util.Event;
import org.eclipse.ecf.core.util.QueueEnqueue;
import org.eclipse.ecf.provider.Trace;
import org.eclipse.ecf.provider.generic.gmm.Member;

public abstract class SOContainer implements ISharedObjectContainer {
	class LoadingSharedObject implements ISharedObject {
		Object credentials;

		SharedObjectDescription description;

		Thread runner = null;

		ID fromID = null;

		LoadingSharedObject(ID fromID, SharedObjectDescription sd,
				Object credentials) {
			this.fromID = fromID;
			this.description = sd;
			this.credentials = credentials;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.core.ISharedObject#dispose(org.eclipse.ecf.core.identity.ID)
		 */
		public void dispose(ID containerID) {
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.core.ISharedObject#getAdapter(java.lang.Class)
		 */
		public Object getAdapter(Class clazz) {
			return null;
		}

		ID getHomeID() {
			return description.getHomeID();
		}

		ID getID() {
			return description.getID();
		}

		Thread getThread() {
			return new Thread(loadingThreadGroup, new Runnable() {
				public void run() {
					try {
						if (Thread.currentThread().isInterrupted()
								|| isClosing())
							throw new InterruptedException(
									"Loading interrupted for object "
											+ getID().getName());
						// First load object
						ISharedObject obj = load(description);
						// Create wrapper object and move from loading to active
						// list.
						SOWrapper wrap = makeNewRemoteSharedObjectWrapper(
								fromID, description, obj);
                        
                        wrap.init();
						// Check to make sure thread has not been
						// interrupted...if it has, throw
						if (Thread.currentThread().isInterrupted()
								|| isClosing())
							throw new InterruptedException(
									"Loading interrupted for object "
											+ getID().getName());
						// Finally, we move from loading to active, and then the
						// object is done
						SOContainer.this.moveFromLoadingToActive(wrap);
					} catch (Exception e) {
						dumpStack("Exception loading object ", e);
						SOContainer.this.removeFromLoading(getID());
						try {
							sendCreateResponse(getHomeID(), getID(), e,
									description.getIdentifier());
						} catch (Exception e1) {
							dumpStack(
									"Exception sending create response from LoadingSharedObject.run",
									e1);
						}
					}
				}
			}, getID().getName() + ":load");
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.core.ISharedObject#handleEvent(org.eclipse.ecf.core.util.Event)
		 */
		public void handleEvent(Event event) {
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.core.ISharedObject#handleEvents(org.eclipse.ecf.core.util.Event[])
		 */
		public void handleEvents(Event[] events) {
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.core.ISharedObject#init(org.eclipse.ecf.core.ISharedObjectConfig)
		 */
		public void init(ISharedObjectConfig initData)
				throws SharedObjectInitException {
		}

		void start() {
			if (runner == null) {
				runner = (Thread) AccessController
						.doPrivileged(new PrivilegedAction() {
							public Object run() {
								return getThread();
							}
						});
				runner.setDaemon(true);
				runner.start();
			}
		}
	}

	class MessageReceiver implements ISynchAsynchConnectionEventHandler {
		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.internal.comm.IConnectionEventHandler#getAdapter(java.lang.Class)
		 */
		public Object getAdapter(Class clazz) {
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.internal.comm.IAsynchConnectionEventHandler#handleAsynchEvent(org.eclipse.ecf.internal.comm.AsynchConnectionEvent)
		 */
		public void handleAsynchEvent(AsynchConnectionEvent event)
				throws IOException {
			processAsynch(event);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.internal.comm.IConnectionEventHandler#handleDisconnectEvent(org.eclipse.ecf.internal.comm.ConnectionEvent)
		 */
		public void handleDisconnectEvent(DisconnectConnectionEvent event) {
			processDisconnect(event);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.internal.comm.IConnectionEventHandler#handleSuspectEvent(org.eclipse.ecf.internal.comm.ConnectionEvent)
		 */
		public boolean handleSuspectEvent(ConnectionEvent event) {
			return false;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.internal.comm.ISynchConnectionEventHandler#handleSynchEvent(org.eclipse.ecf.internal.comm.SynchConnectionEvent)
		 */
		public Object handleSynchEvent(SynchConnectionEvent event)
				throws IOException {
			return processSynch(event);
		}
	}

	static Trace debug = Trace.create("container");

	public static final String DEFAULT_OBJECT_ARG_KEY = SOContainer.class
			.getName()
			+ ".sharedobjectargs";

	public static final String DEFAULT_OBJECT_ARGTYPES_KEY = SOContainer.class
			.getName()
			+ ".sharedobjectargs";

	protected ISharedObjectContainerConfig config = null;

	protected SOContainerGMM groupManager = null;

	protected boolean isClosing = false;

	private Vector listeners = null;

	protected ThreadGroup loadingThreadGroup = null;

	protected MessageReceiver receiver;

	private long sequenceNumber = 0L;

	protected SOManager sharedObjectManager = null;

	protected ThreadGroup sharedObjectThreadGroup = null;

	public SOContainer(ISharedObjectContainerConfig config) {
		if (config == null)
			throw new InstantiationError("config must not be null");
		this.config = config;
		groupManager = new SOContainerGMM(this, new Member(config.getID()));
		sharedObjectManager = new SOManager(this);
		loadingThreadGroup = makeLoadingThreadGroup();
		sharedObjectThreadGroup = getSharedObjectThreadGroup();
		listeners = new Vector();
		receiver = new MessageReceiver();
		debug("<init>");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#addListener(org.eclipse.ecf.core.ISharedObjectContainerListener,
	 *      java.lang.String)
	 */
	public void addListener(ISharedObjectContainerListener l, String filter) {
		synchronized (listeners) {
			listeners.add(new ContainerListener(l, filter));
		}
	}

	protected boolean addNewRemoteMember(ID memberID, Object data) {
		debug("addNewRemoteMember:" + memberID);
		return groupManager.addMember(new Member(memberID, data));
	}

	protected ISharedObject addSharedObject0(SharedObjectDescription sd,
			ISharedObject s) throws Exception {
		addSharedObjectWrapper(makeNewSharedObjectWrapper(sd, s));
		return s;
	}

	protected void addSharedObjectAndWait(SharedObjectDescription sd,
			ISharedObject s, ISharedObjectContainerTransaction t)
			throws Exception {
		if (sd.getID() == null || s == null) {
			throw new SharedObjectAddException(
					"Object id is null, or instance is null");
		}
		ISharedObject so = addSharedObject0(sd, s);
		// Wait right here until committed
		if (t != null)
			t.waitToCommit();
	}

	protected void addSharedObjectWrapper(SOWrapper wrapper) throws Exception {
		if (wrapper == null)
			return;
		ID id = wrapper.getObjID();
		synchronized (getGroupMembershipLock()) {
			Object obj = groupManager.getFromAny(id);
			if (obj != null) {
				throw new SharedObjectAddException("SharedObject with id "
						+ id.getName() + " already in container");
			}
			// Call initialize. If this throws it halts everything
			wrapper.init();
			// Put in table
			groupManager.addSharedObjectToActive(wrapper);
		}
	}

	protected boolean addToLoading(LoadingSharedObject lso) {
		return groupManager.addLoadingSharedObject(lso);
	}

	/**
	 * Check remote creation of shared objects. This method is called by the
	 * remote shared object creation message handler, to verify that the shared
	 * object from container 'fromID' to container 'toID' with description
	 * 'desc' is to be allowed to be created within the current container. If
	 * this method throws, a failure (and exception will be sent back to caller
	 * If this method returns null, the create message is ignored. If this
	 * method returns a non-null object, the creation is allowed to proceed. The
	 * default implementation is to return a non-null object
	 * 
	 * @param fromID
	 *            the ID of the container sending us this create request
	 * @param toID
	 *            the ID (or null) of the container intended to receive this
	 *            request
	 * @param seq
	 *            the sequence number associated with the container message
	 * @param desc
	 *            the SharedObjectDescription that describes the shared object
	 *            to be created
	 * 
	 * @return Object null if the create message is to be ignored, non-null if
	 *          the creation should continue
	 * 
	 * @throws Exception
	 *             may throw any Exception to communicate back (via
	 *             sendCreateResponse) to the sender that the creation has
	 *             failed
	 */
	protected Object checkRemoteCreate(ID fromID, ID toID, long seq,
			SharedObjectDescription desc) throws Exception {
		debug("checkRemoteCreate(" + fromID + "," + toID + "," + seq + ","
				+ desc + ")");
		return desc;
	}

	protected void debug(String msg) {
		if (Trace.ON && debug != null) {
			debug.msg(msg + ":" + config.getID());
		}
	}

	protected boolean destroySharedObject(ID sharedObjectID) {
		return groupManager.removeSharedObject(sharedObjectID);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#dispose(long)
	 */
	public void dispose(long waittime) {
		debug("dispose(" + waittime + ")");
		isClosing = true;
		// notify listeners
		fireContainerEvent(new SharedObjectContainerDisposeEvent(getID()));
		// Clear group manager
		if (groupManager != null) {
			groupManager.removeAllMembers();
			groupManager = null;
		}
		// Clear shared object manager
		if (sharedObjectManager != null) {
			sharedObjectManager.dispose();
			sharedObjectManager = null;
		}
		if (sharedObjectThreadGroup != null) {
			sharedObjectThreadGroup.interrupt();
			sharedObjectThreadGroup = null;
		}
		if (loadingThreadGroup != null) {
			loadingThreadGroup.interrupt();
			loadingThreadGroup = null;
		}
		if (listeners != null) {
			listeners.clear();
			listeners = null;
		}
	}

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

	protected void fireContainerEvent(IContainerEvent event) {
		synchronized (listeners) {
			for (Iterator i = listeners.iterator(); i.hasNext();) {
				ContainerListener l = (ContainerListener) i.next();
				l.handleEvent(event);
			}
		}
	}

	protected final void forward(ID fromID, ID toID, ContainerMessage data)
			throws IOException {
		if (toID == null) {
			forwardExcluding(fromID, fromID, data);
		} else {
			forwardToRemote(fromID, toID, data);
		}
	}

	abstract protected void forwardExcluding(ID from, ID excluding,
			ContainerMessage data) throws IOException;

	abstract protected void forwardToRemote(ID from, ID to,
			ContainerMessage data) throws IOException;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#getAdapter(java.lang.Class)
	 */
	public Object getAdapter(Class adapter) {
		return null;
	}

	/**
	 * @param sd
	 * @return Object []
	 */
	public Object[] getArgsFromProperties(SharedObjectDescription sd) {
		if (sd == null)
			return null;
		Map aMap = sd.getProperties();
		if (aMap == null)
			return null;
		Object obj = aMap.get(DEFAULT_OBJECT_ARG_KEY);
		if (obj == null)
			return null;
		if (obj instanceof Object[]) {
			Object[] ret = (Object[]) obj;
			aMap.remove(DEFAULT_OBJECT_ARG_KEY);
			return ret;
		} else
			return null;
	}

	/**
	 * @param sd
	 * @return String []
	 */
	public String[] getArgTypesFromProperties(SharedObjectDescription sd) {
		if (sd == null)
			return null;
		Map aMap = sd.getProperties();
		if (aMap == null)
			return null;
		Object obj = aMap.get(DEFAULT_OBJECT_ARGTYPES_KEY);
		if (obj == null)
			return null;
		if (obj instanceof String[]) {
			String[] ret = (String[]) obj;
			aMap.remove(DEFAULT_OBJECT_ARGTYPES_KEY);
			return ret;
		} else
			return null;
	}

	protected byte[] getBytesForObject(Serializable obj) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(obj);
		return bos.toByteArray();
	}

	protected ClassLoader getClassLoaderForContainer() {
		return this.getClass().getClassLoader();
	}

	/**
	 * @param sd
	 * @return ClassLoader
	 */
	protected ClassLoader getClassLoaderForSharedObject(
			SharedObjectDescription sd) {
		if (sd != null) {
			ClassLoader cl = sd.getClassLoader();
			if (cl != null)
				return cl;
			else
				return getClassLoaderForContainer();
		} else
			return getClassLoaderForContainer();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#getConfig()
	 */
	public ISharedObjectContainerConfig getConfig() {
		return config;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#getGroupID()
	 */
	public abstract ID getGroupID();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#getGroupMemberIDs()
	 */
	public ID[] getGroupMemberIDs() {
		return groupManager.getMemberIDs();
	}

	protected Object getGroupMembershipLock() {
		return groupManager;
	}

	public ID getID() {
		return config.getID();
	}

	protected int getMaxGroupMembers() {
		return groupManager.getMaxMembers();
	}

	protected Thread getNewSharedObjectThread(ID sharedObjectID,
			Runnable runnable) {
		return new Thread(sharedObjectThreadGroup, runnable, sharedObjectID
				.getName()
				+ ":run");
	}

	protected long getNextSequenceNumber() {
		if (sequenceNumber == Long.MAX_VALUE) {
			sequenceNumber = 0;
			return sequenceNumber;
		} else
			return sequenceNumber++;
	}

	protected ContainerMessage getObjectFromBytes(byte[] bytes)
			throws IOException {
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = new ObjectInputStream(bis);
		Object obj = null;
		try {
			obj = ois.readObject();
		} catch (ClassNotFoundException e) {
			dumpStack("class not found for message", e);
			return null;
		}
		if (obj instanceof ContainerMessage) {
			return (ContainerMessage) obj;
		} else {
			debug("message received is not containermessage:" + obj);
			return null;
		}
	}

	protected IOSGIService getOSGIServiceInterface() {
		return null;
	}

	public ID[] getOtherMemberIDs() {
		return groupManager.getOtherMemberIDs();
	}

	protected ISynchAsynchConnectionEventHandler getReceiver() {
		return receiver;
	}

	protected ISharedObject getSharedObject(ID id) {
		SOWrapper wrap = getSharedObjectWrapper(id);
		if (wrap == null)
			return null;
		else
			return wrap.getSharedObject();
	}

	protected ID[] getSharedObjectIDs() {
		return groupManager.getSharedObjectIDs();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#getSharedObjectManager()
	 */
	public ISharedObjectManager getSharedObjectManager() {
		return sharedObjectManager;
	}

	protected ThreadGroup getSharedObjectThreadGroup() {
		return new ThreadGroup(getID() + ":SOs");
	}

	protected SOWrapper getSharedObjectWrapper(ID id) {
		return groupManager.getFromActive(id);
	}

	protected void handleAsynchIOException(IOException except,
			AsynchConnectionEvent e) {
		// If we get IO Exception, we'll disconnect...if we can
		killConnection(e.getConnection());
	}

	protected void handleCreateMessage(ContainerMessage mess)
			throws IOException {
		debug("handleCreateMessage:" + mess);
		ContainerMessage.CreateMessage create = (ContainerMessage.CreateMessage) mess
				.getData();
		SharedObjectDescription desc = (SharedObjectDescription) create
				.getData();
		ID fromID = mess.getFromContainerID();
		ID toID = mess.getToContainerID();
		long seq = mess.getSequence();
		Object checkCreateResult = null;
		ID sharedObjectID = desc.getID();
		// Check to make sure that the remote creation is allowed.
		// If this method throws, a failure (and exception will be sent back to
		// caller
		// If this method returns null, the create message is ignored. If this
		// method
		// returns a non-null object, the creation is allowed to proceed
		try {
			checkCreateResult = checkRemoteCreate(fromID, toID, seq, desc);
		} catch (Exception e) {
			SharedObjectAddException addException = new SharedObjectAddException(
					"shared object " + sharedObjectID
							+ " rejected by container " + getID(), e);
			dumpStack("Exception in checkRemoteCreate", addException);
			try {
				sendCreateResponse(fromID, sharedObjectID, addException, desc
						.getIdentifier());
			} catch (IOException except) {
				logException(
						"Exception from sendCreateResponse in handleCreateResponse",
						except);
			}
			return;
		}
		// Then if result from check is non-null, we continue. If null, we
		// ignore
		if (checkCreateResult != null) {
			LoadingSharedObject lso = new LoadingSharedObject(fromID, desc,
					checkCreateResult);
			synchronized (getGroupMembershipLock()) {
				if (!addToLoading(lso)) {
					try {
						sendCreateResponse(fromID, sharedObjectID,
								new SharedObjectAddException("shared object "
										+ sharedObjectID
										+ " already exists in container "
										+ getID()), desc.getIdentifier());
					} catch (IOException e) {
						logException(
								"Exception in handleCreateMessage.sendCreateResponse",
								e);
					}
				}
				forward(fromID, toID, mess);
				return;
			}
		}
		synchronized (getGroupMembershipLock()) {
			forward(fromID, toID, mess);
		}
	}

	protected void handleCreateResponseMessage(ContainerMessage mess)
			throws IOException {
		debug("handleCreateResponseMessage:" + mess);
		ID fromID = mess.getFromContainerID();
		ID toID = mess.getToContainerID();
		long seq = mess.getSequence();
		ContainerMessage.CreateResponseMessage resp = (ContainerMessage.CreateResponseMessage) mess
				.getData();
		if (toID != null && toID.equals(getID())) {
			ID sharedObjectID = resp.getSharedObjectID();
			SOWrapper sow = getSharedObjectWrapper(sharedObjectID);
			if (sow != null) {
				sow.deliverCreateResponse(fromID, resp);
			} else {
				log("handleCreateResponseMessage...wrapper not found for "
						+ sharedObjectID);
			}
		} else {
			forwardToRemote(fromID, toID, mess);
		}
	}

	/**
	 * @param mess
	 */
	protected abstract void handleLeaveGroupMessage(ContainerMessage mess);

	protected void handleSharedObjectDisposeMessage(ContainerMessage mess)
			throws IOException {
		debug("handleSharedObjectDisposeMessage:" + mess);
		ID fromID = mess.getFromContainerID();
		ID toID = mess.getToContainerID();
		long seq = mess.getSequence();
		ContainerMessage.SharedObjectDisposeMessage resp = (ContainerMessage.SharedObjectDisposeMessage) mess
				.getData();
		ID sharedObjectID = resp.getSharedObjectID();
		synchronized (getGroupMembershipLock()) {
			if (groupManager.isLoading(sharedObjectID)) {
				groupManager.removeSharedObjectFromLoading(sharedObjectID);
			} else {
				groupManager.removeSharedObject(sharedObjectID);
			}
			forward(fromID, toID, mess);
		}
	}

	protected void handleSharedObjectMessage(ContainerMessage mess)
			throws IOException {
		debug("handleSharedObjectMessage:" + mess);
		ID fromID = mess.getFromContainerID();
		ID toID = mess.getToContainerID();
		long seq = mess.getSequence();
		ContainerMessage.SharedObjectMessage resp = (ContainerMessage.SharedObjectMessage) mess
				.getData();
		synchronized (getGroupMembershipLock()) {
			if (toID == null || toID.equals(getID())) {
				SOWrapper sow = getSharedObjectWrapper(resp
						.getFromSharedObjectID());
				if (sow != null) {
					sow.deliverSharedObjectMessage(fromID, resp.getData());
				}
			}
			forward(fromID, toID, mess);
		}
	}

	protected void handleUnidentifiedMessage(ContainerMessage mess)
			throws IOException {
		// do nothing
	}

	protected abstract void handleViewChangeMessage(ContainerMessage mess)
			throws IOException;

	protected boolean isClosing() {
		return isClosing;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#isGroupManager()
	 */
	public abstract boolean isGroupManager();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#isGroupServer()
	 */
	public abstract boolean isGroupServer();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#joinGroup(org.eclipse.ecf.core.identity.ID,
	 *      java.lang.Object)
	 */
	public abstract void joinGroup(ID groupID, Object loginData)
			throws SharedObjectContainerJoinException;

	protected void killConnection(IConnection conn) {
		debug("killconnection");
		try {
			if (conn != null)
				conn.disconnect();
		} catch (IOException e) {
			logException("Exception in killConnection", e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#leaveGroup()
	 */
	public abstract void leaveGroup();

	protected ISharedObject load(SharedObjectDescription sd) throws Exception {
		return sharedObjectManager.loadSharedObject(sd);
	}

	protected void log(String msg) {
		debug(msg);
	}

	protected void logException(String msg, Throwable e) {
		dumpStack(msg, e);
	}

	protected ThreadGroup makeLoadingThreadGroup() {
		return new ThreadGroup(getID() + ":load");
	}

	protected SOConfig makeNewSharedObjectConfig(SharedObjectDescription sd,
			ISharedObject obj) {
		ID homeID = sd.getHomeID();
		if (homeID == null)
			homeID = getID();
		return new SOConfig(sd.getID(), homeID, this, sd.getProperties());
	}

	protected SOConfig makeNewRemoteSharedObjectConfig(ID fromID,
			SharedObjectDescription sd, ISharedObject obj) {
		ID homeID = sd.getHomeID();
		if (homeID == null)
			homeID = fromID;
		return new SOConfig(sd.getID(), homeID, this, sd.getProperties());
	}

	protected SOContext makeNewSharedObjectContext(SOConfig config,
			QueueEnqueue queue) {
		return new SOContext(config.getSharedObjectID(), config
				.getHomeContainerID(), this, config.getProperties(), queue);
	}

	protected SOContext makeNewRemoteSharedObjectContext(SOConfig config,
			QueueEnqueue queue) {
		return new SOContext(config.getSharedObjectID(), config
				.getHomeContainerID(), this, config.getProperties(), queue);
	}

	protected SOWrapper makeNewSharedObjectWrapper(SharedObjectDescription sd,
			ISharedObject s) {
		SOConfig newConfig = makeNewSharedObjectConfig(sd, s);
		return new SOWrapper(newConfig, s, this);
	}

	protected SOWrapper makeNewRemoteSharedObjectWrapper(ID fromID,
			SharedObjectDescription sd, ISharedObject s) {
		SOConfig newConfig = makeNewRemoteSharedObjectConfig(fromID, sd, s);
		return new SOWrapper(newConfig, s, this);
	}

	protected void memberLeave(ID target, IConnection conn) {
		debug("memberLeave:" + target + ":" + conn);
		if (target == null)
			return;
		if (groupManager.removeMember(target)) {
			try {
				forwardExcluding(getID(), target, ContainerMessage
						.makeViewChangeMessage(getID(), null,
								getNextSequenceNumber(), new ID[] { target },
								false, null));
			} catch (IOException e) {
				logException("Exception in memberLeave.forwardExcluding", e);
			}
		}
		if (conn != null)
			killConnection(conn);
	}

	protected void moveFromLoadingToActive(SOWrapper wrap) {
		groupManager.moveSharedObjectFromLoadingToActive(wrap);
	}

	protected void notifySharedObjectActivated(ID sharedObjectID) {
		groupManager.notifyOthersActivated(sharedObjectID);
	}

	protected void notifySharedObjectDeactivated(ID sharedObjectID) {
		groupManager.notifyOthersDeactivated(sharedObjectID);
	}

	protected ContainerMessage validateContainerMessage(Object mess) {
		// Message must not be null
		if (mess == null) {
			debug("Ignoring null ContainerMessage");
			return null;
		}
		if (mess instanceof ContainerMessage) {
			ContainerMessage contmess = (ContainerMessage) mess;
			ID fromID = contmess.getFromContainerID();
			if (fromID == null) {
				debug("Ignoring ContainerMessage from null sender...ignoring");
				return null;
			}
			ID toID = contmess.getToContainerID();
			if (toID == null) {
				return contmess;
			} else {
				if (toID.equals(getID())) {
					return contmess;
				} else {
					debug("Ignoring ContainerMessage from " + fromID + " to "
							+ toID);
					return null;
				}
			}
			// OK
		} else {
			debug("Ignoring invalid ContainerMessage:" + mess);
			return null;
		}

	}

	protected void processAsynch(AsynchConnectionEvent e) {
		try {
			Object obj = e.getData();
			if (obj == null) {
				debug("Ignoring null data in event " + e);
				return;
			}
			if (!(obj instanceof byte[])) {
				debug("Ignoring event without valid data " + e);
			}
			ContainerMessage mess = validateContainerMessage(getObjectFromBytes((byte[]) obj));
			if (mess == null) {
				return;
			}
			Serializable submess = mess.getData();
			if (submess != null) {
				if (submess instanceof ContainerMessage.CreateMessage) {
					handleCreateMessage(mess);
				} else if (submess instanceof ContainerMessage.CreateResponseMessage) {
					handleCreateResponseMessage(mess);
				} else if (submess instanceof ContainerMessage.SharedObjectDisposeMessage) {
					handleSharedObjectDisposeMessage(mess);
				} else if (submess instanceof ContainerMessage.SharedObjectMessage) {
					handleSharedObjectMessage(mess);
				} else if (submess instanceof ContainerMessage.ViewChangeMessage) {
					handleViewChangeMessage(mess);
				} else {
					handleUnidentifiedMessage(mess);
				}
			} else {
				handleUnidentifiedMessage(mess);
			}
		} catch (IOException except) {
			handleAsynchIOException(except, e);
		}
	}

	protected void processDisconnect(DisconnectConnectionEvent e) {
		debug("processDisconnect:" + e);
		try {
			ContainerMessage mess = getObjectFromBytes((byte[]) e.getData());
		} catch (Exception except) {
			logException("Exception in processDisconnect ", except);
		}
	}

	protected Serializable processSynch(SynchConnectionEvent e)
			throws IOException {
		debug("processSynch:" + e);
		ContainerMessage mess = getObjectFromBytes((byte[]) e.getData());
		Serializable data = mess.getData();
		// Must be non null
		if (data != null && data instanceof ContainerMessage.LeaveGroupMessage) {
			handleLeaveGroupMessage(mess);
		}
		return null;
	}

	abstract protected void queueContainerMessage(ContainerMessage mess)
			throws IOException;

	protected void removeFromLoading(ID id) {
		groupManager.removeSharedObjectFromLoading(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.ISharedObjectContainer#removeListener(org.eclipse.ecf.core.ISharedObjectContainerListener)
	 */
	public void removeListener(ISharedObjectContainerListener l) {
		synchronized (listeners) {
			for (Enumeration e = listeners.elements(); e.hasMoreElements();) {
				ContainerListener list = (ContainerListener) e.nextElement();
				if (list.isListener(l)) {
					// found it...so remove
					listeners.remove(list);
				}
			}
		}
	}

	protected boolean removeRemoteMember(ID remoteMember) {
		return groupManager.removeMember(remoteMember);
	}

	protected ISharedObject removeSharedObject(ID id) {
		synchronized (getGroupMembershipLock()) {
			SOWrapper wrap = groupManager.getFromActive(id);
			if (wrap == null)
				return null;
			groupManager.removeSharedObject(id);
			return wrap.getSharedObject();
		}
	}

	protected void sendCreate(ID sharedObjectID, ID toContainerID,
			SharedObjectDescription sd) throws IOException {
		sendCreateSharedObjectMessage(toContainerID, sd);
	}

	protected void sendCreateResponse(ID homeID, ID sharedObjectID,
			Throwable t, long identifier) throws IOException {
		sendCreateResponseSharedObjectMessage(homeID, sharedObjectID, t,
				identifier);
	}

	protected void sendCreateResponseSharedObjectMessage(ID toContainerID,
			ID fromSharedObject, Throwable t, long ident) throws IOException {
		sendMessage(ContainerMessage.makeSharedObjectCreateResponseMessage(
				getID(), toContainerID, getNextSequenceNumber(),
				fromSharedObject, t, ident));
	}

	protected ID[] sendCreateSharedObjectMessage(ID toContainerID,
			SharedObjectDescription sd) throws IOException {
		ID[] returnIDs = null;
		if (toContainerID == null) {
			synchronized (getGroupMembershipLock()) {
				// Send message to all
				sendMessage(ContainerMessage.makeSharedObjectCreateMessage(
						getID(), toContainerID, getNextSequenceNumber(), sd));
				returnIDs = getOtherMemberIDs();
			}
		} else {
			// If the create msg is directed to this space, no msg will be sent
			if (getID().equals(toContainerID)) {
				returnIDs = new ID[0];
			} else {
				sendMessage(ContainerMessage.makeSharedObjectCreateMessage(
						getID(), toContainerID, getNextSequenceNumber(), sd));
				returnIDs = new ID[1];
				returnIDs[0] = toContainerID;
			}
		}
		return returnIDs;
	}

	protected void sendDispose(ID toContainerID, ID sharedObjectID)
			throws IOException {
		sendDisposeSharedObjectMessage(toContainerID, sharedObjectID);
	}

	protected void sendDisposeSharedObjectMessage(ID toContainerID,
			ID fromSharedObject) throws IOException {
		sendMessage(ContainerMessage.makeSharedObjectDisposeMessage(getID(),
				toContainerID, getNextSequenceNumber(), fromSharedObject));
	}

	protected void sendMessage(ContainerMessage data) throws IOException {
		synchronized (getGroupMembershipLock()) {
			ID ourID = getID();
			// We don't send to ourselves
			if (!ourID.equals(data.getToContainerID())) {
				debug("sendcontainermessage:" + data);
				queueContainerMessage(data);
			}
		}
	}

	protected void sendMessage(ID toContainerID, ID sharedObjectID,
			Object message) throws IOException {
		if (message == null)
			return;
		sendSharedObjectMessage(toContainerID, sharedObjectID,
				(Serializable) message);
	}

	protected void sendSharedObjectMessage(ID toContainerID,
			ID fromSharedObject, Serializable data) throws IOException {
		sendMessage(ContainerMessage.makeSharedObjectMessage(getID(),
				toContainerID, getNextSequenceNumber(), fromSharedObject, data));
	}

	protected void setIsClosing() {
		isClosing = true;
	}

	protected void setMaxGroupMembers(int max) {
		groupManager.setMaxMembers(max);
	}
}

Back to the top