view m-toolbox/classes/@ltpda_uo/retrieve.m @ 7:1e91f84a4be8 database-connection-manager

Make ltpda_up.retrieve work with java.sql.Connection objects
author Daniele Nicolodi <nicolodi@science.unitn.it>
date Mon, 05 Dec 2011 16:20:06 +0100
parents f0afece42f48
children 2f5c9bd7d95d
line wrap: on
line source

% RETRIEVE retrieves a collection of objects from an LTPDA repository.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: This static method retrieves a collection of objects from an
%              LTPDA repository.
%
% CALL:    objs    = retrieve(conn, obj_id_1, obj_id_2)
%          [o1,o2] = retrieve(conn, obj_id_1, obj_id_2)
%          [o1,o2] = retrieve(conn, 'binary', obj_id_1, obj_id_2)
%          objs    = retrieve(conn, 'Collection', coll_id)
%          objs    = retrieve(conn, 'binary', 'Collection', coll_id)
%
% INPUTS:
%          conn       - database connection object
%          obj_id_N   - an object ID
%          coll_id    - a collection ID
%          'binary'   - to retrieve a binary representation of the object
%                       (if stored)
%
% OUTPUTS:
%          objs          - the retrieved object(s) as a cell array.*
%          o1,o2,...,oN  - returns the first N objects
%
%
% If more than one object is retrieved and only one output is specified
% then the output is a cell array of objects.
%
% If only a single object is requested, it is returned as an object,
% not packed in a cell array.
%
% VERSION:     $Id: retrieve.m,v 1.28 2011/07/01 14:38:57 ingo Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = retrieve(varargin)

  % Check if this is a call for parameters
  if utils.helper.isinfocall(varargin{:})
    varargout{1} = getInfo(varargin{3});
    return
  end

  import utils.const.*
  utils.helper.msg(msg.PROC3, 'running %s/%s', mfilename('class'), mfilename);

  if nargin == 0
    help(mfilename);
    error('### Incorrect inputs');
  end

  objs = [];
  conn = varargin{1};
  if ~isa(conn, 'java.sql.Connection')
    error('### the first argument should be a java.sql.Connection object');
  end

  try

    % get username and user id
    username = utils.mysql.execute(conn, 'SELECT SUBSTRING_INDEX(USER(),''@'',1)');
    rows     = utils.mysql.execute(conn, 'SELECT id FROM users WHERE username = ?', username{1});
    if isempty(rows)
      error('### could not determine user id');
    end
    userid = rows{1};

    binary = false;
    if nargin >= 3 && ischar(varargin{2}) && strcmpi(varargin{2}, 'binary')
      %%%  retrieve(conn, 'binary', obj_id_1, obj_id_2)
      %%%  retrieve(conn, 'binary', 'Collection', coll_id)
      binary = true;
      if nargin == 4 && ischar(varargin{3}) && strcmpi(varargin{3}, 'Collection') && isnumeric(varargin{4}) && numel(varargin{4}) == 1
        cid = varargin{4};
        % Get a list of object IDs from the collection ID
        rows = utils.mysql.execute(conn, 'SELECT nobjs, obj_ids FROM collections WHERE id = ?', cid);
        nobjs = rows{1};
        ids = strread(rows{2}, '%d', 'delimiter', ',');
        if length(ids) ~= nobjs
          error('### inconsistent collection description');
        end
      elseif nargin >= 3 && isnumeric([varargin{3:end}])
        ids = [varargin{3:end}];
      else
        help(mfilename)
        error('### Incorrect usage');
      end

    elseif nargin == 3 && ischar(varargin{2}) && strcmpi(varargin{2}, 'Collection') && isnumeric(varargin{3}) && numel(varargin{3}) == 1
      %%%  retrieve(conn, 'Collection', coll_id)
      cid = varargin{3};
      % Get a list of object IDs from the collection ID
      rows = utils.mysql.execute(conn, 'SELECT nobjs, obj_ids FROM collections WHERE id = ?', cid);
      nobjs = rows{1};
      ids = strread(rows{2}, '%d', 'delimiter', ',');
      if length(ids) ~= nobjs
        error('### inconsistent collection description');
      end

    elseif nargin >= 2 && isnumeric([varargin{2:end}])
      %%%  retrieve(conn, obj_id_1, obj_id_2)
      ids = [varargin{2:end}];

    else
      help(mfilename)
      error('### incorrect usage');
    end

    utils.helper.msg(msg.PROC1, ['retrieving objects' sprintf(' %d', ids)]);

    v = ver('LTPDA');
    for j=1:length(ids)

      rows = utils.mysql.execute(conn, 'SELECT version, obj_type FROM objmeta WHERE obj_id = ?', ids(j));
      if isempty(rows)
        error('### object %d not found', ids(j));
      end
      objver = rows{1};
      objtype = rows{2};

      % it is only possible to download the object if the object in the
      % database was submitted with the same or lower LTPDA version as
      % the current version
      if utils.helper.ver2num(v.Version) < utils.helper.ver2num(objver)
        error(['### object %d was submitted with newer LTPDA version (%s) '...
               'than this one (%s). please update'], ids(j), objver, v.Version);
      end

      if binary
        % binary download

        % Retrieve the bytes
        rows = utils.mysql.execute(conn, 'SELECT mat FROM bobjs WHERE obj_id = ?', ids(j));
        if isempty(rows)
          error('### failed to get binary data for object %d', ids(j));
        end
        dd = rows{1};

        % Write bytes out to a temp MAT file
        fname = [tempname '.mat'];
        fd = fopen(fname, 'w+');
        fwrite(fd, dd, 'int8');
        fclose(fd);
        % Load the MAT data to a structure
        obj = load(fname);
        % Delete temp file
        delete(fname);
        % Get the struct out
        obj = obj.objs;

        % Check if the retrieved object is a struct
        if isstruct(obj)
          % Call the constructor with this struct
          fcn_name   = [objtype '.update_struct'];
          obj = feval(fcn_name, obj, obj.tbxver);
          obj = feval(objtype, obj);
        end
        % Add tyo object array
        objs = [objs {obj}];

      else
        % xml download

        % get xml
        rows = utils.mysql.execute(conn, 'SELECT xml FROM objs WHERE id = ?', ids(j));
        if isempty(rows)
          error('### failed to get data for object %d', ids(j));
        end

        % parse xml
        stream = java.io.StringBufferInputStream(java.lang.String(rows{1}));
        builder = javax.xml.parsers.DocumentBuilderFactory.newInstance.newDocumentBuilder();
        xdoc = builder.parse(stream);
        obj = utils.xml.xmlread(xdoc);

        % add to output array
        objs = [objs {obj}];

        % make transaction entry
        t = time().format('yyyy-mm-dd HH:MM:SS', 'UTC');
        utils.mysql.execute(conn, ['INSERT INTO transactions (obj_id, user_id, transdate, direction) ' ...
                                   'VALUES (?, ?, ?, ?)'], ids(j), userid, t, 'out');
        utils.helper.msg(msg.PROC1, 'updated transactions table');
      end

    end

  catch ex
    utils.helper.msg(msg.PROC1, '### retrieve error');
    rethrow(ex)
  end

  % Set outputs
  if nargout == 1
    if length(objs) == 1
      varargout{1} = objs{1};
    else
      varargout{1} = objs;
    end
  else
    for k=1:nargout
      varargout{k} = objs{k};
    end
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                               Local Functions                               %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function ii = getInfo(varargin)
  if nargin == 1 && strcmpi(varargin{1}, 'None')
    sets = {};
    pl   = [];
  else
    sets = {'Default'};
    pl   = getDefaultPlist;
  end
  % Build info object
  ii = minfo(mfilename, 'ltpda_uo', 'ltpda', utils.const.categories.internal, '$Id: retrieve.m,v 1.28 2011/07/01 14:38:57 ingo Exp $', sets, pl);
  ii.setModifier(false);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
function plout = getDefaultPlist()
  persistent pl;
  if exist('pl', 'var')==0 || isempty(pl)
    pl = buildplist();
  end
  plout = pl;
end

function plo = buildplist()
  plo = plist();

  p = param({'conn', 'A database object'}, paramValue.EMPTY_DOUBLE);
  plo.append(p);

  p = param({'ids', 'IDs which should be collected'}, paramValue.EMPTY_DOUBLE);
  plo.append(p);
end