Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements utility methods like:
4
 *             1/ Reding all doctypes from db connection
5
 *             2/ Reading DTD or Schema file from Metacat catalog system
6
 *             3/ Reading Lore type Data Guide from db connection
7
 *  Copyright: 2000 Regents of the University of California and the
8
 *             National Center for Ecological Analysis and Synthesis
9
 *    Authors: Jivka Bojilova
10
 * 
11
 *   '$Author: daigle $'
12
 *     '$Date: 2009-12-18 13:37:26 -0800 (Fri, 18 Dec 2009) $'
13
 * '$Revision: 5167 $'
14
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 2 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program; if not, write to the Free Software
27
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28
 */
29

    
30
package edu.ucsb.nceas.metacat;
31

    
32
import java.sql.SQLException;
33
import java.sql.PreparedStatement;
34
import java.sql.ResultSet;
35

    
36
import java.io.BufferedInputStream;
37
import java.io.InputStream;
38
import java.io.IOException;
39
import java.net.URL;
40
import java.net.MalformedURLException;
41

    
42
import java.util.Enumeration;
43
import java.util.Vector;
44

    
45
import org.apache.log4j.Logger;
46

    
47
import edu.ucsb.nceas.metacat.database.DBConnection;
48
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
49
import edu.ucsb.nceas.metacat.properties.PropertyService;
50
import edu.ucsb.nceas.metacat.util.DocumentUtil;
51
import edu.ucsb.nceas.metacat.util.SystemUtil;
52
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
53

    
54
/**
55
 * A suite of utility classes for querying DB
56
 */
57
public class DBUtil {
58

    
59
  //private Connection	conn = null;
60
  private static Logger logMetacat = Logger.getLogger(DBUtil.class);
61

    
62
  /**
63
   * main routine used for testing.
64
   * <p>
65
   * Usage: java DBUtil <-dt|-dg>
66
   *
67
   * @param -dt for selecting all doctypes
68
   *        -dg for selecting DataGuide
69
   */
70
  static public void main(String[] args) {
71
     
72
     if (args.length < 1)
73
     {
74
        System.err.println("Wrong number of arguments!!!");
75
        System.err.println("USAGE: java DBUtil <-dt | -ds [doctype] | -dl user>");
76
        return;
77
     } else {
78
        try {
79
                    
80
          // Open a connection to the database
81
          //Connection dbconn = util.openDBConnection();
82

    
83
          DBUtil dbutil = new DBUtil();
84
          
85
          if ( args[0].equals("-dt") ) {
86
            String doctypes = dbutil.readDoctypes();
87
            System.out.println(doctypes);
88
          } else if ( args[0].equals("-ds") ) {
89
            String doctype = null;
90
            if ( args.length == 2 ) { doctype = args[1]; }
91
            String dtdschema = dbutil.readDTDSchema(doctype);
92
            System.out.println(dtdschema);
93
          } else if ( args[0].equals("-dl") ) {
94
            String scope = "";
95
            if ( args.length == 2 ) { scope = args[1]; }
96
            String docid = dbutil.getMaxDocid(scope);
97
            System.out.println(docid);
98
          } else {
99
            System.err.println(
100
            "USAGE: java DBUtil <-dt | -ds [doctype] | -dg [doctype]>");
101
          }  
102

    
103
        } catch (Exception e) {
104
          //System.err.println("error in DBUtil.main");
105
          //System.err.println(e.getMessage());
106
          e.printStackTrace(System.err);
107
        }
108
     }
109
  }
110
  
111
  /**
112
   * Construct an instance of the utility class
113
   */
114
  public DBUtil() {
115
    //this.conn = conn;
116
  }
117

    
118
  /**
119
   * read all doctypes from db connection in XML format
120
   * select all Public Id from xml_catalog table
121
   */
122
  public String readDoctypes()
123
        throws SQLException  {
124

    
125
    Vector<String> doctypeList = new Vector<String>();
126
    DBConnection dbConn = null;
127
    int serialNumber = -1;
128
    PreparedStatement pstmt = null;
129
    try {
130

    
131
      dbConn=DBConnectionPool.
132
                  getDBConnection("DBUtil.readDoctypes");
133
      serialNumber=dbConn.getCheckOutSerialNumber();
134
      pstmt =
135
        dbConn.prepareStatement("SELECT public_id FROM xml_catalog " +
136
                              "WHERE entry_type = 'DTD'");
137

    
138
      pstmt.execute();
139
      ResultSet rs = pstmt.getResultSet();
140
      boolean tableHasRows = rs.next();
141
      while (tableHasRows) {
142
           doctypeList.addElement(rs.getString(1));
143
           tableHasRows = rs.next();
144
      }
145
      
146
      pstmt.close();
147

    
148
    } catch (SQLException e) {
149
      throw new SQLException("DBUtil.readDoctypes - SQL error: " + e.getMessage());
150
    }
151
    finally
152
    {
153
      try
154
      {
155
        pstmt.close();
156
      }//try
157
      finally
158
      {
159
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
160
      }//finally
161
    }//finally
162
       
163

    
164
    return formatToXML(doctypeList, "doctype");
165
  }
166

    
167
  /**
168
   * read DTD or Schema file from Metacat's XML catalog system
169
   */
170
  public String readDTDSchema(String doctype)
171
        throws SQLException, MalformedURLException, IOException, PropertyNotFoundException
172
  {
173
    String systemID = null;
174
    PreparedStatement pstmt = null;
175
    StringBuffer cbuff = new StringBuffer();
176
    DBConnection dbConn = null;
177
    int serialNumber = -1;
178
    // get doctype's System ID from db catalog
179
    try {
180
    
181
      dbConn=DBConnectionPool.
182
                  getDBConnection("DBUtil.readDTDSchema");
183
      serialNumber=dbConn.getCheckOutSerialNumber();
184
      pstmt = dbConn.prepareStatement("SELECT system_id " + 
185
                                    "FROM xml_catalog " +
186
                                    "WHERE entry_type in ('DTD','Schema') " +
187
                                    "AND public_id LIKE ?");
188
      pstmt.setString(1, doctype);
189
      pstmt.execute();
190
      ResultSet rs = pstmt.getResultSet();
191
      boolean hasRow = rs.next();
192
      if (hasRow) {
193
        systemID = rs.getString(1);
194
        // system id may not have server url on front.  Add it if not.
195
        if (!systemID.startsWith("http://")) {
196
        	systemID = SystemUtil.getContextURL() + systemID;
197
        }
198
      } else {
199
        throw new SQLException("DBUtil.readDTDSchema - Non-registered doctype: " + doctype);
200
      }
201
      pstmt.close();
202

    
203
    } catch (SQLException e) {
204
      throw new SQLException("DBUtil.readDTDSchema - " + e.getMessage());
205
    }
206
    finally
207
    {
208
      try
209
      {
210
        pstmt.close();
211
      }//try
212
      finally
213
      {
214
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
215
      }//finally
216
    }//finally
217

    
218
    // read from URL stream as specified by the System ID.
219
    try {
220
      // open a connection to this URL and return an InputStream
221
      // for reading from that connection
222
      InputStream istream = new URL(systemID).openStream();
223
      // create a buffering character-input stream
224
      // that uses a default-sized input buffer
225
      BufferedInputStream in = new BufferedInputStream(istream);
226

    
227
      // read the input and write into the string buffer
228
	    int inputByte;
229
	    while ( (inputByte = in.read()) != -1 ) {
230
        cbuff.append((char)inputByte);
231
	    }
232

    
233
      // the input stream must be closed
234
	    in.close();
235
	    
236
    } catch (MalformedURLException e) {
237
    	throw new MalformedURLException("DBUtil.readDTDSchema - Malformed URL Error: " + e.getMessage());
238
    } catch (IOException e) {
239
    	throw new IOException("DBUtil.readDTDSchema - I/O error: " + e.getMessage());
240
    } catch (SecurityException e) {
241
    	throw new IOException("DBUtil.readDTDSchema - Security error: " + e.getMessage());
242
    }
243
    
244
   return cbuff.toString();
245
  }
246

    
247
//  /**
248
//   * format the DataGuide ResultSet to XML
249
//   */
250
//  private String formatToXML(Vector resultset) {
251
//  
252
//    String currPath = null;
253
//    String currElement = null;
254
//    String prevElement = null;
255
//    StringBuffer result = new StringBuffer();
256
//    Enumeration<String> rs = resultset.elements(); 
257
//    Stack st = new Stack();
258
//    int i = 0;
259
//
260
//    result.append("<?xml version=\"1.0\"?>\n");
261
//    result.append("<resultset>\n"); 
262
//    
263
//    while (rs.hasMoreElements()) {
264
//        currPath = (String)rs.nextElement();
265
//        while ( !In(prevElement, currPath) ) {
266
//            currElement = (String)st.pop();
267
//            result.append(pad(" ",i--) + "</" + currElement + ">\n");
268
//            if ( st.empty() ) 
269
//                prevElement = null;
270
//            else    
271
//                prevElement = (String)st.peek();
272
//        }    
273
//        currElement = getElementFromPath(currPath);
274
//        st.push(currElement);
275
//        result.append(pad(" ",++i) + "<" + currElement + ">\n");
276
//        prevElement = currElement;
277
//    }
278
//    while ( !st.empty() ) {
279
//        prevElement = (String)st.pop();
280
//        result.append(pad(" ",i--) + "</" + prevElement + ">\n");
281
//    }    
282
//    result.append("</resultset>\n"); 
283
//
284
//    return result.toString();
285
//  }
286

    
287
//  /**
288
//   * check if element is in path like /elem1/elem2/elemn3
289
//   */
290
//  private boolean In(String element, String path) {
291
//    
292
//    if ( element == null ) return true;
293
//    return ( path.indexOf(element) != -1 );
294
//  }
295
//
296
//  /**
297
//   * get last element from path like /elem1/elem2/elemn3
298
//   */
299
//  private String getElementFromPath(String path) {
300
//    
301
//    return ( path.substring(path.lastIndexOf("/")+1) );
302
//  }
303
//
304
//  /**
305
//   * repeates the str n-times
306
//   */
307
//  private String pad(String str, int n) {
308
//    
309
//    String result = "";
310
//    for ( int i = 0; i < n; i++ )
311
//        result = result.concat(str);
312
//        
313
//    return result;    
314
//  }
315

    
316
  /**
317
   * format the ResultSet to XML
318
   */
319
  private String formatToXML(Vector<String> resultset, String tag) {
320
  
321
    String val = null;
322
    StringBuffer result = new StringBuffer();
323
    Enumeration<String> rs = resultset.elements(); 
324

    
325
    result.append("<?xml version=\"1.0\"?>\n");
326
    result.append("<resultset>\n"); 
327
    while (rs.hasMoreElements()) {
328
        val = rs.nextElement();
329
        result.append("   <" + tag + ">" + val + "</" + tag + ">\n");
330
    }
331
    result.append("</resultset>\n"); 
332
    
333
    return result.toString();
334
  }
335

    
336
  /**
337
   * get the latest Accession Number from a particular scope
338
   */
339
  public String getMaxDocid(String scope)
340
        throws SQLException  {
341

    
342
    String accnum = null;
343
    String sep = ".";
344
    try {
345
    	PropertyService.getProperty("document.accNumSeparator");
346
    } catch (PropertyNotFoundException pnfe) {
347
    	logMetacat.error("DBUtil.getMaxDocid - could not get property " + 
348
    			"'accNumSeparator'.  setting to '.': " + pnfe.getMessage());  	
349
    }
350
    PreparedStatement pstmt = null;
351
    DBConnection dbConn = null;
352
    int serialNumber = -1;
353
    try {
354
        dbConn=DBConnectionPool.
355
                  getDBConnection("DBUtil.getMaxDocid");
356
        serialNumber=dbConn.getCheckOutSerialNumber();
357
        pstmt =
358
        dbConn.prepareStatement(
359
            "SELECT docid, max(rev) FROM " +
360
            "( " +
361
                "SELECT docid, rev " + 
362
                "FROM xml_documents " +
363
                "WHERE docid LIKE ? " +
364
            "UNION " + 
365
                "SELECT docid, rev " + 
366
                "FROM xml_revisions " +
367
                "WHERE docid LIKE ?" +
368
            ") subquery GROUP BY docid"
369
            );
370

    
371
      pstmt.setString(1,scope + sep + "%");
372
      pstmt.setString(2,scope + sep + "%");
373
      pstmt.execute();
374
      ResultSet rs = pstmt.getResultSet();
375
      
376
      long max = 0;
377
      String temp = null;
378
      
379
      while(rs.next()){
380
    	  temp = rs.getString(1);
381
    	  if(temp != null){
382
    		  temp = temp.substring(temp.indexOf(scope) + scope.length() + 1);
383
    		  try {
384
    			  long localid = Long.parseLong(temp);
385
    			  if (localid > max) {
386
    				  max = localid;
387
    				  accnum = rs.getString(1) + sep + rs.getString(2);
388
    			  }
389
    		  } catch (NumberFormatException nfe){
390
    			  // ignore the exception as it is possible that the  
391
    			  // localid in the identifier is not an integer 
392
    		  }
393
    	  }
394
      }
395
      
396
      pstmt.close();
397

    
398
    } catch (SQLException e) {
399
      throw new SQLException("DBUtil.getMaxDocid(). " + e.getMessage());
400
    }
401
    finally
402
    {
403
      try
404
      {
405
        pstmt.close();
406
      }//try
407
      finally
408
      {
409
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
410
      }//finally
411
    }//finally
412

    
413
    return accnum;
414
  }
415
  
416
  /**
417
   * return true if the given docid is registered in either the xml_documents
418
   * or xml_revisions table
419
   */
420
  public boolean idExists(String docid)
421
    throws SQLException
422
  {
423
    Vector<String> v = getAllDocids(null);
424
    for(int i=0; i<v.size(); i++)
425
    {
426
      String id = (String)v.elementAt(i);
427
      if(id.trim().equals(docid.trim()))
428
      {
429
        return true;
430
      }
431
    }
432
    return false;
433
  }
434
  
435
  /**
436
   * return all docids with a given doctype
437
   */
438
  public Vector<String> getAllDocidsByType(String doctype, boolean includeRevs) throws SQLException {
439
		Vector<String> resultVector = new Vector<String>();
440
		String sep = ".";
441
	    try {
442
	    	PropertyService.getProperty("document.accNumSeparator");
443
	    } catch (PropertyNotFoundException pnfe) {
444
	    	logMetacat.error("DBUtil.getAllDocidsByType - could not get property " + 
445
	    			"'accNumSeparator'.  setting to '.': " + pnfe.getMessage());  	
446
	    }
447
		PreparedStatement pstmt = null;
448
		DBConnection dbConn = null;
449
		int serialNumber = -1;
450
		try {
451
			dbConn = DBConnectionPool.getDBConnection("DBUtil.getAllDocidsByType");
452
			serialNumber = dbConn.getCheckOutSerialNumber();
453
			StringBuffer sb = new StringBuffer();
454

    
455
			sb.append("SELECT docid, rev FROM " + "( " + "SELECT docid, rev "
456
					+ "FROM xml_documents ");
457
			if (doctype != null) {
458
				sb.append("WHERE doctype LIKE ? ");
459
			}
460
			if (includeRevs) {
461
				sb.append("UNION " + "SELECT docid, rev " + "FROM xml_revisions ");
462
				if (doctype != null) {
463
					sb.append("WHERE doctype LIKE ?");
464
				}
465
			}
466
			sb.append(") subquery GROUP BY docid, rev");
467
			pstmt = dbConn.prepareStatement(sb.toString());
468

    
469
			if (doctype != null) {
470
				pstmt.setString(1, doctype);
471
				if (includeRevs) {
472
					pstmt.setString(2, doctype);
473
				}
474
			}
475
			pstmt.execute();
476
			ResultSet rs = pstmt.getResultSet();
477

    
478
			String id = null;
479
			String rev = null;
480
			while (rs.next()) {
481
				id = rs.getString(1);
482
				rev = rs.getString(2);
483
				if (id != null) {
484
					resultVector.addElement(id + sep + rev);
485
				}
486
			}
487

    
488
			pstmt.close();
489

    
490
		} catch (SQLException e) {
491
			throw new SQLException("DBUtil.getAllDocidsByType(). " + e.getMessage());
492
		} finally {
493
			try {
494
				pstmt.close();
495
			}// try
496
			finally {
497
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
498
			}// finally
499
		}// finally
500

    
501
		return resultVector;
502
	}
503
  
504
  /**
505
   * get the latest Accession Number from a particular scope
506
   */
507
  public Vector<String> getAllDocids(String scope)
508
        throws SQLException  {
509
    Vector<String> resultVector = new Vector<String>();
510
//    String accnum = null;
511
    String sep = ".";
512
    try {
513
    	PropertyService.getProperty("document.accNumSeparator");
514
    } catch (PropertyNotFoundException pnfe) {
515
    	logMetacat.error("could not get property 'accNumSeparator'.  setting to '.': " 
516
    			+ pnfe.getMessage());  	
517
    }
518
    PreparedStatement pstmt = null;
519
    DBConnection dbConn = null;
520
    int serialNumber = -1;
521
    try 
522
    {
523
      dbConn=DBConnectionPool.
524
                getDBConnection("DBUtil.getAllDocids");
525
      serialNumber=dbConn.getCheckOutSerialNumber();
526
      StringBuffer sb = new StringBuffer();
527
      
528
      sb.append("SELECT docid, rev FROM " +
529
                "( " +
530
                "SELECT docid, rev " + 
531
                "FROM xml_documents ");
532
      if(scope != null)
533
      {
534
        sb.append("WHERE docid LIKE ? ");
535
      }
536
      sb.append("UNION " + 
537
                "SELECT docid, rev " + 
538
                "FROM xml_revisions ");
539
      if(scope != null)
540
      {
541
        sb.append("WHERE docid LIKE ?");
542
      }
543
      sb.append(") subquery GROUP BY docid, rev");
544
      pstmt = dbConn.prepareStatement(sb.toString());
545

    
546
      if(scope != null)
547
      {
548
        pstmt.setString(1,scope + sep + "%");
549
        pstmt.setString(2,scope + sep + "%");
550
      }
551
      pstmt.execute();
552
      ResultSet rs = pstmt.getResultSet();
553
      
554
//      long max = 0;
555
      String id = null;
556
      String rev = null;
557
      while(rs.next()){
558
    	  id = rs.getString(1);
559
        rev = rs.getString(2);
560
    	  if(id != null){
561
    		  //temp = temp.substring(id.indexOf(scope) + scope.length() + 1);
562
          resultVector.addElement(id + sep + rev);
563
        }
564
      }
565
      
566
      pstmt.close();
567

    
568
    } catch (SQLException e) {
569
      throw new SQLException("DBUtil.getAllDocids - SQL error:  " + e.getMessage());
570
    }
571
    finally
572
    {
573
      try
574
      {
575
        pstmt.close();
576
      }//try
577
      finally
578
      {
579
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
580
      }//finally
581
    }//finally
582

    
583
    return resultVector;
584
  }
585
  
586
  /**
587
   * To a given docid, found a dataset docid which contains the the given docid
588
   * This will be done by searching xml_relation table
589
   * If couldn't find, null will be return
590
   * @param givenDocId, the docid which we want to find
591
   */
592
  public static String findDataSetDocIdForGivenDocument(String givenDocId)
593
  {
594
    // Prepared statement for sql
595
    PreparedStatement pStmt = null;
596
    // Result set
597
    ResultSet resultSet = null;
598
    // String to store the data set docid
599
    String dataSetDocId = null;
600
    // DBConnection will be checkout
601
    DBConnection dbConn = null;
602
    int serialNumber = -1;
603
    // String to store the sql command
604
    String sqlCommand = null;
605
    try
606
    {
607
      // Checkout DBConnection from pool
608
      dbConn=DBConnectionPool.
609
                  getDBConnection("DBUtil.findDataSetDocIdForGivenDocument");
610
      serialNumber=dbConn.getCheckOutSerialNumber();
611
      // SQL command to chose a docid from xm_relation table
612
      sqlCommand = "select docid from xml_relation where object like ? or " 
613
                                                    + "subject like ?";
614
      // Prepared statement
615
      pStmt = dbConn.prepareStatement(sqlCommand);
616
      // Bind variable
617
      pStmt.setString(1, givenDocId);
618
      pStmt.setString(2, givenDocId);
619
      // Execute prepared statement
620
      pStmt.execute();
621
      // Get result set
622
      resultSet = pStmt.getResultSet();
623
      
624
      // There has record
625
      if (resultSet.next())
626
      {
627
        // Put the docid into dataSetDocid
628
        dataSetDocId = resultSet.getString(1);
629
        return dataSetDocId;
630
      }//if
631
      else
632
      {
633
        // No record in xml_relation table for given doicd, null returned
634
        return dataSetDocId;
635
      }//else
636
    
637
    }//try
638
    catch ( SQLException e)
639
    {
640
      // Print out exception
641
      logMetacat.error("DBUtil.findDataSetDocIdForGivenDocument - " +
642
    		  "SQL error: " + e.getMessage());
643
      // return null
644
      return dataSetDocId;
645
     
646
    }//catch
647
    finally
648
    {
649
      try
650
      {
651
        // Close result set
652
        resultSet.close();
653
        // Close preparedStatement
654
        pStmt.close();
655
      }//try
656
      catch ( SQLException e)
657
      {
658
        // Print out exception
659
    	  logMetacat.error("DBUtil.findDataSetDocIdForGivenDocument - " +
660
    			  "error closing db resources: "  + e.getMessage());
661
     
662
      }//catch
663
      finally
664
      {
665
        // Return DBConnection to the pool
666
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
667
      }//finally
668
    }//finally
669
        
670
  }//findDataSetDocIdForGivenDocument
671
  
672
  /**
673
   * Method to get current revision and doctype for a given docid
674
   * The output will look like "rev;doctype"
675
   * @param givenDocId, the docid which we want 
676
   */
677
  public String getCurrentRevisionAndDocTypeForGivenDocument(String givenDocId)
678
                                                 throws SQLException
679
  {
680
    // DBConection for JDBC
681
    DBConnection dbConn = null;
682
    int serialNumber = -1;
683
    // Prepared Statement
684
    PreparedStatement pstmt = null;
685
    // String to store a docid without rev
686
    String docIdWithoutRevision = null;
687
    // SQL command
688
    String sqlCommand = null;
689
    // Result set
690
    ResultSet rs = null;
691
    // String to store the revision
692
    String revision = null;
693
    // String to store the doctype
694
    String docType = null;
695
    
696
    // Get docid without rev
697
    docIdWithoutRevision = DocumentUtil.getDocIdFromString(givenDocId);
698
    // SQL command is:
699
    sqlCommand = "select rev, doctype from xml_documents where docid like ?";
700
    
701
    try
702
    {
703
      // Check out the connection
704
      dbConn=DBConnectionPool.
705
         getDBConnection("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument");
706
      serialNumber=dbConn.getCheckOutSerialNumber();
707
      
708
      // Prepare the sql command
709
      pstmt = dbConn.prepareStatement(sqlCommand);
710
      // Bin variable
711
      pstmt.setString(1, docIdWithoutRevision);
712
      // Execute the prepared statement
713
      pstmt.execute();
714
      // Get result set
715
      rs = pstmt.getResultSet();
716
      // If there is some record
717
      if (rs.next())
718
      {
719
        revision = rs.getString(1);
720
        docType = rs.getString(2);
721
      }//if
722
      else
723
      {
724
        // No record, throw a exception
725
        throw new 
726
              SQLException("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument - " + 
727
            		  "There is no record for given docid: " + givenDocId);
728
      }//else
729
        
730
    }
731
    finally
732
    {
733
      try
734
      {
735
        // Close result set
736
        rs.close();
737
        // Close preparedStatement
738
        pstmt.close();
739
      }//try
740
      catch ( SQLException e)
741
      {
742
        // Print out exception
743
    	  logMetacat.error("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument - " + 
744
    			  "Error closing db resources: " + e.getMessage());
745
     
746
      }//catch
747
      finally
748
      {
749
        // Return DBConnection to the pool
750
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
751
      }//finally
752
    }
753
    return revision+";"+docType;
754
  }//getCurrentRevisionAndDocTypeForGivenDocument
755
  
756
  /**
757
   * Method to return a rev list in xml_revision for given docid.
758
   * @param docId
759
   * @return is a vector which contains Integer object
760
   * @throws SQLException
761
   */
762
  public static Vector<Integer> getRevListFromRevisionTable(String docIdWithoutRev) throws SQLException
763
  {
764
      Vector<Integer> list = new Vector<Integer>();
765
      int rev = 1;
766
      PreparedStatement pStmt = null;
767
      DBConnection dbConn = null;
768
      int serialNumber = -1;
769
      // get rid of rev
770
      //docId = MetacatUtil.getDocIdFromString(docId);
771
      try {
772
          //check out DBConnection
773
          dbConn = DBConnectionPool
774
                  .getDBConnection("getRevListFromRevisionTable");
775
          serialNumber = dbConn.getCheckOutSerialNumber();
776

    
777
          pStmt = dbConn
778
                  .prepareStatement("SELECT rev FROM xml_revisions WHERE docid='"
779
                          + docIdWithoutRev + "'");
780
          pStmt.execute();
781

    
782
          ResultSet rs = pStmt.getResultSet();
783
          boolean hasRow = rs.next();
784
          while (hasRow) {
785
              rev = rs.getInt(1);
786
              logMetacat.info("DBUtil.getRevListFromRevisionTable - rev: " + rev + 
787
            		  " is added to list for docid: " + docIdWithoutRev);
788
              list.add(new Integer(rev));
789
              hasRow = rs.next();
790
              
791
          }
792
          pStmt.close();
793
      }//try
794
      finally {
795
          try {
796
              pStmt.close();
797
          } catch (Exception ee) {
798
        	  logMetacat.error("DBUtil.getRevListFromRevisionTable - Error closing " + 
799
        			  "prepared statement: " + ee.getMessage());
800
          } finally {
801
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
802
          }
803
      }//finally
804

    
805
      return list;
806
  }//getLatestRevisionNumber
807
  
808
  /**
809
   * Get last revision number from database for a docid If couldn't find an
810
   * entry, -1 will return The return value is integer because we want compare
811
   * it to there new one
812
   *
813
   * @param docid
814
   *            <sitecode>. <uniqueid>part of Accession Number
815
   */
816
  public static int getLatestRevisionInDocumentTable(String docIdWithoutRev) throws SQLException
817
  {
818
      int rev = 1;
819
      PreparedStatement pStmt = null;
820
      DBConnection dbConn = null;
821
      int serialNumber = -1;
822
      try {
823
          //check out DBConnection
824
          dbConn = DBConnectionPool
825
                  .getDBConnection("DBUtil.getLatestRevisionInDocumentTable");
826
          serialNumber = dbConn.getCheckOutSerialNumber();
827

    
828
          pStmt = dbConn
829
                  .prepareStatement("SELECT rev FROM xml_documents WHERE docid='"
830
                          + docIdWithoutRev + "'");
831
          pStmt.execute();
832

    
833
          ResultSet rs = pStmt.getResultSet();
834
          boolean hasRow = rs.next();
835
          if (hasRow) {
836
              rev = rs.getInt(1);
837
              pStmt.close();
838
          } else {
839
              rev = -1;
840
              pStmt.close();
841
          }
842
      }//try
843
      finally {
844
          try {
845
              pStmt.close();
846
          } catch (Exception ee) {
847
        	  logMetacat.error("DBUtil.getLatestRevisionInDocumentTable - Error closing " + 
848
        			  " prepared statement: " + ee.getMessage());
849
          } finally {
850
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
851
          }
852
      }//finally
853

    
854
      return rev;
855
  }
856
   
857
}
(22-22/59)