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: leinfelder $'
12
 *     '$Date: 2009-10-27 15:42:09 -0700 (Tue, 27 Oct 2009) $'
13
 * '$Revision: 5094 $'
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.Connection;
33
import java.sql.SQLException;
34
import java.sql.PreparedStatement;
35
import java.sql.ResultSet;
36

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

    
44
import java.util.Enumeration;
45
import java.util.Vector;
46
import java.util.Stack;
47

    
48
import org.apache.log4j.Logger;
49

    
50
import edu.ucsb.nceas.metacat.database.DBConnection;
51
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
52
import edu.ucsb.nceas.metacat.properties.PropertyService;
53
import edu.ucsb.nceas.metacat.util.DocumentUtil;
54
import edu.ucsb.nceas.metacat.util.SystemUtil;
55
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
56

    
57
/**
58
 * A suite of utility classes for quering DB
59
 */
60
public class DBUtil {
61

    
62
  //private Connection	conn = null;
63
  private static Logger logMetacat = Logger.getLogger(DBUtil.class);
64

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

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

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

    
122
  /**
123
   * read all doctypes from db connection in XML format
124
   * select all Public Id from xml_catalog table
125
   */
126
  public String readDoctypes()
127
        throws SQLException  {
128

    
129
    Vector doctypeList = new Vector();
130
    DBConnection dbConn = null;
131
    int serialNumber = -1;
132
    PreparedStatement pstmt = null;
133
    try {
134

    
135
      dbConn=DBConnectionPool.
136
                  getDBConnection("DBUtil.readDoctypes");
137
      serialNumber=dbConn.getCheckOutSerialNumber();
138
      pstmt =
139
        dbConn.prepareStatement("SELECT public_id FROM xml_catalog " +
140
                              "WHERE entry_type = 'DTD'");
141

    
142
      pstmt.execute();
143
      ResultSet rs = pstmt.getResultSet();
144
      boolean tableHasRows = rs.next();
145
      while (tableHasRows) {
146
           doctypeList.addElement(rs.getString(1));
147
           tableHasRows = rs.next();
148
      }
149
      
150
      pstmt.close();
151

    
152
    } catch (SQLException e) {
153
      throw new SQLException("DBUtil.readDoctypes(). " + e.getMessage());
154
    }
155
    finally
156
    {
157
      try
158
      {
159
        pstmt.close();
160
      }//try
161
      finally
162
      {
163
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
164
      }//finally
165
    }//finally
166
       
167

    
168
    return formatToXML(doctypeList, "doctype");
169
  }
170

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

    
207
    } catch (SQLException e) {
208
      throw new SQLException("DBUtil.readDTD(). " + e.getMessage());
209
    }
210
    finally
211
    {
212
      try
213
      {
214
        pstmt.close();
215
      }//try
216
      finally
217
      {
218
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
219
      }//finally
220
    }//finally
221

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

    
231
      // read the input and write into the string buffer
232
	    int inputByte;
233
	    while ( (inputByte = in.read()) != -1 ) {
234
        cbuff.append((char)inputByte);
235
	    }
236

    
237
      // the input stream must be closed
238
	    in.close();
239
	    
240
    } catch (MalformedURLException e) {
241
      throw new MalformedURLException
242
      ("DBUtil.readDTD(). " + e.getMessage());
243
    } catch (IOException e) {
244
      throw new IOException
245
      ("DBUtil.readDTD(). " + e.getMessage());
246
    } catch (SecurityException e) {
247
      throw new IOException
248
      ("DBUtil.readDTD(). " + e.getMessage());
249
    }
250
    
251
   return cbuff.toString();
252
  }
253

    
254
  /**
255
   * format the DataGuide ResultSet to XML
256
   */
257
  private String formatToXML(Vector resultset) {
258
  
259
    String currPath = null;
260
    String currElement = null;
261
    String prevElement = null;
262
    StringBuffer result = new StringBuffer();
263
    Enumeration rs = resultset.elements(); 
264
    Stack st = new Stack();
265
    int i = 0;
266

    
267
    result.append("<?xml version=\"1.0\"?>\n");
268
    result.append("<resultset>\n"); 
269
    
270
    while (rs.hasMoreElements()) {
271
        currPath = (String)rs.nextElement();
272
        while ( !In(prevElement, currPath) ) {
273
            currElement = (String)st.pop();
274
            result.append(pad(" ",i--) + "</" + currElement + ">\n");
275
            if ( st.empty() ) 
276
                prevElement = null;
277
            else    
278
                prevElement = (String)st.peek();
279
        }    
280
        currElement = getElementFromPath(currPath);
281
        st.push(currElement);
282
        result.append(pad(" ",++i) + "<" + currElement + ">\n");
283
        prevElement = currElement;
284
    }
285
    while ( !st.empty() ) {
286
        prevElement = (String)st.pop();
287
        result.append(pad(" ",i--) + "</" + prevElement + ">\n");
288
    }    
289
    result.append("</resultset>\n"); 
290

    
291
    return result.toString();
292
  }
293

    
294
  /**
295
   * check if element is in path like /elem1/elem2/elemn3
296
   */
297
  private boolean In(String element, String path) {
298
    
299
    if ( element == null ) return true;
300
    return ( path.indexOf(element) != -1 );
301
  }
302

    
303
  /**
304
   * get last element from path like /elem1/elem2/elemn3
305
   */
306
  private String getElementFromPath(String path) {
307
    
308
    return ( path.substring(path.lastIndexOf("/")+1) );
309
  }
310

    
311
  /**
312
   * repeates the str n-times
313
   */
314
  private String pad(String str, int n) {
315
    
316
    String result = "";
317
    for ( int i = 0; i < n; i++ )
318
        result = result.concat(str);
319
        
320
    return result;    
321
  }
322

    
323
  /**
324
   * format the ResultSet to XML
325
   */
326
  private String formatToXML(Vector resultset, String tag) {
327
  
328
    String val = null;
329
    StringBuffer result = new StringBuffer();
330
    Enumeration rs = resultset.elements(); 
331

    
332
    result.append("<?xml version=\"1.0\"?>\n");
333
    result.append("<resultset>\n"); 
334
    while (rs.hasMoreElements()) {
335
        val = (String)rs.nextElement();
336
        result.append("   <" + tag + ">" + val + "</" + tag + ">\n");
337
    }
338
    result.append("</resultset>\n"); 
339
    
340
    return result.toString();
341
  }
342

    
343
  /**
344
   * get the lastest Accession Number from a particular scope
345
   */
346
  public String getMaxDocid(String scope)
347
        throws SQLException  {
348

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

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

    
405
    } catch (SQLException e) {
406
      throw new SQLException("DBUtil.getMaxDocid(). " + e.getMessage());
407
    }
408
    finally
409
    {
410
      try
411
      {
412
        pstmt.close();
413
      }//try
414
      finally
415
      {
416
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
417
      }//finally
418
    }//finally
419

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

    
463
			sb.append("SELECT docid, rev FROM " + "( " + "SELECT docid, rev "
464
					+ "FROM xml_documents ");
465
			if (doctype != null) {
466
				sb.append("WHERE doctype LIKE ? ");
467
			}
468
			if (includeRevs) {
469
				sb.append("UNION " + "SELECT docid, rev " + "FROM xml_revisions ");
470
				if (doctype != null) {
471
					sb.append("WHERE doctype LIKE ?");
472
				}
473
			}
474
			sb.append(") subquery GROUP BY docid, rev");
475
			pstmt = dbConn.prepareStatement(sb.toString());
476

    
477
			if (doctype != null) {
478
				pstmt.setString(1, doctype);
479
				if (includeRevs) {
480
					pstmt.setString(2, doctype);
481
				}
482
			}
483
			pstmt.execute();
484
			ResultSet rs = pstmt.getResultSet();
485

    
486
			String id = null;
487
			String rev = null;
488
			while (rs.next()) {
489
				id = rs.getString(1);
490
				rev = rs.getString(2);
491
				if (id != null) {
492
					resultVector.addElement(id + sep + rev);
493
				}
494
			}
495

    
496
			pstmt.close();
497

    
498
		} catch (SQLException e) {
499
			throw new SQLException("DBUtil.getAllDocidsByType(). " + e.getMessage());
500
		} finally {
501
			try {
502
				pstmt.close();
503
			}// try
504
			finally {
505
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
506
			}// finally
507
		}// finally
508

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

    
554
      if(scope != null)
555
      {
556
        pstmt.setString(1,scope + sep + "%");
557
        pstmt.setString(2,scope + sep + "%");
558
      }
559
      pstmt.execute();
560
      ResultSet rs = pstmt.getResultSet();
561
      
562
      long max = 0;
563
      String id = null;
564
      String rev = null;
565
      while(rs.next()){
566
    	  id = rs.getString(1);
567
        rev = rs.getString(2);
568
    	  if(id != null){
569
    		  //temp = temp.substring(id.indexOf(scope) + scope.length() + 1);
570
          resultVector.addElement(id + sep + rev);
571
        }
572
      }
573
      
574
      pstmt.close();
575

    
576
    } catch (SQLException e) {
577
      throw new SQLException("DBUtil.getAllDocids(). " + e.getMessage());
578
    }
579
    finally
580
    {
581
      try
582
      {
583
        pstmt.close();
584
      }//try
585
      finally
586
      {
587
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
588
      }//finally
589
    }//finally
590

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

    
784
          pStmt = dbConn
785
                  .prepareStatement("SELECT rev FROM xml_revisions WHERE docid='"
786
                          + docIdWithoutRev + "'");
787
          pStmt.execute();
788

    
789
          ResultSet rs = pStmt.getResultSet();
790
          boolean hasRow = rs.next();
791
          while (hasRow) {
792
              rev = rs.getInt(1);
793
              logMetacat.warn("rev "+ rev +" is added to list");
794
              list.add(new Integer(rev));
795
              hasRow = rs.next();
796
              
797
          }
798
          pStmt.close();
799
      }//try
800
      finally {
801
          try {
802
              pStmt.close();
803
          } catch (Exception ee) {
804
        	  logMetacat.error("Error in DocumentImpl."
805
                      + "getLatestRevisionNumber: " + ee.getMessage());
806
          } finally {
807
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
808
          }
809
      }//finally
810

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

    
834
          pStmt = dbConn
835
                  .prepareStatement("SELECT rev FROM xml_documents WHERE docid='"
836
                          + docIdWithoutRev + "'");
837
          pStmt.execute();
838

    
839
          ResultSet rs = pStmt.getResultSet();
840
          boolean hasRow = rs.next();
841
          if (hasRow) {
842
              rev = rs.getInt(1);
843
              pStmt.close();
844
          } else {
845
              rev = -1;
846
              pStmt.close();
847
          }
848
      }//try
849
      finally {
850
          try {
851
              pStmt.close();
852
          } catch (Exception ee) {
853
        	  logMetacat.error("Error in DBUtil."
854
                      + "getLatestRevisionInDocumentTable: " + ee.getMessage());
855
          } finally {
856
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
857
          }
858
      }//finally
859

    
860
      return rev;
861
  }//getLatestRevisionNumber
862
   
863
}
(21-21/58)