Skip to content

Commit eb143bd

Browse files
author
Mattia Bertorello
committed
Reduce download method complexity of FileDownloader class.
1 parent a8c7184 commit eb143bd

File tree

2 files changed

+79
-61
lines changed

2 files changed

+79
-61
lines changed

Diff for: arduino-core/src/cc/arduino/contributions/DownloadableContributionsDownloader.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ public void download(URL url, File tmpFile, Progress progress, String statusText
126126
}
127127

128128
public void download(URL url, File tmpFile, Progress progress, String statusText, ProgressListener progressListener, boolean noResume, boolean allowCache) throws Exception {
129-
FileDownloader downloader = new FileDownloader(url, tmpFile);
129+
FileDownloader downloader = new FileDownloader(url, tmpFile, allowCache);
130130
downloader.addObserver((o, arg) -> {
131131
FileDownloader me = (FileDownloader) o;
132132
String msg = "";
@@ -139,7 +139,7 @@ public void download(URL url, File tmpFile, Progress progress, String statusText
139139
progress.setProgress(me.getProgress());
140140
progressListener.onProgress(progress);
141141
});
142-
downloader.download(noResume, allowCache);
142+
downloader.download(noResume);
143143
if (!downloader.isCompleted()) {
144144
throw new Exception(format(tr("Error downloading {0}"), url), downloader.getError());
145145
}

Diff for: arduino-core/src/cc/arduino/utils/network/FileDownloader.java

+77-59
Original file line numberDiff line numberDiff line change
@@ -65,14 +65,15 @@ public enum Status {
6565
private final URL downloadUrl;
6666

6767
private final File outputFile;
68-
private InputStream stream = null;
68+
private final boolean allowCache;
6969
private Exception error;
7070

71-
public FileDownloader(URL url, File file) {
72-
downloadUrl = url;
73-
outputFile = file;
74-
downloaded = 0;
75-
initialSize = 0;
71+
public FileDownloader(URL url, File file, boolean allowCache) {
72+
this.downloadUrl = url;
73+
this.outputFile = file;
74+
this.allowCache = allowCache;
75+
this.downloaded = 0;
76+
this.initialSize = 0;
7677
}
7778

7879
public long getInitialSize() {
@@ -118,7 +119,7 @@ public void setStatus(Status status) {
118119
}
119120

120121

121-
public void download(boolean noResume, boolean allowCache) throws InterruptedException {
122+
public void download(boolean noResume) throws InterruptedException {
122123
if ("file".equals(downloadUrl.getProtocol())) {
123124
saveLocalFile();
124125
} else {
@@ -137,33 +138,18 @@ private void saveLocalFile() {
137138
}
138139

139140
private void downloadFile(boolean noResume, boolean allowCache) throws InterruptedException {
140-
RandomAccessFile randomAccessOutputFile = null;
141141

142+
InputStream stream = null;
142143
try {
143144
setStatus(Status.CONNECTING);
144145

145146
final Optional<FileDownloaderCache.FileCached> fileCached = FileDownloaderCache.getFileCached(downloadUrl);
146-
147147
if (fileCached.isPresent() && fileCached.get().isNotChange()) {
148-
try {
149-
final Optional<File> fileFromCache =
150-
fileCached.get().getFileFromCache();
151-
if (fileFromCache.isPresent()) {
152-
log.info("No need to download using cached file: {}", fileCached.get());
153-
FileUtils.copyFile(fileFromCache.get(), outputFile);
154-
setStatus(Status.COMPLETE);
155-
return;
156-
} else {
157-
log.info(
158-
"The file in the cache is not in the path or the md5 validation failed: path={}, file exist={}, md5 validation={}",
159-
fileCached.get().getLocalPath(), fileCached.get().exists(), fileCached.get().md5Check());
160-
}
161-
} catch (Exception e) {
162-
log.warn(
163-
"Cannot get the file from the cache, will be downloaded a new one ", e);
148+
final Optional<File> fileFromCache = getFileCached(fileCached.get());
149+
if (fileFromCache.isPresent()) {
150+
FileUtils.copyFile(fileFromCache.get(), outputFile);
151+
setStatus(Status.COMPLETE);
164152
}
165-
} else {
166-
log.info("The file is change {}", fileCached);
167153
}
168154

169155
initialSize = outputFile.length();
@@ -172,19 +158,75 @@ private void downloadFile(boolean noResume, boolean allowCache) throws Interrupt
172158
Files.deleteIfExists(outputFile.toPath());
173159
initialSize = 0;
174160
}
175-
// Open file and seek to the end of it
176-
randomAccessOutputFile = new RandomAccessFile(outputFile, "rw");
177-
randomAccessOutputFile.seek(initialSize);
178161

179162
final HttpURLConnection connection = new HttpConnectionManager(downloadUrl)
180163
.makeConnection((c) -> setDownloaded(0));
181164
final int resp = connection.getResponseCode();
182165

183166
if (resp < 200 || resp >= 300) {
184-
IOUtils.closeQuietly(randomAccessOutputFile);
185167
Files.deleteIfExists(outputFile.toPath());
186168
throw new IOException("Received invalid http status code from server: " + resp);
187169
}
170+
copyStreamToFile(connection);
171+
172+
if (fileCached.isPresent() && allowCache) {
173+
fileCached.get().updateCacheFile(outputFile);
174+
}
175+
if (!allowCache) {
176+
log.info("The file {} was not cached because allow cache is false", downloadUrl);
177+
}
178+
setStatus(Status.COMPLETE);
179+
180+
} catch (InterruptedException e) {
181+
setStatus(Status.CANCELLED);
182+
// lets InterruptedException go up to the caller
183+
throw e;
184+
185+
} catch (SocketTimeoutException e) {
186+
setStatus(Status.CONNECTION_TIMEOUT_ERROR);
187+
setError(e);
188+
log.error("The request went in socket timeout", e);
189+
190+
} catch (Exception e) {
191+
setStatus(Status.ERROR);
192+
setError(e);
193+
log.error("The request stop", e);
194+
195+
} finally {
196+
IOUtils.closeQuietly(stream);
197+
}
198+
199+
200+
}
201+
202+
private Optional<File> getFileCached(FileDownloaderCache.FileCached fileCached) {
203+
204+
try {
205+
final Optional<File> fileFromCache =
206+
fileCached.getFileFromCache();
207+
if (fileFromCache.isPresent()) {
208+
log.info("No need to download using cached file: {}", fileCached);
209+
return fileFromCache;
210+
} else {
211+
log.info(
212+
"The file in the cache is not in the path or the md5 validation failed: path={}, file exist={}, md5 validation={}",
213+
fileCached.getLocalPath(), fileCached.exists(), fileCached.md5Check());
214+
}
215+
} catch (Exception e) {
216+
log.warn(
217+
"Cannot get the file from the cache, will be downloaded a new one ", e);
218+
}
219+
log.info("The file is change {}", fileCached);
220+
return Optional.empty();
221+
}
222+
223+
private void copyStreamToFile(HttpURLConnection connection) throws Exception {
224+
RandomAccessFile randomAccessOutputFile = null;
225+
InputStream stream = null;
226+
try {
227+
// Open file and seek to the end of it
228+
randomAccessOutputFile = new RandomAccessFile(outputFile, "rw");
229+
randomAccessOutputFile.seek(initialSize);
188230

189231
// Check for valid content length.
190232
long len = connection.getContentLength();
@@ -193,9 +235,8 @@ private void downloadFile(boolean noResume, boolean allowCache) throws Interrupt
193235
}
194236
setStatus(Status.DOWNLOADING);
195237

196-
synchronized (this) {
197-
stream = connection.getInputStream();
198-
}
238+
stream = connection.getInputStream();
239+
199240
byte[] buffer = new byte[10240];
200241
while (status == Status.DOWNLOADING) {
201242
int read = stream.read(buffer);
@@ -217,35 +258,12 @@ private void downloadFile(boolean noResume, boolean allowCache) throws Interrupt
217258
}
218259
// Set the cache whe it finish to download the file
219260
IOUtils.closeQuietly(randomAccessOutputFile);
220-
if (fileCached.isPresent() && allowCache) {
221-
fileCached.get().updateCacheFile(outputFile);
222-
}
223-
if (!allowCache) {
224-
log.info("The file {} was not cached because allow cache is false", downloadUrl);
225-
}
226-
setStatus(Status.COMPLETE);
227-
} catch (InterruptedException e) {
228-
setStatus(Status.CANCELLED);
229-
// lets InterruptedException go up to the caller
230-
throw e;
231-
232-
} catch (SocketTimeoutException e) {
233-
setStatus(Status.CONNECTION_TIMEOUT_ERROR);
234-
setError(e);
235-
log.error("The request went in socket timeout", e);
236-
237-
} catch (Exception e) {
238-
setStatus(Status.ERROR);
239-
setError(e);
240-
log.error("The request stop", e);
241261

242262
} finally {
243263
IOUtils.closeQuietly(randomAccessOutputFile);
244-
245-
synchronized (this) {
246-
IOUtils.closeQuietly(stream);
247-
}
264+
IOUtils.closeQuietly(stream);
248265
}
266+
249267
}
250268

251269
private void setError(Exception e) {

0 commit comments

Comments
 (0)