Skip to content

Commit 50cc72e

Browse files
committed
Make FileDownloader helper class internal
We don't want to expose it as public API, at least not now.
1 parent 03e6cb9 commit 50cc72e

File tree

2 files changed

+55
-89
lines changed

2 files changed

+55
-89
lines changed

src/main/java/org/apposed/appose/util/Downloads.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,4 +405,59 @@ private static String userAgent() {
405405
return "Appose/" + Appose.version() +
406406
" (Java " + javaVersion + "/" + os + ")";
407407
}
408+
409+
/**
410+
* Helper class for downloading content with or without cancelability.
411+
*
412+
* @author Carlos Garcia Lopez de Haro
413+
*/
414+
static class FileDownloader {
415+
private static final long CHUNK_SIZE = 1024 * 1024 * 5;
416+
417+
private final ReadableByteChannel rbc;
418+
private final FileOutputStream fos;
419+
420+
FileDownloader(ReadableByteChannel rbc, FileOutputStream fos) {
421+
this.rbc = rbc;
422+
this.fos = fos;
423+
}
424+
425+
/**
426+
* Download a file without the possibility of interrupting the download.
427+
*
428+
* @throws IOException if there is any error downloading the file from the url
429+
*/
430+
void call() throws IOException {
431+
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
432+
}
433+
434+
/**
435+
* Download a file with the possibility of interrupting the download if the
436+
* parentThread is interrupted.
437+
*
438+
* @param parentThread
439+
* thread from where the download was launched; it is the reference used to stop the download
440+
* @throws IOException if there is any error downloading the file from the url
441+
* @throws InterruptedException if the download is interrupted because the parentThread is interrupted
442+
*/
443+
void call(Thread parentThread) throws IOException, InterruptedException {
444+
long position = 0;
445+
while (true) {
446+
long transferred = fos.getChannel().transferFrom(rbc, position, CHUNK_SIZE);
447+
if (transferred == 0) break;
448+
449+
position += transferred;
450+
if (parentThread != null && !parentThread.isAlive()) {
451+
// Close resources if needed and exit.
452+
closeResources();
453+
throw new InterruptedException("File download was interrupted.");
454+
}
455+
}
456+
}
457+
458+
private void closeResources() throws IOException {
459+
if (rbc != null) rbc.close();
460+
if (fos != null) fos.close();
461+
}
462+
}
408463
}

src/main/java/org/apposed/appose/util/FileDownloader.java

Lines changed: 0 additions & 89 deletions
This file was deleted.

0 commit comments

Comments
 (0)