Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

issue-16: fix download bug in data product delivery #18

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 24 additions & 19 deletions onc/+onc/DataProductFile.m
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@
uri = matlab.net.URI(this.baseUrl);
uri.Query = matlab.net.QueryParameter(this.filters);
fullUrl = char(uri);
options = matlab.net.http.HTTPOptions('ConnectTimeout', timeout, 'ConvertResponse', false);

options = matlab.net.http.HTTPOptions('ConnectTimeout', timeout);

while this.status == 202
% run and time request
if this.showInfo, log.printLine(sprintf('Requesting URL:\n %s', fullUrl)); end
Expand Down Expand Up @@ -96,41 +98,44 @@
if length(lengthData) == 1
this.fileSize = str2double(lengthData.Value);
else
this.fileSize = strlength(response.Body.Data);
ext = util.extractFileExtension(filename);
if strcmp(ext, 'xml')
Copy link

@KristenMeyerONC KristenMeyerONC Apr 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove a level of nesting here by:

                    ext = util.extractFileExtension(filename);
                    if length(lengthData) == 1
                        this.fileSize = str2double(lengthData.Value);
                    elseif strcmp(ext, 'xml')
                        this.fileSize = length(xmlwrite(response.Body.Data));
                    else
                        this.fileSize = strlength(response.Body.Data);
                    end

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well that did not format well, one sec

this.fileSize = length(xmlwrite(response.Body.Data));
else
this.fileSize = strlength(response.Body.Data);
end
end

savefilename = fullfile(outPath, filename);
% Create folder if not exist
if ~exist(outPath,'dir')
mkdir(outPath)
end
% saveResult -2: File exists and set to not overwrite 0: done
if ~overwrite && exist(savefilename,'file') == 2
saveResult = -2;
else
websave(savefilename,uri.EncodedURI);
saveResult = 0;
try
saveResult = util.save_as_file(response.Body.Data, outPath, filename, 'overwrite', overwrite);
catch ME
if strcmp(ME.identifier, 'onc:FileExistsError')
log.printLine(sprintf('Skipping "%s": File already exists\n', this.fileName));
this.status = 777;
saveResult = -2;
this.downloaded = false;
else
rethrow(ME);
end
end

this.downloadingTime = round(duration, 3);

% log status
if saveResult == 0
log.printLine(sprintf('Downloaded "%s"\n', this.fileName));
elseif saveResult == -2
log.printLine(sprintf('Skipping "%s": File already exists\n', this.fileName));
this.status = 777;
end
elseif s == 202
% Still processing, wait and retry
log.printResponse(jsondecode(response.Body.Data));
log.printResponse(response.Body.Data);
pause(pollPeriod);
elseif s == 204
% No data found
log.printLine('No data found.\n');
elseif s == 400
% API Error
util.print_error(response, fullUrl);
throw(util.prepare_exception(s, double(jsondecode(response.Body.Data).errors.errorCode)));
throw(util.prepare_exception(s, double(response.Body.Data.errors.errorCode)));

elseif s == 404
% Index too high, no more files to download
else
Expand Down
13 changes: 13 additions & 0 deletions onc/+util/extractFileExtension.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function ext = extractFileExtension(filename)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of this function you can use: https://www.mathworks.com/help/matlab/ref/fileparts.html which also handles string and char array.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh this function is a perfect fit! I will update the codes

% get extension from filename (string or char array)
% this function is called by save_as_file.m to decide which download method to use

filename = char(filename);
possibleExtensionStartIndex = strfind(filename, '.');
if ~isempty(possibleExtensionStartIndex)
extensionStartIndex = possibleExtensionStartIndex(end);
ext = filename(extensionStartIndex + 1:end);
else
ext = '';
end
end
37 changes: 25 additions & 12 deletions onc/+util/save_as_file.m
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
% @param fileName Name of the file to save
% @param overwrite If true will overwrite files with the same name
% @return (numeric) Result code from {0: done, -1: error, -2: fileExists}
function endCode = save_as_file(response, filePath, fileName, varargin)
function endCode = save_as_file(dataToWrite, filePath, fileName, varargin)
[overwrite] = util.param(varargin, 'overwrite', false);

fullPath = fileName;
Expand All @@ -25,25 +25,38 @@
try
matlabVersion = version('-release');
year = str2double(matlabVersion(1:end-1));
if year >= 2021
f = fopen(fullPath, 'w','n','ISO-8859-1');
else
f = fopen(fullPath, 'w','n');
end

if f ~= -1
fwrite(f, response);

ext = util.extractFileExtension(fileName);

% if result is an image file or .xml file, use other save methods instead of fwrite.
if strcmp(ext, 'png') || strcmp(ext, 'jpg')
imwrite(dataToWrite, fullPath);
elseif strcmp(ext, 'xml')
xmlwrite(fullPath, dataToWrite);
else
endCode = -1;
return;
% open output file
if year >= 2021
f = fopen(fullPath, 'w','n','ISO-8859-1');
else
f = fopen(fullPath, 'w','n');
end

% write result if open file successfully
if f ~= -1
fwrite(f, char(dataToWrite));
else
endCode = -1;
return;
end
fclose(f);
end
fclose(f);
catch ex
disp(ex);
endCode = -1;
return;
end
else
% if file exists and overwrite is false, raise exception
throw(MException('onc:FileExistsError', 'Data product file exists in destination but overwrite is set to false'));
end

Expand Down