Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2010 Regents of the University of California and the
4
 *             National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: jones $'
7
 *     '$Date: 2010-02-03 17:58:12 -0900 (Wed, 03 Feb 2010) $'
8
 * '$Revision: 5211 $'
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 2 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
 */
24

    
25
package edu.ucsb.nceas.metacat;
26

    
27
import java.math.BigInteger;
28
import java.sql.PreparedStatement;
29
import java.sql.ResultSet;
30
import java.sql.SQLException;
31
import java.sql.Timestamp;
32
import java.util.ArrayList;
33
import java.util.Date;
34
import java.util.Hashtable;
35
import java.util.List;
36
import java.util.Vector;
37

    
38
import org.apache.log4j.Logger;
39
import org.dataone.client.ObjectFormatCache;
40
import org.dataone.service.exceptions.BaseException;
41
import org.dataone.service.exceptions.InvalidSystemMetadata;
42
import org.dataone.service.types.v1.AccessPolicy;
43
import org.dataone.service.types.v1.AccessRule;
44
import org.dataone.service.types.v1.Checksum;
45
import org.dataone.service.types.v1.Identifier;
46
import org.dataone.service.types.v1.NodeReference;
47
import org.dataone.service.types.v1.ObjectFormatIdentifier;
48
import org.dataone.service.types.v1.ObjectInfo;
49
import org.dataone.service.types.v1.ObjectList;
50
import org.dataone.service.types.v1.Permission;
51
import org.dataone.service.types.v1.Replica;
52
import org.dataone.service.types.v1.ReplicationPolicy;
53
import org.dataone.service.types.v1.ReplicationStatus;
54
import org.dataone.service.types.v1.Subject;
55
import org.dataone.service.types.v1.SystemMetadata;
56

    
57
import edu.ucsb.nceas.metacat.accesscontrol.XMLAccessAccess;
58
import edu.ucsb.nceas.metacat.database.DBConnection;
59
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
60
import edu.ucsb.nceas.metacat.database.DatabaseService;
61
import edu.ucsb.nceas.metacat.properties.PropertyService;
62
import edu.ucsb.nceas.metacat.shared.AccessException;
63
import edu.ucsb.nceas.metacat.shared.ServiceException;
64
import edu.ucsb.nceas.metacat.util.DocumentUtil;
65
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
66
import edu.ucsb.nceas.utilities.access.AccessControlInterface;
67
import edu.ucsb.nceas.utilities.access.XMLAccessDAO;
68

    
69
/**
70
 * Manage the relationship between Metacat local identifiers (LocalIDs) that are
71
 * codified as the (docid, rev) pair with globally unique string identifiers
72
 * (GUIDs) that are opaque strings.  This class provides methods to manage these
73
 * identifiers, and to search for and look up LocalIDs based on their GUID and
74
 * vice versa. IdentifierManager is a singleton.
75
 * 
76
 * @author Matthew Jones
77
 */
78
public class IdentifierManager {
79
    
80
    public static final String TYPE_SYSTEM_METADATA = "systemmetadata";
81
    public static final String TYPE_IDENTIFIER = "identifier";
82
  
83
    /**
84
     * The single instance of the manager that is always returned.
85
     */
86
    private static IdentifierManager self = null;
87
    private Logger logMetacat = Logger.getLogger(IdentifierManager.class);
88

    
89
    /**
90
     * A private constructor that initializes the class when getInstance() is
91
     * called.
92
     */
93
    private IdentifierManager() {}
94

    
95
    /**
96
     * Return the single instance of the manager after initializing it if it
97
     * wasn't previously initialized.
98
     * 
99
     * @return the single IdentifierManager instance
100
     */
101
    public static IdentifierManager getInstance()
102
    {
103
        if (self == null) {
104
            self = new IdentifierManager();
105
        }
106
        return self;
107
    }
108
    
109
    public SystemMetadata asSystemMetadata(Date dateUploaded, String rightsHolder,
110
            String checksum, String checksumAlgorithm, String originMemberNode,
111
            String authoritativeMemberNode, Date dateModified, String submitter, 
112
            String guid, String fmtidStr, BigInteger size, BigInteger serialVersion) {
113
        SystemMetadata sysMeta = new SystemMetadata();
114

    
115
        Identifier sysMetaId = new Identifier();
116
        sysMetaId.setValue(guid);
117
        sysMeta.setIdentifier(sysMetaId);
118
        sysMeta.setDateUploaded(dateUploaded);
119
        Subject rightsHolderSubject = new Subject();
120
        rightsHolderSubject.setValue(rightsHolder);
121
        sysMeta.setRightsHolder(rightsHolderSubject);
122
        Checksum checksumObject = new Checksum();
123
        checksumObject.setValue(checksum);
124
        checksumObject.setAlgorithm(checksumAlgorithm);
125
        sysMeta.setChecksum(checksumObject);
126
        NodeReference omn = new NodeReference();
127
        omn.setValue(originMemberNode);
128
        sysMeta.setOriginMemberNode(omn);
129
        NodeReference amn = new NodeReference();
130
        amn.setValue(authoritativeMemberNode);
131
        sysMeta.setAuthoritativeMemberNode(amn);
132
        sysMeta.setDateSysMetadataModified(dateModified);
133
        Subject submitterSubject = new Subject();
134
        submitterSubject.setValue(submitter);
135
        sysMeta.setSubmitter(submitterSubject);
136
        ObjectFormatIdentifier fmtid = null;
137
        try {
138
        	ObjectFormatIdentifier formatId = new ObjectFormatIdentifier();
139
        	formatId.setValue(fmtidStr);
140
        	fmtid = ObjectFormatCache.getInstance().getFormat(formatId).getFormatId();
141
        	sysMeta.setFormatId(fmtid);
142
        	
143
        } catch (BaseException nfe) {
144
            logMetacat.error("The objectFormat " + fmtidStr +
145
          	" is not registered. Setting the default format id.");
146
            fmtid = new ObjectFormatIdentifier();
147
            fmtid.setValue("application/octet-stream");
148
            sysMeta.setFormatId(fmtid);
149
            
150
        }
151
        sysMeta.setSize(size);
152
        sysMeta.setSerialVersion(serialVersion);
153
        
154
        return sysMeta;
155
    }
156
    
157
    /**
158
     * return a hash of all of the info that is in the systemmetadata table
159
     * @param localId
160
     * @return
161
     */
162
    public Hashtable<String, String> getSystemMetadataInfo(String localId)
163
    throws McdbDocNotFoundException
164
    {
165
        try
166
        {
167
            AccessionNumber acc = new AccessionNumber(localId, "NONE");
168
            localId = acc.getDocid();
169
        }
170
        catch(Exception e)
171
        {
172
            //do nothing. just try the localId as it is
173
        }
174
        Hashtable<String, String> h = new Hashtable<String, String>();
175
        String sql = "select guid, date_uploaded, rights_holder, checksum, checksum_algorithm, " +
176
          "origin_member_node, authoritive_member_node, date_modified, submitter, object_format, size " +
177
          "from systemmetadata where docid = ?";
178
        DBConnection dbConn = null;
179
        int serialNumber = -1;
180
        try 
181
        {
182
            // Get a database connection from the pool
183
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getDocumentInfo");
184
            serialNumber = dbConn.getCheckOutSerialNumber();
185

    
186
            // Execute the insert statement
187
            PreparedStatement stmt = dbConn.prepareStatement(sql);
188
            stmt.setString(1, localId);
189
            ResultSet rs = stmt.executeQuery();
190
            if (rs.next()) 
191
            {
192
                String guid = rs.getString(1);
193
                Timestamp dateUploaded = rs.getTimestamp(2);
194
                String rightsHolder = rs.getString(3);
195
                String checksum = rs.getString(4);
196
                String checksumAlgorithm = rs.getString(5);
197
                String originMemberNode = rs.getString(6);
198
                String authoritativeMemberNode = rs.getString(7);
199
                Timestamp dateModified = rs.getTimestamp(8);
200
                String submitter = rs.getString(9);
201
                String objectFormat = rs.getString(10);
202
                long size = new Long(rs.getString(11)).longValue();
203
                
204
                h.put("guid", guid);
205
                h.put("date_uploaded", new Long(dateUploaded.getTime()).toString());
206
                h.put("rights_holder", rightsHolder);
207
                h.put("checksum", checksum);
208
                h.put("checksum_algorithm", checksumAlgorithm);
209
                h.put("origin_member_node", originMemberNode);
210
                h.put("authoritative_member_node", authoritativeMemberNode);
211
                h.put("date_modified", new Long(dateModified.getTime()).toString());
212
                h.put("submitter", submitter);
213
                h.put("object_format", objectFormat);
214
                h.put("size", new Long(size).toString());
215
                
216
                stmt.close();
217
            } 
218
            else
219
            {
220
                stmt.close();
221
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
222
                throw new McdbDocNotFoundException("2Could not find document " + localId);
223
            }
224
            
225
        } 
226
        catch (SQLException e) 
227
        {
228
            e.printStackTrace();
229
            logMetacat.error("Error while getting system metadata info for localid " + localId + " : "  
230
                    + e.getMessage());
231
        } 
232
        finally 
233
        {
234
            // Return database connection to the pool
235
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
236
        }
237
        return h;
238
    }
239
    
240
    /**
241
     * return a hash of all of the info that is in the systemmetadata table
242
     * @param guid
243
     * @return
244
     * @throws McdbDocNotFoundException 
245
     */
246
    public SystemMetadata getSystemMetadata(String guid)
247
    	throws McdbDocNotFoundException
248
    {
249
        
250
        SystemMetadata sysMeta = new SystemMetadata();
251
        String sql = "select guid, date_uploaded, rights_holder, checksum, checksum_algorithm, " +
252
          "origin_member_node, authoritive_member_node, date_modified, submitter, object_format, size, " +
253
          "replication_allowed, number_replicas, obsoletes, obsoleted_by, serial_version, archived " +
254
          "from systemmetadata where guid = ?";
255
        DBConnection dbConn = null;
256
        int serialNumber = -1;
257
        Boolean replicationAllowed = new Boolean(false);
258
        BigInteger numberOfReplicas = new BigInteger("-1");
259
        BigInteger serialVersion = new BigInteger("-1");
260
        Boolean archived = new Boolean(false);
261

    
262
        try 
263
        {
264
            // Get a database connection from the pool
265
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getSystemMetadata");
266
            serialNumber = dbConn.getCheckOutSerialNumber();
267

    
268
            // Execute the statement
269
            PreparedStatement stmt = dbConn.prepareStatement(sql);
270
            stmt.setString(1, guid);
271
            ResultSet rs = stmt.executeQuery();
272
            if (rs.next()) 
273
            {
274
                Timestamp dateUploaded = rs.getTimestamp(2);
275
                String rightsHolder = rs.getString(3);
276
                String checksum = rs.getString(4);
277
                String checksumAlgorithm = rs.getString(5);
278
                String originMemberNode = rs.getString(6);
279
                String authoritativeMemberNode = rs.getString(7);
280
                Timestamp dateModified = rs.getTimestamp(8);
281
                String submitter = rs.getString(9);
282
                String fmtidStr = rs.getString(10);
283
                BigInteger size = new BigInteger(rs.getString(11));
284
                replicationAllowed = new Boolean(rs.getBoolean(12));
285
                numberOfReplicas = new BigInteger(rs.getString(13));
286
                String obsoletes = rs.getString(14);
287
                String obsoletedBy = rs.getString(15);
288
                serialVersion = new BigInteger(rs.getString(16));
289
                archived = new Boolean(rs.getBoolean(17));
290

    
291
                Identifier sysMetaId = new Identifier();
292
                sysMetaId.setValue(guid);
293
                sysMeta.setIdentifier(sysMetaId);
294
                sysMeta.setSerialVersion(serialVersion);
295
                sysMeta.setDateUploaded(dateUploaded);
296
                Subject rightsHolderSubject = new Subject();
297
                rightsHolderSubject.setValue(rightsHolder);
298
                sysMeta.setRightsHolder(rightsHolderSubject);
299
                Checksum checksumObject = new Checksum();
300
                checksumObject.setValue(checksum);
301
                checksumObject.setAlgorithm(checksumAlgorithm);
302
                sysMeta.setChecksum(checksumObject);
303
                if (originMemberNode != null) {
304
	                NodeReference omn = new NodeReference();
305
	                omn.setValue(originMemberNode);
306
	                sysMeta.setOriginMemberNode(omn);
307
                }
308
                if (authoritativeMemberNode != null) {
309
	                NodeReference amn = new NodeReference();
310
	                amn.setValue(authoritativeMemberNode);
311
	                sysMeta.setAuthoritativeMemberNode(amn);
312
                }
313
                sysMeta.setDateSysMetadataModified(dateModified);
314
                if (submitter != null) {
315
	                Subject submitterSubject = new Subject();
316
	                submitterSubject.setValue(submitter);
317
	                sysMeta.setSubmitter(submitterSubject);
318
                }
319
                ObjectFormatIdentifier fmtid = new ObjectFormatIdentifier();
320
                fmtid.setValue(fmtidStr);
321
            	sysMeta.setFormatId(fmtid);
322
                sysMeta.setSize(size);
323
                if (obsoletes != null) {
324
	                Identifier obsoletesId = new Identifier();
325
	                obsoletesId.setValue(obsoletes);
326
	                sysMeta.setObsoletes(obsoletesId);
327
                }
328
                if (obsoletedBy != null) {
329
		            Identifier obsoletedById = new Identifier();
330
		            obsoletedById.setValue(obsoletedBy);
331
		            sysMeta.setObsoletedBy(obsoletedById);
332
                }
333
                sysMeta.setArchived(archived);
334
                stmt.close();
335
            } 
336
            else
337
            {
338
                stmt.close();
339
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
340
                throw new McdbDocNotFoundException("Could not find " + guid);
341
            }
342
            
343
        } 
344
        catch (SQLException e) 
345
        {
346
            e.printStackTrace();
347
            logMetacat.error("Error while getting system metadata for guid " + guid + " : "  
348
                    + e.getMessage());
349
        } 
350
        finally 
351
        {
352
            // Return database connection to the pool
353
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
354
        }
355

    
356
        // populate the replication policy
357
        ReplicationPolicy replicationPolicy = new ReplicationPolicy();
358
        if ( numberOfReplicas != null  && numberOfReplicas.intValue() != -1 ) {
359
            replicationPolicy.setNumberReplicas(numberOfReplicas.intValue());
360
            
361
        }
362
        
363
        if ( replicationAllowed != null ) {
364
            replicationPolicy.setReplicationAllowed(replicationAllowed);
365
            
366
        }
367
        replicationPolicy.setBlockedMemberNodeList(getReplicationPolicy(guid, "blocked"));
368
        replicationPolicy.setPreferredMemberNodeList(getReplicationPolicy(guid, "preferred"));
369
		    sysMeta.setReplicationPolicy(replicationPolicy);
370
		
371
		    // look up replication status
372
		    sysMeta.setReplicaList(getReplicationStatus(guid));
373
		
374
		    // look up access policy
375
		    try {
376
		    	sysMeta.setAccessPolicy(getAccessPolicy(guid));
377
		    } catch (AccessException e) {
378
		    	throw new McdbDocNotFoundException(e);
379
		    }
380
        
381
        return sysMeta;
382
    }
383
    
384
    
385
    private List<NodeReference> getReplicationPolicy(String guid, String policy)
386
		throws McdbDocNotFoundException {
387
		
388
		List<NodeReference> nodes = new ArrayList<NodeReference>();
389
		String sql = "select guid, policy, member_node " +
390
			"from smReplicationPolicy where guid = ? and policy = ?";
391
	    DBConnection dbConn = null;
392
	    int serialNumber = -1;
393
	    try {
394
	        // Get a database connection from the pool
395
	        dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getReplicationPolicy");
396
	        serialNumber = dbConn.getCheckOutSerialNumber();
397
	
398
	        // Execute the statement
399
	        PreparedStatement stmt = dbConn.prepareStatement(sql);
400
	        stmt.setString(1, guid);
401
	        stmt.setString(2, policy);
402
	        ResultSet rs = stmt.executeQuery();
403
	        while (rs.next()) 
404
	        {
405
	            String memberNode = rs.getString(3);
406
	            NodeReference node = new NodeReference();
407
	            node.setValue(memberNode);
408
	            nodes.add(node);
409
	        
410
	        } 
411
	        stmt.close();
412
	        
413
	    } catch (SQLException e) {
414
	        logMetacat.error("Error while getting system metadata replication policy for guid " + guid, e);
415
	    } 
416
	    finally {
417
	        // Return database connection to the pool
418
	        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
419
	    }
420
	    
421
	    return nodes;
422
	}
423
    
424
    private List<Replica> getReplicationStatus(String guid) throws McdbDocNotFoundException {
425
		
426
		List<Replica> replicas = new ArrayList<Replica>();
427
		String sql = "select guid, member_node, status, date_verified " +
428
			"from smReplicationStatus where guid = ?";
429
	    DBConnection dbConn = null;
430
	    int serialNumber = -1;
431
	    try {
432
	        // Get a database connection from the pool
433
	        dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getReplicas");
434
	        serialNumber = dbConn.getCheckOutSerialNumber();
435
	
436
	        // Execute the statement
437
	        PreparedStatement stmt = dbConn.prepareStatement(sql);
438
	        stmt.setString(1, guid);
439
	        ResultSet rs = stmt.executeQuery();
440
	        while (rs.next()) 
441
	        {
442
	            String memberNode = rs.getString(2);
443
	            String status = rs.getString(3);
444
	            java.sql.Timestamp verified = rs.getTimestamp(4);
445
	            
446
	            Replica replica = new Replica();	            
447
	            NodeReference node = new NodeReference();
448
	            node.setValue(memberNode);
449
	            replica.setReplicaMemberNode(node);
450
	            replica.setReplicationStatus(ReplicationStatus.valueOf(status));
451
	            replica.setReplicaVerified(new Date(verified.getTime()));
452
	            replicas.add(replica);
453
	        } 
454
	        stmt.close();
455
	        
456
	    } catch (SQLException e) {
457
	        logMetacat.error("Error while getting system metadata replication policy for guid " + guid, e);
458
	    } 
459
	    finally {
460
	        // Return database connection to the pool
461
	        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
462
	    }
463
	    
464
	    return replicas;
465
	}
466
    
467
    
468
    /**
469
     * return the newest rev for a given localId
470
     * @param localId
471
     * @return
472
     */
473
    public int getLatestRevForLocalId(String localId)
474
        throws McdbDocNotFoundException
475
    {
476
        try
477
        {
478
            AccessionNumber acc = new AccessionNumber(localId, "NONE");
479
            localId = acc.getDocid();
480
        }
481
        catch(Exception e)
482
        {
483
            //do nothing. just try the localId as it is
484
        }
485
        int rev = 0;
486
        String sql = "select rev from xml_documents where docid like ? ";
487
        DBConnection dbConn = null;
488
        int serialNumber = -1;
489
        try 
490
        {
491
            // Get a database connection from the pool
492
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getLatestRevForLocalId");
493
            serialNumber = dbConn.getCheckOutSerialNumber();
494

    
495
            // Execute the insert statement
496
            PreparedStatement stmt = dbConn.prepareStatement(sql);
497
            stmt.setString(1, localId);
498
            ResultSet rs = stmt.executeQuery();
499
            if (rs.next()) 
500
            {
501
                rev = rs.getInt(1);
502
                stmt.close();
503
            } 
504
            else
505
            {
506
                stmt.close();
507
                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
508
                throw new McdbDocNotFoundException("While trying to get the latest rev, could not find document " + localId);
509
            }
510
        } 
511
        catch (SQLException e) 
512
        {
513
            logMetacat.error("Error while looking up the guid: " 
514
                    + e.getMessage());
515
        } 
516
        finally 
517
        {
518
            // Return database connection to the pool
519
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
520
        }
521
        return rev;
522
    }
523
    
524
    /**
525
     * return all local ids in the object store that do not have associated
526
     * system metadata
527
     */
528
    public List<String> getLocalIdsWithNoSystemMetadata(boolean includeRevisions, int serverLocation)
529
    {
530
        Vector<String> ids = new Vector<String>();
531
        String sql = "select docid, rev from xml_documents " +
532
        		"where docid not in " +
533
        		"(select docid from identifier where guid in (select guid from systemmetadata))";
534
        if (serverLocation > 0) {
535
        	sql = sql + " and server_location = ? ";
536
        }
537
        
538
        String revisionSql = "select docid, rev from xml_revisions " +
539
				"where docid not in " +
540
				"(select docid from identifier where guid in (select guid from systemmetadata))";
541
        if (serverLocation > 0) {
542
        	revisionSql = revisionSql + " and server_location = ? ";
543
        }
544
        
545
        if (includeRevisions) {
546
        	sql = sql + " UNION ALL " + revisionSql;
547
        }
548
        
549
        DBConnection dbConn = null;
550
        int serialNumber = -1;
551
        try 
552
        {
553
            // Get a database connection from the pool
554
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getLocalIdsWithNoSystemMetadata");
555
            serialNumber = dbConn.getCheckOutSerialNumber();
556

    
557
            // Execute the insert statement
558
            PreparedStatement stmt = dbConn.prepareStatement(sql);
559
            // set params based on what we have in the query string
560
            if (serverLocation > 0) {
561
            	stmt.setInt(1, serverLocation);
562
            	if (includeRevisions) {
563
            		stmt.setInt(2, serverLocation);
564
            	}
565
            }
566
            ResultSet rs = stmt.executeQuery();
567
            while (rs.next()) 
568
            {
569
                String localid = rs.getString(1);
570
                String rev = rs.getString(2);
571
                localid += "." + rev;
572
                logMetacat.debug("id to add SM for: " + localid);
573
                ids.add(localid);
574
            } 
575
            stmt.close();
576
        } 
577
        catch (SQLException e) 
578
        {
579
            logMetacat.error("Error while looking up the guid: " 
580
                    + e.getMessage());
581
        } 
582
        finally 
583
        {
584
            // Return database connection to the pool
585
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
586
        }
587
        
588
        return ids;
589
    }
590
    
591
    /**
592
     * return a listing of all local ids in the object store
593
     * @return a list of all local ids in metacat
594
     */
595
    public List<String> getAllLocalIds()
596
    // seems to be an unnecessary and restrictive throw -rnahf 13-Sep-2011
597
    //    throws Exception
598
    {
599
        Vector<String> ids = new Vector<String>();
600
        String sql = "select docid from xml_documents";
601
        DBConnection dbConn = null;
602
        int serialNumber = -1;
603
        try 
604
        {
605
            // Get a database connection from the pool
606
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getAllLocalIds");
607
            serialNumber = dbConn.getCheckOutSerialNumber();
608

    
609
            // Execute the insert statement
610
            PreparedStatement stmt = dbConn.prepareStatement(sql);
611
            ResultSet rs = stmt.executeQuery();
612
            while (rs.next()) 
613
            {
614
                String localid = rs.getString(1);
615
                ids.add(localid);
616
            } 
617
            stmt.close();
618
        } 
619
        catch (SQLException e) 
620
        {
621
            logMetacat.error("Error while looking up the guid: " 
622
                    + e.getMessage());
623
        } 
624
        finally 
625
        {
626
            // Return database connection to the pool
627
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
628
        }
629
        return ids;
630
    }
631
    
632
    
633
    /**
634
     * return a listing of all guids in the object store
635
     * @return a list of all GUIDs in metacat
636
     */
637
    public List<String> getAllSystemMetadataGUIDs()
638
    {
639
        Vector<String> guids = new Vector<String>();
640
        String sql = "select guid from systemmetadata";
641
        DBConnection dbConn = null;
642
        int serialNumber = -1;
643
        try 
644
        {
645
            // Get a database connection from the pool
646
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getAllGUIDs");
647
            serialNumber = dbConn.getCheckOutSerialNumber();
648

    
649
            // Execute the insert statement
650
            PreparedStatement stmt = dbConn.prepareStatement(sql);
651
            ResultSet rs = stmt.executeQuery();
652
            while (rs.next()) 
653
            {
654
                String guid = rs.getString(1);
655
                guids.add(guid);
656
            } 
657
            stmt.close();
658
        } 
659
        catch (SQLException e) 
660
        {
661
            logMetacat.error("Error while retrieving the guid: " 
662
                    + e.getMessage());
663
        } 
664
        finally 
665
        {
666
            // Return database connection to the pool
667
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
668
        }
669
        return guids;
670
    }
671
    
672
    
673
    
674
    /**
675
     * returns a list of system metadata-only guids since the given date
676
     * @return a list of system ids in metacat that do not correspond to objects
677
     * TODO: need to check which server they are on
678
     */
679
    public List<String> getUpdatedSystemMetadataIds(Date since)
680
       throws Exception
681
    {
682
        List<String> ids = new Vector<String>();
683
        String sql = 
684
        	"select guid from " + TYPE_SYSTEM_METADATA +
685
        	" where guid not in " +
686
        	" (select guid from " + TYPE_IDENTIFIER + ") " +
687
        	" and date_modified > ?";
688
        DBConnection dbConn = null;
689
        int serialNumber = -1;
690
        try 
691
        {
692
            // Get a database connection from the pool
693
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getUpdatedSystemMetadataIds");
694
            serialNumber = dbConn.getCheckOutSerialNumber();
695

    
696
            // Execute the insert statement
697
            PreparedStatement stmt = dbConn.prepareStatement(sql);
698
            stmt.setDate(1, new java.sql.Date(since.getTime()));
699
            ResultSet rs = stmt.executeQuery();
700
            while (rs.next()) 
701
            {
702
                String guid = rs.getString(1);
703
                ids.add(guid);
704
            } 
705
            stmt.close();
706
        } 
707
        catch (SQLException e) 
708
        {
709
            logMetacat.error("Error while looking up the updated guids: " 
710
                    + e.getMessage());
711
        } 
712
        finally 
713
        {
714
            // Return database connection to the pool
715
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
716
        }
717
        return ids;
718
    }
719
    
720
    /**
721
     * returns a list of system metadata-only guids since the given date
722
     * @return a list of system ids in metacat that do not correspond to objects
723
     * TODO: need to check which server they are on
724
     */
725
    public Date getLastModifiedDate() throws Exception {
726
        Date maxDate = null;
727

    
728
        List<String> ids = new Vector<String>();
729
        String sql = 
730
        	"select max(date_modified) from " + TYPE_SYSTEM_METADATA;
731
        DBConnection dbConn = null;
732
        int serialNumber = -1;
733
        try 
734
        {
735
            // Get a database connection from the pool
736
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getLastModifiedDate");
737
            serialNumber = dbConn.getCheckOutSerialNumber();
738

    
739
            // Execute the insert statement
740
            PreparedStatement stmt = dbConn.prepareStatement(sql);
741
            ResultSet rs = stmt.executeQuery();
742
            if (rs.next()) {
743
            	maxDate = rs.getDate(1);
744
            } 
745
            stmt.close();
746
        } 
747
        catch (SQLException e) 
748
        {
749
            logMetacat.error("Error while looking up the latest update date: " 
750
                    + e.getMessage());
751
        } 
752
        finally 
753
        {
754
            // Return database connection to the pool
755
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
756
        }
757
        return maxDate;
758
    }
759

    
760
    
761
    /**
762
     * Determine if an identifier exists already, returning true if so.
763
     * NOTE: looks in the identifier and system metadata table for a match
764
     * (in that order)
765
     * 
766
     * @param guid the global identifier to look up
767
     * @return boolean true if the identifier exists
768
     */
769
    public boolean identifierExists(String guid)
770
    {
771
        boolean idExists = false;
772
        try {
773
            String id = getLocalId(guid);
774
            if (id != null) {
775
                idExists = true;
776
            }
777
        } catch (McdbDocNotFoundException e) {
778
        	// try system metadata only
779
        	try {
780
        		idExists = systemMetadataExists(guid);
781
            } catch (Exception e2) {
782
            	idExists = false;
783
            }
784
        }
785
        return idExists;
786
    }
787
    
788
    /**
789
     * Determine if an identifier mapping exists already, 
790
     * returning true if so.
791
     * 
792
     * @param guid the global identifier to look up
793
     * @return boolean true if the identifier exists
794
     */
795
    public boolean mappingExists(String guid)
796
    {
797
        boolean idExists = false;
798
        try {
799
            String id = getLocalId(guid);
800
            if (id != null) {
801
                idExists = true;
802
            }
803
        } catch (McdbDocNotFoundException e) {
804
        	// nope!
805
        }
806
        return idExists;
807
    }
808
    
809
    /**
810
     * 
811
     * @param guid
812
     * @param rev
813
     * @return
814
     */
815
    public String generateLocalId(String guid, int rev)
816
    {
817
        return generateLocalId(guid, rev, false);
818
    }
819

    
820
    /**
821
     * Given a global identifier (guid), create a suitable local identifier that
822
     * follows Metacat's docid semantics and format (scope.id.rev), and create
823
     * a mapping between these two identifiers.  This effectively reserves both
824
     * the global and the local identifier, as they will now be present in the
825
     * identifier mapping table.  
826
     * 
827
     * REMOVED feature: If the incoming guid has the syntax of a
828
     * Metacat docid (scope.id.rev), then simply use it.
829
     * WHY: because "test.1.001" becomes "test.1.1" which is not correct for DataONE
830
     * identifier use (those revision numbers are just chartacters and should not be interpreted)
831
     * 
832
     * @param guid the global string identifier
833
     * @param rev the revision number to be used in the localId
834
     * @return String containing the localId to be used for Metacat operations
835
     */
836
    public String generateLocalId(String guid, int rev, boolean isSystemMetadata) 
837
    {
838
        String localId = "";
839
        boolean conformsToDocidFormat = false;
840
        
841
        // BRL -- do not allow Metacat-conforming IDs to be used:
842
        // test.1.001 becomes test.1.1 which is NOT correct for DataONE identifiers
843
        // Check if the guid passed in is already in docid (scope.id.rev) format
844
//        try {
845
//            AccessionNumber acc = new AccessionNumber(guid, "NONE");
846
//            if (new Integer(acc.getRev()).intValue() > 0) {
847
//                conformsToDocidFormat = true;
848
//            }
849
//        } catch (NumberFormatException e) {
850
//            // No action needed, simply detecting invalid AccessionNumbers
851
//        } catch (AccessionNumberException e) {
852
//            // No action needed, simply detecting invalid AccessionNumbers
853
//        } catch (SQLException e) {
854
//            // No action needed, simply detecting invalid AccessionNumbers
855
//        }
856
        
857
        if (conformsToDocidFormat) {
858
            // if it conforms, use it for both guid and localId
859
            localId = guid;
860
        } else {
861
            // if not, then generate a new unique localId
862
            localId = DocumentUtil.generateDocumentId(rev);
863
        }
864
        
865
        // Register this new pair in the identifier mapping table
866
        logMetacat.debug("creating mapping in generateLocalId");
867
        if(!isSystemMetadata)
868
        { //don't do this if we're generating for system metadata
869
            createMapping(guid, localId);
870
        }
871
        
872
        return localId;
873
    }
874
    
875
    /**
876
     * given a local identifer, look up the guid.  Throw McdbDocNotFoundException
877
     * if the docid, rev is not found in the identifiers or systemmetadata tables
878
     *
879
     * @param docid the docid to look up
880
     * @param rev the revision of the docid to look up
881
     * @return String containing the mapped guid
882
     * @throws McdbDocNotFoundException if the docid, rev is not found
883
     */
884
    public String getGUID(String docid, int rev)
885
      throws McdbDocNotFoundException
886
    {
887
        logMetacat.debug("getting guid for " + docid);
888
        String query = "select guid from identifier where docid = ? and rev = ?";
889
        String guid = null;
890
        
891
        DBConnection dbConn = null;
892
        int serialNumber = -1;
893
        try {
894
            // Get a database connection from the pool
895
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.getGUID");
896
            serialNumber = dbConn.getCheckOutSerialNumber();
897
            
898
            // Execute the insert statement
899
            PreparedStatement stmt = dbConn.prepareStatement(query);
900
            stmt.setString(1, docid);
901
            stmt.setInt(2, rev);
902
            ResultSet rs = stmt.executeQuery();
903
            if (rs.next()) 
904
            {
905
                guid = rs.getString(1);
906
            } 
907
            else
908
            {
909
            	throw new McdbDocNotFoundException("No guid registered for docid " + docid + "." + rev);
910
            }
911
            
912
        } catch (SQLException e) {
913
            logMetacat.error("Error while looking up the guid: " 
914
                    + e.getMessage());
915
        } finally {
916
            // Return database connection to the pool
917
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
918
        }
919
        
920
        return guid;
921
    }
922
    
923
    public boolean systemMetadataExists(String guid) {
924
		logMetacat.debug("looking up system metadata for guid " + guid);
925
		boolean exists = false;
926
		String query = "select guid from systemmetadata where guid = ?";
927

    
928
		DBConnection dbConn = null;
929
		int serialNumber = -1;
930
		try {
931
			// Get a database connection from the pool
932
			dbConn = DBConnectionPool.getDBConnection("IdentifierManager.systemMetadataExisits");
933
			serialNumber = dbConn.getCheckOutSerialNumber();
934

    
935
			// Execute the insert statement
936
			PreparedStatement stmt = dbConn.prepareStatement(query);
937
			stmt.setString(1, guid);
938
			ResultSet rs = stmt.executeQuery();
939
			if (rs.next()) {
940
				exists = true;
941
			}
942

    
943
		} catch (SQLException e) {
944
			logMetacat.error("Error while looking up the system metadata: "
945
					+ e.getMessage());
946
		} finally {
947
			// Return database connection to the pool
948
			DBConnectionPool.returnDBConnection(dbConn, serialNumber);
949
		}
950

    
951
		return exists;
952
	}
953
    
954
    /**
955
     * creates a system metadata mapping and adds additional fields from sysmeta
956
     * to the table for quick searching.
957
     * 
958
     * @param guid the id to insert
959
     * @param localId the systemMetadata object to get the local id for
960
     * @throws McdbDocNotFoundException 
961
     * @throws SQLException 
962
     * @throws InvalidSystemMetadata 
963
     */
964
    public void insertOrUpdateSystemMetadata(SystemMetadata sysmeta) 
965
        throws McdbDocNotFoundException, SQLException, InvalidSystemMetadata {
966
    	String guid = sysmeta.getIdentifier().getValue();
967
    	
968
    	 // Get a database connection from the pool
969
        DBConnection dbConn = DBConnectionPool.getDBConnection("IdentifierManager.insertSystemMetadata");
970
        int serialNumber = dbConn.getCheckOutSerialNumber();
971
        
972
        try {
973
        	// use a single transaction for it all
974
        	dbConn.setAutoCommit(false);
975
        	
976
	    	// insert the record if needed
977
        	if (!IdentifierManager.getInstance().systemMetadataExists(guid)) {
978
    	        insertSystemMetadata(guid, dbConn);
979
			}
980
	        // update with the values
981
	        updateSystemMetadata(sysmeta, dbConn);
982
	        
983
	        // commit if we got here with no errors
984
	        dbConn.commit();
985
        } catch (Exception e) {
986
            e.printStackTrace();
987
            logMetacat.error("Error while creating " + TYPE_SYSTEM_METADATA + " record: " + guid, e );
988
            dbConn.rollback();
989
        } finally {
990
            // Return database connection to the pool
991
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
992
        }
993
        
994
        
995
    }
996
        
997
    
998
    /**
999
     * update a mapping
1000
     * @param guid
1001
     * @param localId
1002
     */
1003
    public void updateMapping(String guid, String localId)
1004
    {
1005
    	
1006
        logMetacat.debug("$$$$$$$$$$$$$$ updating mapping table");
1007
        int serialNumber = -1;
1008
        DBConnection dbConn = null;
1009
        try {
1010
            // Parse the localId into scope and rev parts
1011
            AccessionNumber acc = new AccessionNumber(localId, "NOACTION");
1012
            String docid = acc.getDocid();
1013
            int rev = 1;
1014
            if(acc.getRev() != null)
1015
            {
1016
              rev = (new Integer(acc.getRev()).intValue());
1017
            }
1018

    
1019
            // Get a database connection from the pool
1020
            dbConn = 
1021
                DBConnectionPool.getDBConnection("IdentifierManager.updateMapping");
1022
            serialNumber = dbConn.getCheckOutSerialNumber();
1023

    
1024
            // Execute the update statement
1025
            String query = "update " + TYPE_IDENTIFIER + " set (docid, rev) = (?, ?) where guid = ?";
1026
            PreparedStatement stmt = dbConn.prepareStatement(query);
1027
            stmt.setString(1, docid);
1028
            stmt.setInt(2, rev);
1029
            stmt.setString(3, guid);
1030
            int rows = stmt.executeUpdate();
1031

    
1032
            stmt.close();
1033
        } catch (SQLException e) {
1034
            e.printStackTrace();
1035
            logMetacat.error("SQL error while updating a mapping identifier: " 
1036
                    + e.getMessage());
1037
        } catch (NumberFormatException e) {
1038
            e.printStackTrace();
1039
            logMetacat.error("NumberFormat error while updating a mapping identifier: " 
1040
                    + e.getMessage());
1041
        } catch (AccessionNumberException e) {
1042
            e.printStackTrace();
1043
            logMetacat.error("AccessionNumber error while updating a mapping identifier: " 
1044
                    + e.getMessage());
1045
        } finally {
1046
            // Return database connection to the pool
1047
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1048
        }
1049
        logMetacat.debug("done updating mapping");
1050
    }
1051
        
1052
    private void updateSystemMetadataFields(long dateUploaded, String rightsHolder,
1053
        String checksum, String checksumAlgorithm, String originMemberNode, 
1054
        String authoritativeMemberNode, long modifiedDate, String submitter, 
1055
        String guid, String objectFormat, BigInteger size, boolean archived,
1056
        boolean replicationAllowed, int numberReplicas, String obsoletes,
1057
        String obsoletedBy, BigInteger serialVersion, DBConnection dbConn) throws SQLException  {
1058
  
1059
        // Execute the insert statement
1060
        String query = "update " + TYPE_SYSTEM_METADATA + 
1061
            " set (date_uploaded, rights_holder, checksum, checksum_algorithm, " +
1062
            "origin_member_node, authoritive_member_node, date_modified, " +
1063
            "submitter, object_format, size, archived, replication_allowed, number_replicas, " +
1064
            "obsoletes, obsoleted_by, serial_version) " +
1065
            "= (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) where guid = ?";
1066
        PreparedStatement stmt = dbConn.prepareStatement(query);
1067
        
1068
        //data values
1069
        stmt.setTimestamp(1, new java.sql.Timestamp(dateUploaded));
1070
        stmt.setString(2, rightsHolder);
1071
        stmt.setString(3, checksum);
1072
        stmt.setString(4, checksumAlgorithm);
1073
        stmt.setString(5, originMemberNode);
1074
        stmt.setString(6, authoritativeMemberNode);
1075
        stmt.setTimestamp(7, new java.sql.Timestamp(modifiedDate));
1076
        stmt.setString(8, submitter);
1077
        stmt.setString(9, objectFormat);
1078
        stmt.setString(10, size.toString());
1079
        stmt.setBoolean(11, archived);
1080
        stmt.setBoolean(12, replicationAllowed);
1081
        stmt.setInt(13, numberReplicas);
1082
        stmt.setString(14, obsoletes);
1083
        stmt.setString(15, obsoletedBy);
1084
        stmt.setString(16, serialVersion.toString());
1085

    
1086
        //where clause
1087
        stmt.setString(17, guid);
1088
        logMetacat.debug("stmt: " + stmt.toString());
1089
        //execute
1090
        int rows = stmt.executeUpdate();
1091

    
1092
        stmt.close();
1093
               
1094
    }
1095
    
1096
    private void insertReplicationPolicy(String guid, String policy, List<String> memberNodes, DBConnection dbConn) throws SQLException
1097
    {
1098
           
1099
        // remove existing values first
1100
        String delete = "delete from smReplicationPolicy " + 
1101
        "where guid = ? and policy = ?";
1102
        PreparedStatement stmt = dbConn.prepareStatement(delete);
1103
        //data values
1104
        stmt.setString(1, guid);
1105
        stmt.setString(2, policy);
1106
        //execute
1107
        int deletedCount = stmt.executeUpdate();
1108
        stmt.close();
1109
        
1110
        for (String memberNode: memberNodes) {
1111
            // Execute the insert statement
1112
            String insert = "insert into smReplicationPolicy " + 
1113
                "(guid, policy, member_node) " +
1114
                "values (?, ?, ?)";
1115
            PreparedStatement insertStatement = dbConn.prepareStatement(insert);
1116
            
1117
            //data values
1118
            insertStatement.setString(1, guid);
1119
            insertStatement.setString(2, policy);
1120
            insertStatement.setString(3, memberNode);
1121
            
1122
            logMetacat.debug("smReplicationPolicy sql: " + insertStatement.toString());
1123

    
1124
            //execute
1125
            int rows = insertStatement.executeUpdate();
1126
            insertStatement.close();
1127
        }
1128
        
1129
    }
1130
    
1131
    private void insertReplicationStatus(String guid, List<Replica> replicas, DBConnection dbConn) throws SQLException {
1132
       
1133
        // remove existing values first
1134
        String delete = "delete from smReplicationStatus " + 
1135
        "where guid = ?";
1136
        PreparedStatement stmt = dbConn.prepareStatement(delete);
1137
        //data values
1138
        stmt.setString(1, guid);
1139
        //execute
1140
        int deletedCount = stmt.executeUpdate();
1141
        stmt.close();
1142
        
1143
        if (replicas != null) {
1144
            for (Replica replica: replicas) {
1145
	            // Execute the insert statement
1146
	            String insert = "insert into smReplicationStatus " + 
1147
	                "(guid, member_node, status, date_verified) " +
1148
	                "values (?, ?, ?, ?)";
1149
	            PreparedStatement insertStatement = dbConn.prepareStatement(insert);
1150
	            
1151
	            //data values
1152
	            String memberNode = replica.getReplicaMemberNode().getValue();
1153
	            String status = replica.getReplicationStatus().toString();
1154
	            java.sql.Timestamp sqlDate = new java.sql.Timestamp(replica.getReplicaVerified().getTime());
1155
	            insertStatement.setString(1, guid);
1156
	            insertStatement.setString(2, memberNode);
1157
	            insertStatement.setString(3, status);
1158
	            insertStatement.setTimestamp(4, sqlDate);
1159

    
1160
	            logMetacat.debug("smReplicationStatus sql: " + insertStatement.toString());
1161
	            
1162
	            //execute
1163
	            int rows = insertStatement.executeUpdate();
1164
	            insertStatement.close();
1165
            }
1166
        }
1167
       
1168
    }
1169
    
1170
    /**
1171
     * Insert the system metadata fields into the db
1172
     * @param sm
1173
     * @throws McdbDocNotFoundException 
1174
     * @throws SQLException 
1175
     * @throws InvalidSystemMetadata 
1176
     * @throws AccessException 
1177
     */
1178
    public void updateSystemMetadata(SystemMetadata sm, DBConnection dbConn) 
1179
      throws McdbDocNotFoundException, SQLException, InvalidSystemMetadata, AccessException {
1180
    	
1181
      Boolean replicationAllowed = false;
1182
		  Integer numberReplicas = -1;
1183
    	ReplicationPolicy replicationPolicy = sm.getReplicationPolicy();
1184
    	if (replicationPolicy != null) {
1185
    		replicationAllowed = replicationPolicy.getReplicationAllowed();
1186
    		numberReplicas = replicationPolicy.getNumberReplicas();
1187
    		replicationAllowed = replicationAllowed == null ? false: replicationAllowed;
1188
    		numberReplicas = numberReplicas == null ? -1: numberReplicas;
1189
    	}
1190
    	
1191
    	// the main systemMetadata fields
1192
		  updateSystemMetadataFields(
1193
				sm.getDateUploaded() == null ? null: sm.getDateUploaded().getTime(),
1194
				sm.getRightsHolder() == null ? null: sm.getRightsHolder().getValue(), 
1195
				sm.getChecksum() == null ? null: sm.getChecksum().getValue(), 
1196
				sm.getChecksum() == null ? null: sm.getChecksum().getAlgorithm(), 
1197
				sm.getOriginMemberNode() == null ? null: sm.getOriginMemberNode().getValue(),
1198
				sm.getAuthoritativeMemberNode() == null ? null: sm.getAuthoritativeMemberNode().getValue(), 
1199
				sm.getDateSysMetadataModified() == null ? null: sm.getDateSysMetadataModified().getTime(),
1200
				sm.getSubmitter() == null ? null: sm.getSubmitter().getValue(), 
1201
		    sm.getIdentifier().getValue(),
1202
		    sm.getFormatId() == null ? null: sm.getFormatId().getValue(),
1203
		    sm.getSize(),
1204
		    sm.getArchived() == null ? false: sm.getArchived(),
1205
		    replicationAllowed, 
1206
		    numberReplicas,
1207
		    sm.getObsoletes() == null ? null:sm.getObsoletes().getValue(),
1208
		    sm.getObsoletedBy() == null ? null: sm.getObsoletedBy().getValue(),
1209
		    sm.getSerialVersion(),
1210
		    dbConn
1211
        );
1212
        
1213
        String guid = sm.getIdentifier().getValue();
1214
        
1215
        // save replication policies
1216
        if (replicationPolicy != null) {
1217
		    List<String> nodes = null;
1218
		    String policy = null;
1219
		    
1220
		    // check for null 
1221
		    if (replicationPolicy.getBlockedMemberNodeList() != null) {
1222
			    nodes = new ArrayList<String>();
1223
			    policy = "blocked";
1224
			    for (NodeReference node: replicationPolicy.getBlockedMemberNodeList()) {
1225
			    	nodes.add(node.getValue());
1226
			    }
1227
			    this.insertReplicationPolicy(guid, policy, nodes, dbConn);
1228
		    }
1229
		    
1230
		    if (replicationPolicy.getPreferredMemberNodeList() != null) {
1231
			    nodes = new ArrayList<String>();
1232
			    policy = "preferred";
1233
			    for (NodeReference node: replicationPolicy.getPreferredMemberNodeList()) {
1234
			    	nodes.add(node.getValue());
1235
			    }
1236
		        this.insertReplicationPolicy(guid, policy, nodes, dbConn);
1237
		    }
1238
        }
1239
        
1240
        // save replica information
1241
        this.insertReplicationStatus(guid, sm.getReplicaList(), dbConn);
1242
        
1243
        // save access policy
1244
        AccessPolicy accessPolicy = sm.getAccessPolicy();
1245
        if (accessPolicy != null) {
1246
			this.insertAccessPolicy(guid, accessPolicy);
1247
        }
1248
    }
1249
    
1250
    /**
1251
     * Creates Metacat access rules and inserts them
1252
     * @param accessPolicy
1253
     * @throws McdbDocNotFoundException
1254
     * @throws AccessException
1255
     */
1256
    private void insertAccessPolicy(String guid, AccessPolicy accessPolicy) throws McdbDocNotFoundException, AccessException {
1257
    	
1258
    	// check for the existing permOrder so that we remain compatible with it (DataONE does not care)
1259
        XMLAccessAccess accessController  = new XMLAccessAccess();
1260
		String existingPermOrder = AccessControlInterface.ALLOWFIRST;
1261
        Vector<XMLAccessDAO> existingAccess = accessController.getXMLAccessForDoc(guid);
1262
        if (existingAccess != null && existingAccess.size() > 0) {
1263
        	existingPermOrder = existingAccess.get(0).getPermOrder();
1264
        }
1265
        
1266
    	List<XMLAccessDAO> accessDAOs = new ArrayList<XMLAccessDAO>();
1267
        for (AccessRule accessRule: accessPolicy.getAllowList()) {
1268
        	List<Subject> subjects = accessRule.getSubjectList();
1269
        	List<Permission> permissions = accessRule.getPermissionList();
1270
        	for (Subject subject: subjects) {
1271
    			XMLAccessDAO accessDAO = new XMLAccessDAO();
1272
        		accessDAO.setPrincipalName(subject.getValue());
1273
    			accessDAO.setGuid(guid);
1274
    			accessDAO.setPermType(AccessControlInterface.ALLOW);
1275
				accessDAO.setPermOrder(existingPermOrder);
1276
    			if (permissions != null) {
1277
	    			for (Permission permission: permissions) {
1278
	    				Long metacatPermission = new Long(convertPermission(permission));
1279
	        			accessDAO.addPermission(metacatPermission);
1280
	    			}
1281
    			}
1282
    			accessDAOs.add(accessDAO);
1283
        	}
1284
        }
1285
        
1286
        
1287
        // remove all existing allow records
1288
        accessController.deleteXMLAccessForDoc(guid, AccessControlInterface.ALLOW);
1289
        // add the ones we can for this guid
1290
        accessController.insertAccess(guid, accessDAOs);
1291
        
1292
        
1293
    }
1294
    
1295
    /**
1296
     * Lookup access policy from Metacat
1297
     * @param guid
1298
     * @return
1299
     * @throws McdbDocNotFoundException
1300
     * @throws AccessException
1301
     */
1302
    public AccessPolicy getAccessPolicy(String guid) throws McdbDocNotFoundException, AccessException {
1303
        AccessPolicy accessPolicy = new AccessPolicy();
1304

    
1305
    	// use GUID to look up the access
1306
        XMLAccessAccess accessController  = new XMLAccessAccess();
1307
        List<XMLAccessDAO> accessDAOs = accessController.getXMLAccessForDoc(guid);
1308
        
1309
        for (XMLAccessDAO accessDAO: accessDAOs) {
1310
        	// only add allow rule
1311
        	if (accessDAO.getPermType().equals(AccessControlInterface.ALLOW)) {
1312
	        	AccessRule accessRule = new AccessRule();    	
1313
	        	List <Permission> permissions = convertPermission(accessDAO.getPermission().intValue());
1314
	        	// cannot include if we have no permissions
1315
	        	if (permissions == null || permissions.isEmpty()) {
1316
	        		logMetacat.warn("skipping empty access rule permissions for " + guid);
1317
	        		continue;
1318
	        	}
1319
	        	accessRule.setPermissionList(permissions);
1320
	        	Subject subject = new Subject();
1321
	        	subject.setValue(accessDAO.getPrincipalName());
1322
	        	accessRule.addSubject(subject);
1323
	            accessPolicy.addAllow(accessRule);
1324
        	}
1325
        }
1326
        return accessPolicy;
1327
    }
1328
    
1329
    public int convertPermission(Permission permission) {
1330
    	if (permission.equals(Permission.READ)) {
1331
    		return AccessControlInterface.READ;
1332
    	}
1333
    	if (permission.equals(Permission.WRITE)) {
1334
    		return AccessControlInterface.WRITE;
1335
    	}
1336
    	if (permission.equals(Permission.CHANGE_PERMISSION)) {
1337
    		return AccessControlInterface.CHMOD;
1338
    	}
1339
		return -1;
1340
    }
1341
    
1342
    public List<Permission> convertPermission(int permission) {
1343
    	
1344
    	List<Permission> permissions = new ArrayList<Permission>();
1345
    	if (permission == AccessControlInterface.ALL) {
1346
    		permissions.add(Permission.READ);
1347
    		permissions.add(Permission.WRITE);
1348
    		permissions.add(Permission.CHANGE_PERMISSION);
1349
    		return permissions;
1350
    	}
1351
    	
1352
    	if ((permission & AccessControlInterface.CHMOD) == AccessControlInterface.CHMOD) {
1353
    		permissions.add(Permission.CHANGE_PERMISSION);
1354
    	}
1355
    	if ((permission & AccessControlInterface.READ) == AccessControlInterface.READ) {
1356
    		permissions.add(Permission.READ);
1357
    	}
1358
    	if ((permission & AccessControlInterface.WRITE) == AccessControlInterface.WRITE) {
1359
    		permissions.add(Permission.WRITE);
1360
    	}
1361
    	
1362
		return permissions;
1363
    }
1364
    
1365
    /**
1366
     * Lookup a localId given the GUID. If
1367
     * the identifier is not found, throw an exception.
1368
     * 
1369
     * @param guid the global identifier to look up
1370
     * @return String containing the corresponding LocalId
1371
     * @throws McdbDocNotFoundException if the identifier is not found
1372
     */
1373
    public String getLocalId(String guid) throws McdbDocNotFoundException {
1374
      
1375
      String db_guid = "";
1376
      String docid = "";
1377
      int rev = 0;
1378
      
1379
      String query = "select guid, docid, rev from " + TYPE_IDENTIFIER + " where guid = ?";
1380
      
1381
      DBConnection dbConn = null;
1382
      int serialNumber = -1;
1383
      try {
1384
          // Get a database connection from the pool
1385
          dbConn = DBConnectionPool.getDBConnection("Identifier.getLocalId");
1386
          serialNumber = dbConn.getCheckOutSerialNumber();
1387
          
1388
          // Execute the insert statement
1389
          PreparedStatement stmt = dbConn.prepareStatement(query);
1390
          stmt.setString(1, guid);
1391
          ResultSet rs = stmt.executeQuery();
1392
          if (rs.next()) {
1393
              db_guid = rs.getString(1);
1394
              docid = rs.getString(2);
1395
              rev = rs.getInt(3);
1396
              assert(db_guid.equals(guid));
1397
          } else {
1398
              throw new McdbDocNotFoundException("Document not found:" + guid);
1399
          }
1400
          stmt.close();
1401
      } catch (SQLException e) {
1402
          logMetacat.error("Error while looking up the local identifier: " 
1403
                  + e.getMessage());
1404
      } finally {
1405
          // Return database connection to the pool
1406
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1407
      }
1408
      return docid + "." + rev;
1409
    }
1410
    
1411
    /**
1412
     * query the systemmetadata table based on the given parameters
1413
     * @param startTime
1414
     * @param endTime
1415
     * @param objectFormat
1416
     * @param replicaStatus
1417
     * @param start
1418
     * @param count
1419
     * @return ObjectList
1420
     * @throws SQLException 
1421
     * @throws ServiceException 
1422
     * @throws PropertyNotFoundException 
1423
     */
1424
    public ObjectList querySystemMetadata(Date startTime, Date endTime,
1425
        ObjectFormatIdentifier objectFormatId, boolean replicaStatus,
1426
        int start, int count) 
1427
        throws SQLException, PropertyNotFoundException, ServiceException {
1428
        ObjectList ol = new ObjectList();
1429
        DBConnection dbConn = null;
1430
        int serialNumber = -1;
1431

    
1432
        try {
1433
            String fieldSql = "select guid, date_uploaded, rights_holder, checksum, "
1434
                    + "checksum_algorithm, origin_member_node, authoritive_member_node, "
1435
                    + "date_modified, submitter, object_format, size from systemmetadata";
1436
            
1437
            // handle special case quickly
1438
            String countSql = "select count(guid) from systemmetadata";
1439
            
1440
            // the clause
1441
            String whereClauseSql = "";
1442

    
1443
            boolean f1 = false;
1444
            boolean f2 = false;
1445
            boolean f3 = false;
1446

    
1447
            if (startTime != null) {
1448
                whereClauseSql += " where systemmetadata.date_modified >= ?";
1449
                f1 = true;
1450
            }
1451

    
1452
            if (endTime != null) {
1453
                if (!f1) {
1454
                    whereClauseSql += " where systemmetadata.date_modified < ?";
1455
                } else {
1456
                    whereClauseSql += " and systemmetadata.date_modified < ?";
1457
                }
1458
                f2 = true;
1459
            }
1460

    
1461
            if (objectFormatId != null) {
1462
                if (!f1 && !f2) {
1463
                    whereClauseSql += " where object_format = ?";
1464
                } else {
1465
                    whereClauseSql += " and object_format = ?";
1466
                }
1467
                f3 = true;
1468
            }
1469

    
1470
            if (!replicaStatus) {
1471
                String currentNodeId = PropertyService.getInstance().getProperty("dataone.nodeId");
1472
                if (!f1 && !f2 && !f3) {
1473
                    whereClauseSql += " where authoritive_member_node = '" +
1474
                        currentNodeId.trim() + "'";
1475
                } else {
1476
                    whereClauseSql += " and authoritive_member_node = '" +
1477
                        currentNodeId.trim() + "'";
1478
                }
1479
            }
1480
            
1481
            // connection
1482
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.querySystemMetadata");
1483
            serialNumber = dbConn.getCheckOutSerialNumber();
1484

    
1485
            // the field query
1486
            String orderBySql = " order by guid ";
1487
            String fieldQuery = fieldSql + whereClauseSql + orderBySql;
1488
            String finalQuery = DatabaseService.getInstance().getDBAdapter().getPagedQuery(fieldQuery, start, count);
1489
            PreparedStatement fieldStmt = dbConn.prepareStatement(finalQuery);
1490
            
1491
            // construct the count query and statment
1492
            String countQuery = countSql + whereClauseSql;
1493
            PreparedStatement countStmt = dbConn.prepareStatement(countQuery);
1494

    
1495
            if (f1 && f2 && f3) {
1496
                fieldStmt.setTimestamp(1, new Timestamp(startTime.getTime()));
1497
                fieldStmt.setTimestamp(2, new Timestamp(endTime.getTime()));
1498
                fieldStmt.setString(3, objectFormatId.getValue());
1499
                // count
1500
                countStmt.setTimestamp(1, new Timestamp(startTime.getTime()));
1501
                countStmt.setTimestamp(2, new Timestamp(endTime.getTime()));
1502
                countStmt.setString(3, objectFormatId.getValue());
1503
            } else if (f1 && f2 && !f3) {
1504
                fieldStmt.setTimestamp(1, new Timestamp(startTime.getTime()));
1505
                fieldStmt.setTimestamp(2, new Timestamp(endTime.getTime()));
1506
                // count
1507
                countStmt.setTimestamp(1, new Timestamp(startTime.getTime()));
1508
                countStmt.setTimestamp(2, new Timestamp(endTime.getTime()));
1509
            } else if (f1 && !f2 && f3) {
1510
                fieldStmt.setTimestamp(1, new Timestamp(startTime.getTime()));
1511
                fieldStmt.setString(2, objectFormatId.getValue());
1512
                // count
1513
                countStmt.setTimestamp(1, new Timestamp(startTime.getTime()));
1514
                countStmt.setString(2, objectFormatId.getValue());
1515
            } else if (f1 && !f2 && !f3) {
1516
                fieldStmt.setTimestamp(1, new Timestamp(startTime.getTime()));
1517
                // count
1518
                countStmt.setTimestamp(1, new Timestamp(startTime.getTime()));
1519
            } else if (!f1 && f2 && f3) {
1520
                fieldStmt.setTimestamp(1, new Timestamp(endTime.getTime()));
1521
                fieldStmt.setString(2, objectFormatId.getValue());
1522
                // count
1523
                countStmt.setTimestamp(1, new Timestamp(endTime.getTime()));
1524
                countStmt.setString(2, objectFormatId.getValue());
1525
            } else if (!f1 && !f2 && f3) {
1526
                fieldStmt.setString(1, objectFormatId.getValue());
1527
                // count
1528
                countStmt.setString(1, objectFormatId.getValue());
1529
            } else if (!f1 && f2 && !f3) {
1530
                fieldStmt.setTimestamp(1, new Timestamp(endTime.getTime()));
1531
                // count
1532
                countStmt.setTimestamp(1, new Timestamp(endTime.getTime()));
1533
            }
1534

    
1535
            logMetacat.debug("list objects fieldStmt: " + fieldStmt.toString());
1536
            
1537
            logMetacat.debug("list objects countStmt: " + countStmt.toString());
1538
            
1539
            // get the total object count no matter what
1540
            int total = 0;
1541
            ResultSet totalResult = countStmt.executeQuery();
1542
            if (totalResult.next()) {
1543
            	total = totalResult.getInt(1);
1544
            }
1545
            
1546
            logMetacat.debug("list objects total: " + total);
1547

    
1548
        	// set the totals
1549
        	ol.setStart(start);
1550
            ol.setCount(count);
1551
            ol.setTotal(total);
1552
            
1553
            // retrieve the actual records if requested
1554
            if (count != 0) {
1555
            	
1556
                ResultSet rs = fieldStmt.executeQuery();
1557
	            while (rs.next()) {                
1558
	                
1559
	                String guid = rs.getString(1);
1560
	                logMetacat.debug("query found object with guid " + guid);
1561
	                // Timestamp dateUploaded = rs.getTimestamp(2);
1562
	                // String rightsHolder = rs.getString(3);
1563
	                String checksum = rs.getString(4);
1564
	                String checksumAlgorithm = rs.getString(5);
1565
	                // String originMemberNode = rs.getString(6);
1566
	                // String authoritiveMemberNode = rs.getString(7);
1567
	                Timestamp dateModified = rs.getTimestamp(8);
1568
	                // String submitter = rs.getString(9);
1569
	                String fmtidStr = rs.getString(10);
1570
	                String sz = rs.getString(11);
1571
	                BigInteger size = new BigInteger("0");
1572
	
1573
	                if (sz != null && !sz.trim().equals("")) {
1574
	                    size = new BigInteger(rs.getString(11));
1575
	                }
1576
	
1577
	                ObjectInfo oi = new ObjectInfo();
1578
	
1579
	                Identifier id = new Identifier();
1580
	                id.setValue(guid);
1581
	                oi.setIdentifier(id);
1582
	
1583
	                if (dateModified != null) {
1584
	                    oi.setDateSysMetadataModified(dateModified);
1585
	                }
1586
	
1587
	                Checksum cs = new Checksum();
1588
	                cs.setValue(checksum);
1589
	                try {
1590
	                    // cs.setAlgorithm(ChecksumAlgorithm.valueOf(checksumAlgorithm));
1591
	                    cs.setAlgorithm(checksumAlgorithm);
1592
	                } catch (Exception e) {
1593
	                    logMetacat.error("could not parse checksum algorithm", e);
1594
	                    continue;
1595
	                }
1596
	                oi.setChecksum(cs);
1597
	
1598
	                // set the format type
1599
	                ObjectFormatIdentifier fmtid = new ObjectFormatIdentifier();
1600
	                fmtid.setValue(fmtidStr);
1601
	                oi.setFormatId(fmtid);
1602
	
1603
	                oi.setSize(size);
1604
	
1605
	                ol.addObjectInfo(oi);                    
1606

    
1607
	            }
1608
	            
1609
	            logMetacat.debug("list objects count: " + ol.sizeObjectInfoList());
1610

    
1611
	            // set the actual count retrieved
1612
	            ol.setCount(ol.sizeObjectInfoList());
1613
	
1614
	        }
1615
            
1616
        }
1617

    
1618
        finally {
1619
            // Return database connection to the pool
1620
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1621
        }
1622

    
1623
        return ol;
1624
    }
1625
    
1626
    /**
1627
     * create a mapping in the identifier table
1628
     * @param guid
1629
     * @param localId
1630
     */
1631
    public void createMapping(String guid, String localId)
1632
    {        
1633
        
1634
        int serialNumber = -1;
1635
        DBConnection dbConn = null;
1636
        try {
1637

    
1638
            // Parse the localId into scope and rev parts
1639
            AccessionNumber acc = new AccessionNumber(localId, "NOACTION");
1640
            String docid = acc.getDocid();
1641
            int rev = 1;
1642
            if (acc.getRev() != null) {
1643
              rev = (new Integer(acc.getRev()).intValue());
1644
            }
1645

    
1646
            // Get a database connection from the pool
1647
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.createMapping");
1648
            serialNumber = dbConn.getCheckOutSerialNumber();
1649

    
1650
            // Execute the insert statement
1651
            String query = "insert into " + TYPE_IDENTIFIER + " (guid, docid, rev) values (?, ?, ?)";
1652
            PreparedStatement stmt = dbConn.prepareStatement(query);
1653
            stmt.setString(1, guid);
1654
            stmt.setString(2, docid);
1655
            stmt.setInt(3, rev);
1656
            logMetacat.debug("mapping query: " + stmt.toString());
1657
            int rows = stmt.executeUpdate();
1658

    
1659
            stmt.close();
1660
        } catch (SQLException e) {
1661
            e.printStackTrace();
1662
            logMetacat.error("createGenericMapping: SQL error while creating a mapping to the " + TYPE_IDENTIFIER + " identifier: " 
1663
                    + e.getMessage());
1664
        } catch (NumberFormatException e) {
1665
            e.printStackTrace();
1666
            logMetacat.error("createGenericMapping: NumberFormat error while creating a mapping to the " + TYPE_IDENTIFIER + " identifier: " 
1667
                    + e.getMessage());
1668
        } catch (AccessionNumberException e) {
1669
            e.printStackTrace();
1670
            logMetacat.error("createGenericMapping: AccessionNumber error while creating a mapping to the " + TYPE_IDENTIFIER + " identifier: " 
1671
                    + e.getMessage());
1672
        } finally {
1673
            // Return database connection to the pool
1674
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1675
        }
1676
    }
1677
    
1678
    /**
1679
     * remove a mapping in the identifier table
1680
     * @param guid
1681
     * @param localId
1682
     */
1683
    public void removeMapping(String guid, String localId)
1684
    {        
1685
        
1686
        int serialNumber = -1;
1687
        DBConnection dbConn = null;
1688
        try {
1689

    
1690
            // Parse the localId into scope and rev parts
1691
            AccessionNumber acc = new AccessionNumber(localId, "NOACTION");
1692
            String docid = acc.getDocid();
1693
            int rev = 1;
1694
            if (acc.getRev() != null) {
1695
              rev = (new Integer(acc.getRev()).intValue());
1696
            }
1697

    
1698
            // Get a database connection from the pool
1699
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.removeMapping");
1700
            serialNumber = dbConn.getCheckOutSerialNumber();
1701

    
1702
            // Execute the insert statement
1703
            String query = "DELETE FROM " + TYPE_IDENTIFIER + " WHERE guid = ? AND docid = ? AND rev = ?";
1704
            PreparedStatement stmt = dbConn.prepareStatement(query);
1705
            stmt.setString(1, guid);
1706
            stmt.setString(2, docid);
1707
            stmt.setInt(3, rev);
1708
            logMetacat.debug("remove mapping query: " + stmt.toString());
1709
            int rows = stmt.executeUpdate();
1710

    
1711
            stmt.close();
1712
        } catch (SQLException e) {
1713
            e.printStackTrace();
1714
            logMetacat.error("removeMapping: SQL error while removing a mapping to the " + TYPE_IDENTIFIER + " identifier: " 
1715
                    + e.getMessage());
1716
        } catch (NumberFormatException e) {
1717
            e.printStackTrace();
1718
            logMetacat.error("removeMapping: NumberFormat error while removing a mapping to the " + TYPE_IDENTIFIER + " identifier: " 
1719
                    + e.getMessage());
1720
        } catch (AccessionNumberException e) {
1721
            e.printStackTrace();
1722
            logMetacat.error("removeMapping: AccessionNumber error while removing a mapping to the " + TYPE_IDENTIFIER + " identifier: " 
1723
                    + e.getMessage());
1724
        } finally {
1725
            // Return database connection to the pool
1726
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1727
        }
1728
    }
1729
    
1730
    /**
1731
     * create the systemmetadata record
1732
     * @param guid
1733
     * @param dbConn 
1734
     * @throws SQLException 
1735
     */
1736
    private void insertSystemMetadata(String guid, DBConnection dbConn) throws SQLException
1737
    {        
1738

    
1739
        // Execute the insert statement
1740
        String query = "insert into " + TYPE_SYSTEM_METADATA + " (guid) values (?)";
1741
        PreparedStatement stmt = dbConn.prepareStatement(query);
1742
        stmt.setString(1, guid);
1743
        logMetacat.debug("system metadata query: " + stmt.toString());
1744
        int rows = stmt.executeUpdate();
1745

    
1746
        stmt.close();
1747
        
1748
    }
1749
    
1750
    public void deleteSystemMetadata(String guid)
1751
    {        
1752
        
1753
        int serialNumber = -1;
1754
        DBConnection dbConn = null;
1755
        String query = null;
1756
        PreparedStatement stmt = null;
1757
        int rows = 0;
1758
        try {
1759

    
1760
            // Get a database connection from the pool
1761
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.deleteSystemMetadata");
1762
            serialNumber = dbConn.getCheckOutSerialNumber();
1763

    
1764
            // remove main system metadata entry
1765
            query = "delete from " + TYPE_SYSTEM_METADATA + " where guid = ? ";
1766
            stmt = dbConn.prepareStatement(query);
1767
            stmt.setString(1, guid);
1768
            logMetacat.debug("delete system metadata: " + stmt.toString());
1769
            rows = stmt.executeUpdate();
1770
            stmt.close();
1771
            
1772
            // remove the smReplicationPolicy
1773
            query = "delete from smReplicationPolicy " + 
1774
            "where guid = ?";
1775
            stmt = dbConn.prepareStatement(query);
1776
            stmt.setString(1, guid);
1777
            logMetacat.debug("delete smReplicationPolicy: " + stmt.toString());
1778
            rows = stmt.executeUpdate();
1779
            stmt.close();
1780
            
1781
            // remove the smReplicationStatus
1782
            query = "delete from smReplicationStatus " + 
1783
            "where guid = ?";
1784
            stmt = dbConn.prepareStatement(query);
1785
            stmt.setString(1, guid);
1786
            logMetacat.debug("delete smReplicationStatus: " + stmt.toString());
1787
            rows = stmt.executeUpdate();
1788
            stmt.close();
1789
            
1790
            // TODO: remove the access?
1791
            // Metacat keeps "deleted" documents so we should not remove access rules.
1792
            
1793
        } catch (Exception e) {
1794
            e.printStackTrace();
1795
            logMetacat.error("Error while deleting " + TYPE_SYSTEM_METADATA + " record: " + guid, e );
1796
            try {
1797
				dbConn.rollback();
1798
			} catch (SQLException sqle) {
1799
	            logMetacat.error("Error while rolling back delete for record: " + guid, sqle );
1800
			}
1801
        } finally {
1802
            // Return database connection to the pool
1803
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1804
        }
1805
    }
1806
    
1807
    public void updateAuthoritativeMemberNodeId(String existingMemberNodeId, String newMemberNodeId)
1808
    {
1809
        DBConnection dbConn = null;
1810
        int serialNumber = -1;
1811
        
1812
        try {
1813
            // Get a database connection from the pool
1814
            dbConn = DBConnectionPool.getDBConnection("IdentifierManager.updateAuthoritativeMemberNodeId");
1815
            serialNumber = dbConn.getCheckOutSerialNumber();
1816

    
1817
            // Execute the insert statement
1818
            String query = "update " + TYPE_SYSTEM_METADATA + 
1819
                " set authoritive_member_node = ? " +
1820
                " where authoritive_member_node = ?";
1821
            PreparedStatement stmt = dbConn.prepareStatement(query);
1822
            
1823
            //data values
1824
            stmt.setString(1, newMemberNodeId);
1825
            stmt.setString(2, existingMemberNodeId);
1826

    
1827
            logMetacat.debug("stmt: " + stmt.toString());
1828
            //execute
1829
            int rows = stmt.executeUpdate();
1830

    
1831
            stmt.close();
1832
        } catch (SQLException e) {
1833
            e.printStackTrace();
1834
            logMetacat.error("updateSystemMetadataFields: SQL error while updating system metadata: " 
1835
                    + e.getMessage());
1836
        } catch (NumberFormatException e) {
1837
            e.printStackTrace();
1838
            logMetacat.error("updateSystemMetadataFields: NumberFormat error while updating system metadata: " 
1839
                    + e.getMessage());
1840
        } finally {
1841
            // Return database connection to the pool
1842
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1843
        }
1844
    }
1845
}
1846

    
(36-36/63)