use of com.openmeap.http.HttpRequestExecuter in project OpenMEAP by OpenMEAP.
the class UpdateHandler method downloadToArchive.
/**
* @param update
* @param eventHandler
* @return true if completed, false if interrupted
* @throws IOException
*/
public Boolean downloadToArchive(UpdateStatus update, StatusChangeHandler eventHandler) throws UpdateException {
// download the file to import.zip
OutputStream os = null;
InputStream is = null;
HttpRequestExecuter requester = HttpRequestExecuterFactory.newDefault();
HttpResponse updateRequestResponse;
try {
updateRequestResponse = requester.get(update.getUpdateHeader().getUpdateUrl());
} catch (HttpRequestException e) {
throw new UpdateException(UpdateResult.IO_EXCEPTION, "An issue occurred fetching the update archive", e);
}
if (updateRequestResponse.getStatusCode() != 200)
throw new UpdateException(UpdateResult.RESPONSE_STATUS_CODE, "Status was " + updateRequestResponse.getStatusCode() + ", expecting 200");
try {
os = storage.getImportArchiveOutputStream();
is = updateRequestResponse.getResponseBody();
byte[] bytes = new byte[1024];
int count = is.read(bytes);
int contentLength = (int) updateRequestResponse.getContentLength();
int contentDownloaded = 0;
int lastContentDownloaded = contentDownloaded;
int percent = contentLength / 100;
while (count != (-1)) {
os.write(bytes, 0, count);
count = is.read(bytes);
contentDownloaded += count;
if (eventHandler != null && lastContentDownloaded + percent < contentDownloaded) {
update.setBytesDownloaded(contentDownloaded);
eventHandler.onStatusChange(update);
lastContentDownloaded = contentDownloaded;
}
synchronized (interruptLock) {
if (interrupt.booleanValue()) {
clearInterruptFlag();
throw new UpdateException(UpdateResult.INTERRUPTED, "Download of archive was interrupted");
}
}
}
} catch (IOException lse) {
throw new UpdateException(UpdateResult.IO_EXCEPTION, lse.getMessage(), lse);
} catch (LocalStorageException lse) {
throw new UpdateException(UpdateResult.IO_EXCEPTION, lse.getMessage(), lse);
} finally {
try {
storage.closeOutputStream(os);
storage.closeInputStream(is);
} catch (LocalStorageException e) {
throw new UpdateException(UpdateResult.IO_EXCEPTION, e.getMessage(), e);
}
// have to hang on to the requester till the download is complete,
// so that we can retain control over when the connection manager
// shut's down
requester.shutdown();
}
return Boolean.TRUE;
}
Aggregations