function [OK, value] = getJavaFutureResult(future, timeAmount, timeUnit)
%getJavaFutureResult calls 'get' on a java future, and unpicks exceptions.
%   [OK, VALUE] = getJavaFutureResult(future, timeAmount, timeUnit) calls
%   VALUE = future.get(timeAmount, timeUnit), and unpicks exceptions
%   thrown. Outcomes:
%   OK = TRUE, VALUE = non-empty - the future completed successfully
%   OK = FALSE, VALUE = [] - the future is not yet complete
%   Error thrown - future execution resulted in some error.

% Copyright 2013 The MathWorks, Inc.

OK = false;
value = [];
try
    value = future.get(timeAmount, timeUnit);
    OK    = true;
catch E
    if isa(E, 'matlab.exception.JavaException')
        underlyingException = E.ExceptionObject;
        if isa(underlyingException, ...
               'java.util.concurrent.TimeoutException')
            % Hit the timeout.
            return;
        elseif isa(underlyingException, ...
                   'java.util.concurrent.ExecutionException')

            % Try and unpick the message ID and message from the real cause.
            realProblem         = underlyingException.getCause();
            hasMessageClassName = ...
                'com.mathworks.toolbox.distcomp.util.i18n.HasI18nMatlabIdentifiedMessage';
            if ~isempty(realProblem) && isa(realProblem, hasMessageClassName)
                % Got all the information to throw the real problem.
                error(char(realProblem.getMessageID()), '%s', ...
                      char(realProblem.getLocalizedMessage()));
            end
        end
    end
    % If we get here, no better ideas, so simply rethrow original.
    rethrow(E);
end
end
