Skip to main content
summaryrefslogtreecommitdiffstats
blob: 41f90661ea1b2bedad146b563ca2a9b65a40663f (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
/*******************************************************************************
 * Copyright (c) 2004, 2010 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
 *    Benjamin Cabe <benjamin.cabe@anyware-tech.com> - bug 220258
 *    Henrich Kraemer - bug 295030, Update Manager doesn't work with SOCKS proxy  
 ******************************************************************************/
package org.eclipse.ecf.provider.filetransfer.retrieve;

import org.eclipse.ecf.provider.filetransfer.util.ProxySetupHelper;

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.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Map;
import org.eclipse.core.net.proxy.IProxyData;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.identity.IDFactory;
import org.eclipse.ecf.core.identity.Namespace;
import org.eclipse.ecf.core.security.IConnectContext;
import org.eclipse.ecf.core.util.Proxy;
import org.eclipse.ecf.filetransfer.FileTransferJob;
import org.eclipse.ecf.filetransfer.IFileRangeSpecification;
import org.eclipse.ecf.filetransfer.IFileTransferListener;
import org.eclipse.ecf.filetransfer.IFileTransferPausable;
import org.eclipse.ecf.filetransfer.IFileTransferRunnable;
import org.eclipse.ecf.filetransfer.IIncomingFileTransfer;
import org.eclipse.ecf.filetransfer.IRetrieveFileTransferOptions;
import org.eclipse.ecf.filetransfer.IncomingFileTransferException;
import org.eclipse.ecf.filetransfer.UserCancelledException;
import org.eclipse.ecf.filetransfer.events.IIncomingFileTransferReceiveDataEvent;
import org.eclipse.ecf.filetransfer.events.IIncomingFileTransferReceiveDoneEvent;
import org.eclipse.ecf.filetransfer.events.IIncomingFileTransferReceivePausedEvent;
import org.eclipse.ecf.filetransfer.events.IIncomingFileTransferReceiveResumedEvent;
import org.eclipse.ecf.filetransfer.events.IIncomingFileTransferReceiveStartEvent;
import org.eclipse.ecf.filetransfer.identity.IFileID;
import org.eclipse.ecf.filetransfer.service.IRetrieveFileTransfer;
import org.eclipse.ecf.internal.provider.filetransfer.Activator;
import org.eclipse.ecf.internal.provider.filetransfer.Messages;
import org.eclipse.ecf.provider.filetransfer.identity.FileTransferNamespace;
import org.eclipse.ecf.provider.filetransfer.util.PollingInputStream;
import org.eclipse.ecf.provider.filetransfer.util.TimeoutInputStream;
import org.eclipse.osgi.util.NLS;

public abstract class AbstractRetrieveFileTransfer implements IIncomingFileTransfer, IRetrieveFileTransfer, IFileTransferPausable {

	public static final int DEFAULT_BUF_LENGTH = 4096;

	protected static final int POLLING_RETRY_ATTEMPTS = new Integer(System.getProperty("org.eclipse.ecf.provider.filetransfer.retrieve.retryAttempts", "20")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$;;

	protected static final int TIMEOUT_INPUTSTREAM_BUFFER_SIZE = 8192;

	protected static final int READ_TIMEOUT = new Integer(System.getProperty("org.eclipse.ecf.provider.filetransfer.retrieve.readTimeout", "1000")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$;

	protected static final int CLOSE_TIMEOUT = new Integer(System.getProperty("org.eclipse.ecf.provider.filetransfer.retrieve.closeTimeout", "1000")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$;

	protected Object jobLock = new Object();
	protected Job job;

	protected URL remoteFileURL;

	protected IFileID remoteFileID;

	protected IFileTransferListener listener;

	protected int buff_length = DEFAULT_BUF_LENGTH;

	protected boolean done = false;

	protected volatile long bytesReceived = 0;

	protected InputStream remoteFileContents;

	protected OutputStream localFileContents;

	protected boolean closeOutputStream = true;

	protected Exception exception;

	protected long fileLength = -1;

	protected long lastModifiedTime = 0L;

	protected Map options = null;

	protected boolean paused = false;

	protected IFileRangeSpecification rangeSpecification = null;

	protected Proxy proxy;

	protected IConnectContext connectContext;

	protected long transferStartTime;

	protected double downloadRateBytesPerSecond = 0L;

	/**
	 * @since 3.1
	 */
	protected Map responseHeaders;

	public AbstractRetrieveFileTransfer() {
		//
	}

	protected InputStream wrapTransferReadInputStream(InputStream inputStream, IProgressMonitor monitor) {
		return new PollingInputStream(remoteFileContents, getRetryAttempts(), monitor);
	}

	private int getRetryAttempts() {
		int result = POLLING_RETRY_ATTEMPTS;
		Map localOptions = getOptions();
		if (localOptions != null) {
			// See if the property is present, if so set
			Object o = localOptions.get("org.eclipse.ecf.provider.filetransfer.retrieve.retryAttempts"); //$NON-NLS-1$
			if (o != null) {
				if (o instanceof Integer) {
					result = ((Integer) o).intValue();
				} else if (o instanceof String) {
					result = new Integer(((String) o)).intValue();
				}
			}
		}
		return result;
	}

	private IFileTransferRunnable fileTransferRunnable = new IFileTransferRunnable() {
		public IStatus performFileTransfer(IProgressMonitor monitor) {
			transferStartTime = System.currentTimeMillis();
			final byte[] buf = new byte[buff_length];
			final long totalWork = ((fileLength == -1) ? 100 : fileLength);
			double factor = (totalWork > Integer.MAX_VALUE) ? (((double) Integer.MAX_VALUE) / ((double) totalWork)) : 1.0;
			int work = (totalWork > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) totalWork;
			monitor.beginTask(getRemoteFileURL().toString() + Messages.AbstractRetrieveFileTransfer_Progress_Data, work);
			InputStream readInputStream = wrapTransferReadInputStream(remoteFileContents, monitor);
			try {
				while (!isDone() && !isPaused()) {
					try {
						final int bytes = readInputStream.read(buf);
						handleReceivedData(buf, bytes, factor, monitor);
					} catch (OperationCanceledException e) {
						throw new UserCancelledException(Messages.AbstractRetrieveFileTransfer_Exception_User_Cancelled);
					}
				}
			} catch (final Exception e) {
				if (!isDone()) {
					setDoneException(e);
				}
			} finally {
				try {
					if (readInputStream != null)
						readInputStream.close();
				} catch (final IOException e) {
					Activator a = Activator.getDefault();
					if (a != null)
						a.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, "hardClose", e)); //$NON-NLS-1$
				}
				hardClose();
				monitor.done();
				try {
					if (isPaused())
						fireTransferReceivePausedEvent();
					else
						fireTransferReceiveDoneEvent();
				} catch (Exception e) {
					// simply log
					Activator a = Activator.getDefault();
					if (a != null)
						a.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.AbstractRetrieveFileTransfer_EXCEPTION_IN_FINALLY, e));
				}
			}
			return getFinalStatus(exception);
		}

	};

	protected URL getRemoteFileURL() {
		return remoteFileURL;
	}

	protected int getSocketReadTimeout() {
		int result = READ_TIMEOUT;
		Map localOptions = getOptions();
		if (localOptions != null) {
			// See if the connect timeout option is present, if so set
			Object o = localOptions.get(IRetrieveFileTransferOptions.READ_TIMEOUT);
			if (o != null) {
				if (o instanceof Integer) {
					result = ((Integer) o).intValue();
				} else if (o instanceof String) {
					result = new Integer(((String) o)).intValue();
				}
				return result;
			}
			o = localOptions.get("org.eclipse.ecf.provider.filetransfer.httpclient.retrieve.readTimeout"); //$NON-NLS-1$
			if (o != null) {
				if (o instanceof Integer) {
					result = ((Integer) o).intValue();
				} else if (o instanceof String) {
					result = new Integer(((String) o)).intValue();
				}
			}
		}
		return result;
	}

	protected int getSocketCloseTimeout() {
		int result = CLOSE_TIMEOUT;
		Map localOptions = getOptions();
		if (localOptions != null) {
			// See if the property is present, if so set
			Object o = localOptions.get("org.eclipse.ecf.provider.filetransfer.retrieve.closeTimeout"); //$NON-NLS-1$
			if (o != null) {
				if (o instanceof Integer) {
					result = ((Integer) o).intValue();
				} else if (o instanceof String) {
					result = new Integer(((String) o)).intValue();
				}
			}
		}
		return result;
	}

	protected void setInputStream(InputStream ins) {
		remoteFileContents = new TimeoutInputStream(ins, TIMEOUT_INPUTSTREAM_BUFFER_SIZE, getSocketReadTimeout(), getSocketCloseTimeout());
	}

	protected void setOutputStream(OutputStream outs) {
		localFileContents = outs;
	}

	protected void setCloseOutputStream(boolean close) {
		closeOutputStream = close;
	}

	protected void setFileLength(long length) {
		fileLength = length;
	}

	protected void setLastModifiedTime(long timestamp) {
		lastModifiedTime = timestamp;
	}

	protected Map getOptions() {
		return options;
	}

	protected synchronized void handleReceivedData(byte[] buf, int bytes, double factor, IProgressMonitor monitor) throws IOException {
		if (bytes != -1) {
			bytesReceived += bytes;
			localFileContents.write(buf, 0, bytes);
			downloadRateBytesPerSecond = (bytesReceived / ((System.currentTimeMillis() + 1 - transferStartTime) / 1000.0));
			monitor.setTaskName(createJobName() + Messages.AbstractRetrieveFileTransfer_Progress_Data + NLS.bind(Messages.AbstractRetrieveFileTransfer_InfoTransferRate, toHumanReadableBytes(downloadRateBytesPerSecond)));
			monitor.worked((int) Math.round(factor * bytes));
			fireTransferReceiveDataEvent();
		} else
			setDone(true);
	}

	public static String toHumanReadableBytes(double size) {
		double convertedSize;
		String unit;

		if (size / (1024 * 1024 * 1024) >= 1) {
			convertedSize = size / (1024 * 1024 * 1024);
			unit = Messages.AbstractRetrieveFileTransfer_SizeUnitGB;
		} else if (size / (1024 * 1024) >= 1) {
			convertedSize = size / (1024 * 1024);
			unit = Messages.AbstractRetrieveFileTransfer_SizeUnitMB;
		} else if (size / 1024 >= 1) {
			convertedSize = size / 1024;
			unit = Messages.AbstractRetrieveFileTransfer_SizeUnitKB;
		} else {
			convertedSize = size;
			unit = Messages.AbstractRetrieveFileTransfer_SizeUnitBytes;
		}

		DecimalFormat df = new DecimalFormat(NLS.bind(Messages.AbstractRetrieveFileTransfer_TransferRateFormat, unit));
		return df.format(convertedSize);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.core.identity.IIdentifiable#getID()
	 */
	public ID getID() {
		return remoteFileID;
	}

	protected IStatus getFinalStatus(Throwable exception1) {
		return Status.OK_STATUS;
	}

	protected void hardClose() {
		try {
			if (remoteFileContents != null)
				remoteFileContents.close();
		} catch (final IOException e) {
			Activator.getDefault().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, "hardClose", e)); //$NON-NLS-1$
		}
		try {
			if (localFileContents != null && closeOutputStream)
				localFileContents.close();
		} catch (final IOException e) {
			Activator.getDefault().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, "hardClose", e)); //$NON-NLS-1$
		}
		// leave job intact to ensure only one done event is fired
		remoteFileContents = null;
		localFileContents = null;
	}

	protected void fireTransferReceivePausedEvent() {
		listener.handleTransferEvent(new IIncomingFileTransferReceivePausedEvent() {

			private static final long serialVersionUID = -1317411290525985140L;

			public IIncomingFileTransfer getSource() {
				return AbstractRetrieveFileTransfer.this;
			}

			public String toString() {
				final StringBuffer sb = new StringBuffer("IIncomingFileTransferReceivePausedEvent["); //$NON-NLS-1$
				sb.append("bytesReceived=").append(bytesReceived) //$NON-NLS-1$
						.append(";fileLength=").append(fileLength).append("]"); //$NON-NLS-1$ //$NON-NLS-2$
				return sb.toString();
			}
		});
	}

	protected void fireTransferReceiveDoneEvent() {
		listener.handleTransferEvent(new IIncomingFileTransferReceiveDoneEvent() {

			private static final long serialVersionUID = 6925524078226825710L;

			public IIncomingFileTransfer getSource() {
				return AbstractRetrieveFileTransfer.this;
			}

			public Exception getException() {
				return AbstractRetrieveFileTransfer.this.getException();
			}

			public String toString() {
				final StringBuffer sb = new StringBuffer("IIncomingFileTransferReceiveDoneEvent["); //$NON-NLS-1$
				sb.append("bytesReceived=").append(bytesReceived) //$NON-NLS-1$
						.append(";fileLength=").append(fileLength).append(";exception=").append(getException()) //$NON-NLS-1$ //$NON-NLS-2$
						.append("]"); //$NON-NLS-1$
				return sb.toString();
			}
		});
	}

	protected void fireTransferReceiveDataEvent() {
		listener.handleTransferEvent(new IIncomingFileTransferReceiveDataEvent() {
			private static final long serialVersionUID = -5656328374614130161L;

			public IIncomingFileTransfer getSource() {
				return AbstractRetrieveFileTransfer.this;
			}

			public String toString() {
				final StringBuffer sb = new StringBuffer("IIncomingFileTransferReceiveDataEvent["); //$NON-NLS-1$
				sb.append("bytesReceived=").append(bytesReceived) //$NON-NLS-1$
						.append(";fileLength=").append(fileLength) //$NON-NLS-1$ 
						.append("]"); //$NON-NLS-1$
				return sb.toString();
			}
		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.eclipse.ecf.filetransfer.IRetrieveFileTransferContainerAdapter#
	 * setConnectContextForAuthentication
	 * (org.eclipse.ecf.core.security.IConnectContext)
	 */
	public void setConnectContextForAuthentication(IConnectContext connectContext) {
		this.connectContext = connectContext;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ecf.filetransfer.IRetrieveFileTransferContainerAdapter#setProxy
	 * (org.eclipse.ecf.core.util.Proxy)
	 */
	public void setProxy(Proxy proxy) {
		this.proxy = proxy;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ecf.filetransfer.IIncomingFileTransfer#getBytesReceived()
	 */
	public long getBytesReceived() {
		return bytesReceived;
	}

	// TODO: replace other instances.
	/**
	 * @since 3.0
	 */
	protected UserCancelledException newUserCancelledException() {
		return new UserCancelledException(Messages.AbstractRetrieveFileTransfer_Exception_User_Cancelled);
	}

	protected synchronized void resetDoneAndException() {
		setDone(false);
		this.exception = null;
	}

	protected synchronized void setDone(boolean done) {
		this.done = done;
	}

	protected synchronized void setDoneException(Exception e) {
		this.done = true;
		this.exception = e;
	}

	protected synchronized boolean isCanceled() {
		return done && exception instanceof UserCancelledException;
	}

	protected void setDoneCanceled() {
		setDoneCanceled(newUserCancelledException());
	}

	protected synchronized void setDoneCanceled(Exception e) {
		this.done = true;
		if (e instanceof UserCancelledException) {
			exception = e;
		} else {
			exception = newUserCancelledException();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IFileTransfer#cancel()
	 */
	public void cancel() {
		if (isPaused()) {
			setDoneCanceled();
			fireTransferReceiveDoneEvent();
			return;
		}
		synchronized (jobLock) {
			if (job != null)
				job.cancel();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IFileTransfer#getException()
	 */
	public synchronized Exception getException() {
		return exception;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IFileTransfer#getPercentComplete()
	 */
	public double getPercentComplete() {
		if (fileLength == -1 || fileLength == 0)
			return fileLength;
		return ((double) bytesReceived / (double) fileLength);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IFileTransfer#getFileLength()
	 */
	public long getFileLength() {
		return fileLength;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer
	 * #getRemoteLastModified()
	 */
	public Date getRemoteLastModified() {
		return lastModifiedTime == 0L ? null : new Date(lastModifiedTime);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IFileTransfer#isDone()
	 */
	public synchronized boolean isDone() {
		return done;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
	 */
	public Object getAdapter(Class adapter) {
		if (adapter == null)
			return null;
		if (adapter.isInstance(this)) {
			return this;
		}
		final IAdapterManager adapterManager = Activator.getDefault().getAdapterManager();
		return (adapterManager == null) ? null : adapterManager.loadAdapter(this, adapter.getName());
	}

	/**
	 * Open incoming and outgoing streams associated with this file transfer.
	 * Subclasses must implement this method to open input and output streams.
	 * The <code>remoteFileContents</code> and <code>localFileContent</code>
	 * must be non-<code>null</code> after successful completion of the
	 * implementation of this method.
	 * 
	 * @throws IncomingFileTransferException
	 */
	protected abstract void openStreams() throws IncomingFileTransferException;

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.eclipse.ecf.filetransfer.IRetrieveFileTransferContainerAdapter#
	 * sendRetrieveRequest(org.eclipse.ecf.filetransfer.identity.IFileID,
	 * org.eclipse.ecf.filetransfer.IFileTransferListener, java.util.Map)
	 */
	public void sendRetrieveRequest(final IFileID remoteFileID1, IFileTransferListener transferListener, Map options1) throws IncomingFileTransferException {
		sendRetrieveRequest(remoteFileID1, null, transferListener, options1);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.eclipse.ecf.filetransfer.IRetrieveFileTransferContainerAdapter#
	 * getRetrieveNamespace()
	 */
	public Namespace getRetrieveNamespace() {
		return IDFactory.getDefault().getNamespaceByName(FileTransferNamespace.PROTOCOL);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IFileTransferPausable#isPaused()
	 */
	public boolean isPaused() {
		return paused;
	}

	/**
	 * Subclass overridable version of {@link #pause()}. Subclasses must provide
	 * an implementation of this method to support {@link IFileTransferPausable}
	 * .
	 * 
	 * @return true if the pause is successful. <code>false</code> otherwise.
	 */
	protected abstract boolean doPause();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IFileTransferPausable#pause()
	 */
	public boolean pause() {
		return doPause();
	}

	/**
	 * Subclass overridable version of {@link #resume()}. Subclasses must
	 * provide an implementation of this method to support
	 * {@link IFileTransferPausable}.
	 * 
	 * @return true if the resume is successful. <code>false</code> otherwise.
	 */
	protected abstract boolean doResume();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IFileTransferPausable#resume()
	 */
	public boolean resume() {
		return doResume();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.filetransfer.IIncomingFileTransfer#getListener()
	 */
	public IFileTransferListener getListener() {
		return listener;
	}

	protected String createRangeName() {
		if (rangeSpecification == null)
			return ""; //$NON-NLS-1$
		return "[" + rangeSpecification.getStartPosition() + "," + rangeSpecification.getEndPosition() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	}

	protected String createJobName() {
		return getRemoteFileURL().toString() + createRangeName();
	}

	protected void setupAndScheduleJob(FileTransferJob fileTransferJob) {
		if (fileTransferJob == null) {
			// Create our own
			fileTransferJob = new FileTransferJob(createJobName());
		}
		// Now set to our runnable
		fileTransferJob.setFileTransferRunnable(fileTransferRunnable);
		fileTransferJob.setFileTransfer(this);
		if (isDone()) {
			return;
		}
		synchronized (jobLock) {
			job = fileTransferJob;
			job.schedule();
		}
	}

	protected void fireReceiveStartEvent() {
		listener.handleTransferEvent(new IIncomingFileTransferReceiveStartEvent() {
			private static final long serialVersionUID = -513800598918052184L;

			/*
			 * (non-Javadoc)
			 * 
			 * @seeorg.eclipse.ecf.filetransfer.events.
			 * IIncomingFileTransferEvent#getFileID()
			 */
			public IIncomingFileTransfer getSource() {
				return AbstractRetrieveFileTransfer.this;
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @seeorg.eclipse.ecf.filetransfer.events.
			 * IIncomingFileTransferReceiveStartEvent#getFileID()
			 */
			public IFileID getFileID() {
				return remoteFileID;
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @seeorg.eclipse.ecf.filetransfer.events.
			 * IIncomingFileTransferReceiveStartEvent
			 * #receive(java.io.File)
			 */
			public IIncomingFileTransfer receive(File localFileToSave) throws IOException {
				return receive(localFileToSave, null);
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @seeorg.eclipse.ecf.filetransfer.events.
			 * IIncomingFileTransferReceiveStartEvent
			 * #receive(java.io.File,
			 * org.eclipse.ecf.filetransfer.FileTransferJob)
			 */
			public IIncomingFileTransfer receive(File localFileToSave, FileTransferJob fileTransferJob) throws IOException {
				setOutputStream(new BufferedOutputStream(new FileOutputStream(localFileToSave)));
				setupAndScheduleJob(fileTransferJob);
				return AbstractRetrieveFileTransfer.this;
			}

			/**
			 * @param streamToStore
			 * @return incoming file transfer instance.
			 * @throws IOException
			 *             not thrown in this implementation.
			 */
			public IIncomingFileTransfer receive(OutputStream streamToStore) throws IOException {
				return receive(streamToStore, null);
			}

			/**
			 * @throws IOException
			 *             not actually thrown by this implementation.
			 */
			public IIncomingFileTransfer receive(OutputStream streamToStore, FileTransferJob fileTransferJob) throws IOException {
				setOutputStream(streamToStore);
				setCloseOutputStream(false);
				setupAndScheduleJob(fileTransferJob);
				return AbstractRetrieveFileTransfer.this;
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @seeorg.eclipse.ecf.filetransfer.events.
			 * IIncomingFileTransferReceiveStartEvent#cancel()
			 */
			public void cancel() {
				AbstractRetrieveFileTransfer.this.cancel();
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see java.lang.Object#toString()
			 */
			public String toString() {
				final StringBuffer sb = new StringBuffer("IIncomingFileTransferReceiveStartEvent["); //$NON-NLS-1$
				sb.append("isdone=").append(isDone()).append(";"); //$NON-NLS-1$ //$NON-NLS-2$
				sb.append("bytesReceived=").append(bytesReceived) //$NON-NLS-1$
						.append("]"); //$NON-NLS-1$
				return sb.toString();
			}

			public Map getResponseHeaders() {
				return responseHeaders;
			}

		});
	}

	protected void fireReceiveResumedEvent() {
		listener.handleTransferEvent(new IIncomingFileTransferReceiveResumedEvent() {

			private static final long serialVersionUID = 7111739642849612839L;

			public IIncomingFileTransfer getSource() {
				return AbstractRetrieveFileTransfer.this;
			}

			public IFileID getFileID() {
				return remoteFileID;
			}

			public IIncomingFileTransfer receive(File localFileToSave, boolean append) throws IOException {
				return receive(localFileToSave, null, append);
			}

			public IIncomingFileTransfer receive(File localFileToSave, FileTransferJob fileTransferJob, boolean append) throws IOException {
				setOutputStream(new BufferedOutputStream(new FileOutputStream(localFileToSave.getName(), append)));
				setupAndScheduleJob(fileTransferJob);
				return AbstractRetrieveFileTransfer.this;
			}

			/**
			 * @param streamToStore
			 * @return incoming file transfer instance.
			 * @throws IOException
			 *             not thrown in this implementation.
			 */
			public IIncomingFileTransfer receive(OutputStream streamToStore) throws IOException {
				return receive(streamToStore, null);
			}

			/**
			 * @throws IOException
			 *             not actually thrown by this implementation.
			 */
			public IIncomingFileTransfer receive(OutputStream streamToStore, FileTransferJob fileTransferJob) throws IOException {
				setOutputStream(streamToStore);
				setCloseOutputStream(false);
				setupAndScheduleJob(fileTransferJob);
				return AbstractRetrieveFileTransfer.this;
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @seeorg.eclipse.ecf.filetransfer.events.
			 * IIncomingFileTransferReceiveStartEvent#cancel()
			 */
			public void cancel() {
				hardClose();
			}

			public String toString() {
				final StringBuffer sb = new StringBuffer("IIncomingFileTransferReceiveResumedEvent["); //$NON-NLS-1$
				sb.append("isdone=").append(isDone()).append(";"); //$NON-NLS-1$ //$NON-NLS-2$
				sb.append("bytesReceived=").append(bytesReceived) //$NON-NLS-1$
						.append("]"); //$NON-NLS-1$
				return sb.toString();
			}

			public Map getResponseHeaders() {
				return responseHeaders;
			}

		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ecf.filetransfer.IIncomingFileTransfer#getFileRangeSpecification
	 * ()
	 */
	public IFileRangeSpecification getFileRangeSpecification() {
		return rangeSpecification;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.eclipse.ecf.filetransfer.IRetrieveFileTransferContainerAdapter#
	 * sendRetrieveRequest(org.eclipse.ecf.filetransfer.identity.IFileID,
	 * org.eclipse.ecf.filetransfer.IFileRangeSpecification,
	 * org.eclipse.ecf.filetransfer.IFileTransferListener, java.util.Map)
	 */
	/**
	 * @throws IncomingFileTransferException  
	 */
	public void sendRetrieveRequest(IFileID rFileID, IFileRangeSpecification rangeSpec, IFileTransferListener transferListener, Map ops) throws IncomingFileTransferException {
		Assert.isNotNull(rFileID, Messages.AbstractRetrieveFileTransfer_RemoteFileID_Not_Null);
		Assert.isNotNull(transferListener, Messages.AbstractRetrieveFileTransfer_TransferListener_Not_Null);
		synchronized (jobLock) {
			this.job = null;
		}
		this.remoteFileURL = null;
		this.remoteFileID = rFileID;
		this.listener = transferListener;
		this.remoteFileContents = null;
		this.localFileContents = null;
		this.closeOutputStream = true;
		resetDoneAndException();
		this.bytesReceived = 0;
		this.fileLength = -1;
		this.options = ops;
		this.paused = false;
		this.rangeSpecification = rangeSpec;

		try {
			this.remoteFileURL = rFileID.getURL();
		} catch (final MalformedURLException e) {
			setDoneException(e);
			fireTransferReceiveDoneEvent();
			return;
		}
		try {
			setupProxies();
			openStreams();
		} catch (final IncomingFileTransferException e) {
			setDoneException(e);
			fireTransferReceiveDoneEvent();
		}
	}

	/**
	 * Setup ECF proxy. Subclasses must override this method to do appropriate
	 * proxy setup. This method will be called from within
	 * {@link #sendRetrieveRequest(IFileID, IFileTransferListener, Map)} and
	 * {@link #sendRetrieveRequest(IFileID, IFileRangeSpecification, IFileTransferListener, Map)}
	 * , prior to the actual call to {@link #openStreams()}.
	 * 
	 * @param proxy
	 *            the proxy to be setup. Will not be <code>null</code>.
	 */
	protected abstract void setupProxy(Proxy proxy);

	/**
	 * Select a single proxy from a set of proxies available for the given host.
	 * This implementation selects in the following manner: 1) If proxies
	 * provided is null or array of 0 length, null is returned. If only one
	 * proxy is available (array of length 1) then the entry is returned. If
	 * proxies provided is length > 1, then if the type of a proxy in the array
	 * matches the given protocol (e.g. http, https), then the first matching
	 * proxy is returned. If the protocol does not match any of the proxies,
	 * then the *first* proxy (i.e. proxies[0]) is returned. Subclasses may
	 * override if desired.
	 * 
	 * @param protocol
	 *            the target protocol (e.g. http, https, scp, etc). Will not be
	 *            <code>null</code>.
	 * @param proxies
	 *            the proxies to select from. May be <code>null</code> or array
	 *            of length 0.
	 * @return proxy data selected from the proxies provided.
	 */
	protected IProxyData selectProxyFromProxies(String protocol, IProxyData[] proxies) {
		if (proxies == null || proxies.length == 0)
			return null;
		// If only one proxy is available, then use that
		if (proxies.length == 1)
			return proxies[0];
		// If more than one proxy is available, then if http/https protocol then
		// look for that
		// one...if not found then use first
		if (protocol.equalsIgnoreCase("http")) { //$NON-NLS-1$
			for (int i = 0; i < proxies.length; i++) {
				if (proxies[i].getType().equals(IProxyData.HTTP_PROXY_TYPE))
					return proxies[i];
			}
		} else if (protocol.equalsIgnoreCase("https")) { //$NON-NLS-1$
			for (int i = 0; i < proxies.length; i++) {
				if (proxies[i].getType().equals(IProxyData.HTTPS_PROXY_TYPE))
					return proxies[i];
			}
		}
		// If we haven't found it yet, then return the first one.
		return proxies[0];
	}

	protected void setupProxies() {
		// If it's been set directly (via ECF API) then this overrides platform
		// settings
		if (proxy == null) {
			proxy = ProxySetupHelper.getProxy(getRemoteFileURL().toExternalForm());
		}
		if (proxy != null)
			setupProxy(proxy);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ecf.filetransfer.IIncomingFileTransfer#getRemoteFileName()
	 */
	public String getRemoteFileName() {
		String pathStr = getRemoteFileURL().getPath();
		if (pathStr.length() > 0) {
			IPath path = Path.fromPortableString(pathStr);
			if (path.segmentCount() > 0)
				return path.lastSegment();
		}
		return null;
	}

	protected boolean targetHasGzSuffix(String target) {
		if (target == null)
			return false;
		if (target.endsWith(".gz")) //$NON-NLS-1$
			return true;
		return false;
	}

}

Back to the top