%serializedFeval
% A wrapper around feval that both receives input and generates output
% that has been Java serialized to a Base64 string.
%

%   Copyright 2016 The MathWorks, Inc.

function out = serializedFeval(command, varargin)

import com.mathworks.toolbox.parallel.mapreduce.SerializationUtils;

try
    for ii = 1:numel(varargin)
        varargin{ii} = SerializationUtils.decodeFromString(varargin{ii});
        varargin{ii} = SerializationUtils.deserialize(varargin{ii});
        if isa(varargin{ii}, 'java.lang.String')
            varargin{ii} = char(varargin{ii});
        end
    end
    
    out = feval(command, varargin{:});
    
    out = SerializationUtils.serialize(out);
    out = char(SerializationUtils.encodeToString(out));
catch err
    % This function expects to be called via the Java MVM feval method. If
    % an error bubbles back to the Java MVM feval call, a Java Exception
    % object is thrown that contains only the message of the error. For
    % clarity in the logs, we wrap the entire error report in a new error
    % message.
    error(message('parallel:mapreduce:HadoopMatlabFailure', err.getReport()));
end
