changeset 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 2b57573b11c7
children 2f5c9bd7d95d
files m-toolbox/classes/@ltpda_uo/retrieve.m
diffstat 1 files changed, 92 insertions(+), 123 deletions(-) [+]
line wrap: on
line diff
--- a/m-toolbox/classes/@ltpda_uo/retrieve.m	Mon Dec 05 16:20:06 2011 +0100
+++ b/m-toolbox/classes/@ltpda_uo/retrieve.m	Mon Dec 05 16:20:06 2011 +0100
@@ -33,60 +33,37 @@
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
 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, 'mpipeline.repository.RepositoryConnection')
-    error('### the first argument should be a mpipeline.repository.RepositoryConnection connection object.');
+  if ~isa(conn, 'java.sql.Connection')
+    error('### the first argument should be a java.sql.Connection object');
   end
-  
-  % Unlock the connection only if the connection was not locked
-  unlockConnection = ~conn.isLocked();
-  
-  rm = LTPDARepositoryManager;
-  
+
   try
-    
-    if ~conn.isConnected
-      if isempty(conn.openConnection());
-        return
-      end
+
+    % 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
-    
-    conn.setLocked(true);
-    
-    % reload connection table if we have a GUI
-    if ~isempty(rm.gui)
-      rm.gui.reloadConnectionTable();
-    end
-    
-    % Get username and user id
-    username = char(conn.getUsername);
-    userid   = utils.jmysql.getUserID(conn, username);
-    
-    if ~isempty(userid)
-      utils.helper.msg(msg.PROC1, 'got user id %d for user: %s', userid, username);
-      if userid < 1 || isnan(userid)  || strcmp(userid, 'No Data') || ischar(userid)
-        error('### Unknown username.');
-      end
-    else
-      error('### Could not determine user id. Can not proceed.');
-    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)
@@ -95,59 +72,69 @@
       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
-        ids = mpipeline.repository.MySQLUtils.getObjectIDsFromCollectionID(conn, cid);
+        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
-      ids = mpipeline.repository.MySQLUtils.getObjectIDsFromCollectionID(conn, cid);
-      
+      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');
+      error('### incorrect usage');
     end
-    
-    utils.helper.msg(msg.PROC1, ['retrieving objects ' utils.xml.mat2str(ids)]);
-    
+
+    utils.helper.msg(msg.PROC1, ['retrieving objects' sprintf(' %d', ids)]);
+
     v = ver('LTPDA');
     for j=1:length(ids)
 
-      % 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.
-      q = sprintf('SELECT version FROM objmeta WHERE obj_id=%d', ids(j));
-      try
-      vDb = utils.jmysql.dbquery(conn, q);
-      catch ME
-        disp(ME);
-      end
-      if utils.helper.ver2num(v.Version) < utils.helper.ver2num(vDb{1})
-        error('### The object with the ID %d was submitted with a higher LTPDA version than you use %s. Please update your LTPDA version.', ids(j), vDb{1});
+      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
-      
-      % Get object
+      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
-        q =  sprintf('select mat from bobjs where obj_id="%d"', ids(j));
-        results = conn.query(q);
-        while results.next
-          dd = results.getObject(1);
+        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
-        
-        if strcmp(dd, 'No Data') || isempty(dd)
-          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+');
@@ -159,64 +146,49 @@
         delete(fname);
         % Get the struct out
         obj = obj.objs;
-        % Get the object class
-        scl = char(mpipeline.repository.MySQLUtils.getObjectTypeForID(conn, ids(j)));
 
         % Check if the retrieved object is a struct
         if isstruct(obj)
           % Call the constructor with this struct
-          fcn_name   = [scl '.update_struct'];
+          fcn_name   = [objtype '.update_struct'];
           obj = feval(fcn_name, obj, obj.tbxver);
-          obj = feval(scl, obj);
+          obj = feval(objtype, obj);
         end
         % Add tyo object array
         objs = [objs {obj}];
+
       else
-        xdoc = utils.jmysql.getXdoc(conn, ids(j));
-        if ~isempty(xdoc)
-          obj = utils.xml.xmlread(xdoc);
-          if j==1
-            objs = {obj};
-          else
-            objs = [objs {obj}];
-          end
-          
-          % make transaction entry
-          t     = time();
-          tdate = t.format('yyyy-mm-dd HH:MM:SS');
-          try
-            message = utils.jmysql.insert(conn, ...
-              'transactions',...
-              'obj_id', ids(j),...
-              'user_id', userid,...
-              'transdate', tdate,...
-              'direction', 'out'...
-              );
-            
-            utils.helper.msg(msg.PROC1, 'updated transactions table');
-          catch
-            error('### Failed to make entry in transactions table');
-          end
-        else
-          warning('!!! Error retrieving object: %d', ids(j));
-        end % End empty Xdoc
-      end % End binary
-    end % End id loop
-    
-  catch ME
-    fprintf(2, [ME.message, '\n\n']);
-    utils.helper.msg(msg.PROC1, '### Retrieve error.');
-    rethrow(ME)
+        % 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
-  
-  if unlockConnection
-    conn.setLocked(false);
-  end
-  
-  % reset Timer
-  LTPDARepositoryManager.resetTimer(rm.timerClearPass, conn);
-  LTPDARepositoryManager.resetTimer(rm.timerDisconnect, conn);
-      
+
   % Set outputs
   if nargout == 1
     if length(objs) == 1
@@ -253,22 +225,19 @@
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
 function plout = getDefaultPlist()
-  persistent pl;  
+  persistent pl;
   if exist('pl', 'var')==0 || isempty(pl)
     pl = buildplist();
   end
-  plout = pl;  
+  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
-
-
-