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
|
/****************************************************************************
* 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.example.collab.share.io;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.sharedobject.ISharedObjectConfig;
import org.eclipse.ecf.core.sharedobject.ReplicaSharedObjectDescription;
import org.eclipse.ecf.core.sharedobject.SharedObjectInitException;
import org.eclipse.ecf.example.collab.share.SharedObjectMsg;
import org.eclipse.ecf.example.collab.share.TransactionSharedObject;
import org.eclipse.osgi.util.NLS;
public class FileTransferSharedObject extends TransactionSharedObject {
public static final int DEFAULT_START_WAIT_INTERVAL = 5000;
private static final String HANDLEDATA_MSG = "handleData";
private static final String HANDLEDONE_MSG = "handleDone";
private static final String STARTSENDTOALL_MSG = "startSendToAll";
private static final String START_MSG = "start";
// Both host and container
protected FileTransferParams transferParams;
protected FileTransferListener progressListener;
// Host only
protected ID targetReceiver;
protected InputStream inputStream;
// Client only
protected OutputStream outputStream;
protected long dataWritten = -1;
public FileTransferSharedObject(InputStream ins, FileTransferParams params) {
this(null, ins, params);
}
public FileTransferSharedObject(InputStream ins) {
this(null, ins, null);
}
public FileTransferSharedObject(FileTransferParams params) {
if (params == null) {
transferParams = new FileTransferParams();
} else
transferParams = params;
progressListener = transferParams.getProgressListener();
}
public FileTransferSharedObject(ID receiver, InputStream ins,
FileTransferParams params) {
targetReceiver = receiver;
Assert.isNotNull(ins);
if (ins == null)
throw new NullPointerException("Input stream cannot be null");
setInputStream(ins);
transferParams = (params == null) ? new FileTransferParams() : params;
progressListener = transferParams.getProgressListener();
}
public FileTransferSharedObject() {
super();
}
protected void setInputStream(InputStream src) {
inputStream = src;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ecf.example.collab.share.TransactionSharedObject#addRemoteParticipants(org.eclipse.ecf.core.identity.ID[])
*/
protected void addRemoteParticipants(ID ids[]) {
if (ids != null && participantIDs != null) {
for (int i = 0; i < ids.length; i++) {
if (targetReceiver == null) {
if (!getHomeContainerID().equals(ids[i]))
participantIDs.addElement(ids[i]);
} else {
if (targetReceiver.equals(ids[i]))
participantIDs.addElement(ids[i]);
}
}
}
}
protected void setOutputStream(OutputStream src) {
outputStream = src;
}
public void activated(ID[] others) {
try {
// Only try to open output file if this is not the host instance
if (!isHost() && !getContext().isGroupManager()) {
// Then notify listener about starting the receive
if (progressListener != null)
progressListener.receiveStart(this, transferParams
.getRemoteFile(), transferParams.getLength(),
transferParams.getRate());
// Open output file
openOutputFile();
if (transferParams.getLength() != -1)
dataWritten = 0;
} else {
// Just notify listener (if any) about the sending
if (progressListener != null)
progressListener.sendStart(this,
transferParams.getLength(), transferParams
.getRate());
}
} catch (Exception e) {
try {
// Respond with create failure message back to host
getContext().sendCreateResponse(getHomeContainerID(), e,
getNextReplicateID());
} catch (Exception e1) {
log("Exception sending failure back to host", e1);
}
return;
}
// Finally, call activated to report success
super.activated(others);
}
protected void openOutputFile() throws IOException {
File aFile = transferParams.getRemoteFile();
if (aFile == null)
throw new IOException("Remote file is null");
// If this is a server, and we shouldn't create a copy of ourselves on a
// server
// then we skip the file creation totally
if (getContext().isGroupManager() && !transferParams.getIncludeServer()) {
// Set myFile to null and outputStream to null
setOutputStream(null);
} else {
try {
String parent = aFile.getParent();
if (parent != null && new File(parent).mkdirs())
/**/;
} catch (Exception ex) {
// Log this exception.
log(NLS.bind("Exception creating local directory for ", aFile),
ex);
}
setOutputStream(new BufferedOutputStream(
new FileOutputStream(aFile)));
}
}
protected void replicate(ID remoteMember) {
// If we don't have a specific receiver, simply allow superclass to
// handle replication.
if (targetReceiver == null) {
super.replicate(remoteMember);
return;
}
// If we do have a specific receiver, only send create message to the
// specific receiver
// if we're replicating on activation
else if (remoteMember == null) {
try {
ReplicaSharedObjectDescription createInfo = getReplicaDescription(targetReceiver);
if (createInfo != null) {
getContext().sendCreate(targetReceiver, createInfo);
return;
}
} catch (IOException e) {
log("Could not send createFail message", e);
}
}
}
public void init(ISharedObjectConfig config)
throws SharedObjectInitException {
super.init(config);
Map map = config.getProperties();
Object[] args = (Object[]) map.get(ARGS_PROPERTY_NAME);
if (args != null && args.length == 1) {
transferParams = (FileTransferParams) args[0];
progressListener = transferParams.getProgressListener();
}
}
protected ReplicaSharedObjectDescription getReplicaDescription(
ID remoteMember) {
HashMap map = new HashMap();
map.put(ARGS_PROPERTY_NAME, new Object[] { transferParams });
return new ReplicaSharedObjectDescription(getClass(), getID(),
getConfig().getHomeContainerID(), map, getNextReplicateID());
}
protected boolean sendData(ID rcvr, FileData data) throws IOException {
// Send it. This does all data delivery.
forwardMsgTo(rcvr, SharedObjectMsg.createMsg(HANDLEDATA_MSG, data));
return data.isDone();
}
protected boolean sendChunk(ID rcvr) throws IOException {
FileData data = new FileData(inputStream, transferParams.getChunkSize());
int size = data.getDataSize();
if (progressListener != null && size != -1)
progressListener.sendData(this, size);
return sendData(rcvr, data);
}
protected void handleData(FileData data) {
preSaveData(data);
// Then save the file data.
int size = data.getDataSize();
if (progressListener != null && size != -1)
progressListener.receiveData(this, size);
saveData(data);
}
protected void preSaveData(FileData data) {
}
/**
* Save data to File. This method is called by handleData to actually save
* data received (on the clients only) to the appropriate file.
*
* @param data
* the FileData to save
*/
protected void saveData(FileData data) {
// Save data locally...if we have an output stream
try {
if (outputStream != null) {
long len = transferParams.getLength();
dataWritten += data.getDataSize();
if (len != -1 && dataWritten > len)
throw new IOException("File larger than " + len);
data.saveData(outputStream);
// Flush to verify that data was saved.
outputStream.flush();
}
} catch (Exception e) {
// Give subclasses opportunity to deal with this
notifyExceptionOnSave(e);
// Report failure back to host if we're not disconnected
try {
// Send it. This does the done msg delivery.
forwardMsgHome(SharedObjectMsg.createMsg(HANDLEDONE_MSG, e));
// Make sure everything is cleaned up
hardClose();
} catch (Exception e1) {
// If this fails...then we should be outta here
log("Exception sending done msg back to host", e1);
}
if (progressListener != null)
progressListener.receiveDone(this, e);
return;
}
Exception except = null;
// If everything saved OK, and that was the last piece, then close
// and report success.
if (data.isDone()) {
try {
// Make sure everything is cleaned up
hardClose();
} catch (Exception e1) {
// If this fails...then we should be outta here
except = e1;
notifyExceptionOnClose(except);
}
// Calling the progress listener first, so that the reference
// to ourselves will be valid even if doneReceiving kills this
// object
if (progressListener != null)
progressListener.receiveDone(this, except);
try {
forwardMsgHome(SharedObjectMsg
.createMsg(HANDLEDONE_MSG, except));
} catch (Exception e) {
log("Exception sending done message home", e);
}
// Now call doneReceiving...which may destroy us
doneReceiving();
}
}
protected void notifyExceptionOnSave(Throwable t) {
// By default, do nothing
}
protected void notifyExceptionOnClose(Throwable t) {
// By default, do nothing
}
public void doneReceiving() {
}
/**
* Handler for done msg. NOTE: If this method name is changed, then the
* static variable 'HANDLEDONE_MSG' should be changed to match.
*
* @param e
* the Exception involved in the failure
*/
public void handleDone(Exception e) {
}
protected void preStartWaiting() {
}
protected void preStartSending() {
}
protected void preChunkSent() {
}
protected void chunkSent() {
}
protected void doneSending(Exception e) {
if (progressListener != null)
progressListener.sendDone(this, e);
}
protected void committed() {
preStartWaiting();
start();
}
protected void preWait() {
}
protected void start() {
if (isHost()) {
Date start = transferParams.getStartDate();
if (start != null && start.after(new Date())) {
try {
preWait();
synchronized (this) {
wait(DEFAULT_START_WAIT_INTERVAL);
}
// Asynchronous tail recursion.
sendSelf(SharedObjectMsg.createMsg(START_MSG));
} catch (Exception e) {
}
} else {
preStartSending();
// Actually begin
startSendToAll();
}
}
}
/**
* Start sending data to all clients. This is the entry point method for
* sending the desired data to remotes.
*/
protected void startSendToAll() {
// Send chunks to all remotes until done.
try {
// Call subclass overrideable method before sending chunk
preChunkSent();
// Send chunk
boolean res = sendChunk(targetReceiver);
// Call subclass overrideable method after sending chunk
chunkSent();
if (!res) {
synchronized (this) {
int waittime = transferParams.getWaitTime();
if (waittime <= 0)
waittime = 10;
wait(waittime);
}
// If all data not sent, send message to self. This results
// in this method iterating until entire file is sent.
sendSelf(SharedObjectMsg.createMsg(STARTSENDTOALL_MSG));
} else {
// Close input stream.
hardClose();
doneSending(null);
}
} catch (Exception e) {
doneSending(e);
}
}
protected void hardClose() throws IOException {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
inputStream = null;
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
}
outputStream = null;
}
}
public void deactivated() {
super.deactivated();
// Make sure things are cleaned up properly in case of wrong trousers
try {
hardClose();
} catch (Exception e) {
}
}
}
|