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: 2008-10-29 11:42:15 -0700 (Wed, 29 Oct 2008) $'
13
 * '$Revision: 4485 $'
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.service.PropertyService;
51
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
52
import edu.ucsb.nceas.metacat.util.SystemUtil;
53
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
54

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

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

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

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

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

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

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

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

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

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

    
166
    return formatToXML(doctypeList, "doctype");
167
  }
168

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

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

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

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

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

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

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

    
289
    return result.toString();
290
  }
291

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

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

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

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

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

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

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

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

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

    
418
    return accnum;
419
  }
420
  
421
  /**
422
   * return true if the given docid is registered in either the xml_documents
423
   * or xml_revisions table
424
   */
425
  public boolean idExists(String docid)
426
    throws SQLException
427
  {
428
    Vector v = getAllDocids(null);
429
    for(int i=0; i<v.size(); i++)
430
    {
431
      String id = (String)v.elementAt(i);
432
      if(id.trim().equals(docid.trim()))
433
      {
434
        return true;
435
      }
436
    }
437
    return false;
438
  }
439
  
440
  /**
441
   * get the lastest Accession Number from a particular scope
442
   */
443
  public Vector<String> getAllDocids(String scope)
444
        throws SQLException  {
445
    Vector<String> resultVector = new Vector<String>();
446
    String accnum = null;
447
    String sep = ".";
448
    try {
449
    	PropertyService.getProperty("document.accNumSeparator");
450
    } catch (PropertyNotFoundException pnfe) {
451
    	logMetacat.error("could not get property 'accNumSeparator'.  setting to '.': " 
452
    			+ pnfe.getMessage());  	
453
    }
454
    PreparedStatement pstmt = null;
455
    DBConnection dbConn = null;
456
    int serialNumber = -1;
457
    try 
458
    {
459
      dbConn=DBConnectionPool.
460
                getDBConnection("DBUtil.getAllDocids");
461
      serialNumber=dbConn.getCheckOutSerialNumber();
462
      StringBuffer sb = new StringBuffer();
463
      
464
      sb.append("SELECT docid, rev FROM " +
465
                "( " +
466
                "SELECT docid, rev " + 
467
                "FROM xml_documents ");
468
      if(scope != null)
469
      {
470
        sb.append("WHERE docid LIKE ? ");
471
      }
472
      sb.append("UNION " + 
473
                "SELECT docid, rev " + 
474
                "FROM xml_revisions ");
475
      if(scope != null)
476
      {
477
        sb.append("WHERE docid LIKE ?");
478
      }
479
      sb.append(") subquery GROUP BY docid, rev");
480
      pstmt = dbConn.prepareStatement(sb.toString());
481

    
482
      if(scope != null)
483
      {
484
        pstmt.setString(1,scope + sep + "%");
485
        pstmt.setString(2,scope + sep + "%");
486
      }
487
      pstmt.execute();
488
      ResultSet rs = pstmt.getResultSet();
489
      
490
      long max = 0;
491
      String id = null;
492
      String rev = null;
493
      while(rs.next()){
494
    	  id = rs.getString(1);
495
        rev = rs.getString(2);
496
    	  if(id != null){
497
    		  //temp = temp.substring(id.indexOf(scope) + scope.length() + 1);
498
          resultVector.addElement(id + sep + rev);
499
        }
500
      }
501
      
502
      pstmt.close();
503

    
504
    } catch (SQLException e) {
505
      throw new SQLException("DBUtil.getAllDocids(). " + e.getMessage());
506
    }
507
    finally
508
    {
509
      try
510
      {
511
        pstmt.close();
512
      }//try
513
      finally
514
      {
515
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
516
      }//finally
517
    }//finally
518

    
519
    return resultVector;
520
  }
521
  
522
  /**
523
   * To a given docid, found a dataset docid which conatains the the given doicd
524
   * This will be done by searching xml_relation table
525
   * If couldn't find, null will be return
526
   * @param givenDocId, the docid which we want to find
527
   */
528
  public static String findDataSetDocIdForGivenDocument(String givenDocId)
529
  {
530
    // Prepared statement for sql
531
    PreparedStatement pStmt = null;
532
    // Result set
533
    ResultSet resultSet = null;
534
    // String to store the data set docid
535
    String dataSetDocId = null;
536
    // DBConnection will be checkout
537
    DBConnection dbConn = null;
538
    int serialNumber = -1;
539
    // String to store the sql command
540
    String sqlCommand = null;
541
    try
542
    {
543
      // Checkout DBConnection from pool
544
      dbConn=DBConnectionPool.
545
                  getDBConnection("DBUtil.findDataSetDocIdForGivenDocument");
546
      serialNumber=dbConn.getCheckOutSerialNumber();
547
      // Sql command to chose a docid from xm_relation table
548
      sqlCommand = "select docid from xml_relation where object like ? or " 
549
                                                    + "subject like ?";
550
      // Prepared statement
551
      pStmt = dbConn.prepareStatement(sqlCommand);
552
      // Bind variable
553
      pStmt.setString(1, givenDocId);
554
      pStmt.setString(2, givenDocId);
555
      // Excute prepared statement
556
      pStmt.execute();
557
      // Get result set
558
      resultSet = pStmt.getResultSet();
559
      
560
      // There has record
561
      if (resultSet.next())
562
      {
563
        // Put the docid into dataSetDocid
564
        dataSetDocId = resultSet.getString(1);
565
        return dataSetDocId;
566
      }//if
567
      else
568
      {
569
        // No record in xml_relation table for given doicd, null returned
570
        return dataSetDocId;
571
      }//else
572
    
573
    }//try
574
    catch ( SQLException e)
575
    {
576
      // Print out excepition
577
      logMetacat.error("Error in DBUil.findDataSEtDocIdForGivenDocument"
578
                                +e.getMessage());
579
      // return null
580
      return dataSetDocId;
581
     
582
    }//catch
583
    finally
584
    {
585
      try
586
      {
587
        // Close result set
588
        resultSet.close();
589
        // Close preparedStatement
590
        pStmt.close();
591
      }//try
592
      catch ( SQLException e)
593
      {
594
        // Print out excepition
595
    	  logMetacat.error("Error in DBUil.findDataSetDocIdForGivenDoc"
596
                                + e.getMessage());
597
     
598
      }//catch
599
      finally
600
      {
601
        // Return DBConnection to the pool
602
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
603
      }//finally
604
    }//finally
605
        
606
  }//findDataSetDocIdForGivenDocument
607
  
608
  /**
609
   * Method to get current revision and doctype for a given docid
610
   * The output will look like "rev;doctype"
611
   * @param givenDocId, the docid which we want 
612
   */
613
  public String getCurrentRevisionAndDocTypeForGivenDocument(String givenDocId)
614
                                                 throws SQLException
615
  {
616
    // DBConection for JDBC
617
    DBConnection dbConn = null;
618
    int serialNumber = -1;
619
    // Prepared Statement
620
    PreparedStatement pstmt = null;
621
    // String to store a docid without rev
622
    String docIdWithoutRevision = null;
623
    // SQL comand
624
    String sqlCommand = null;
625
    // Resulst set
626
    ResultSet rs = null;
627
    // String to store the revision
628
    String revision = null;
629
    // String to store the doctype
630
    String docType = null;
631
    
632
    // Get docid without rev
633
    docIdWithoutRevision = MetaCatUtil.getDocIdFromString(givenDocId);
634
    // SQL comand is:
635
    sqlCommand = "select rev, doctype from xml_documents where docid like ?";
636
    
637
    try
638
    {
639
      // Check out the connection
640
      dbConn=DBConnectionPool.
641
         getDBConnection("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument");
642
      serialNumber=dbConn.getCheckOutSerialNumber();
643
      
644
      // Prepare the sql command
645
      pstmt = dbConn.prepareStatement(sqlCommand);
646
      // Bin vairable
647
      pstmt.setString(1, docIdWithoutRevision);
648
      // Excute the prepared statement
649
      pstmt.execute();
650
      // Get result set
651
      rs = pstmt.getResultSet();
652
      // If there is some record
653
      if (rs.next())
654
      {
655
        revision = rs.getString(1);
656
        docType = rs.getString(2);
657
      }//if
658
      else
659
      {
660
        // No record, throw a exception
661
        throw new 
662
              SQLException("There is not record for given docid:"+givenDocId);
663
      }//else
664
        
665
    }
666
    finally
667
    {
668
      try
669
      {
670
        // Close result set
671
        rs.close();
672
        // Close preparedStatement
673
        pstmt.close();
674
      }//try
675
      catch ( SQLException e)
676
      {
677
        // Print out excepition
678
    	  logMetacat.error("Error in DBUil.getCurrentRevisionAndDocType"
679
                                + e.getMessage());
680
     
681
      }//catch
682
      finally
683
      {
684
        // Return DBConnection to the pool
685
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
686
      }//finally
687
    }
688
    return revision+";"+docType;
689
  }//getCurrentRevisionAndDocTypeForGivenDocument
690
  
691
  /**
692
   * Method to return a rev list in xml_revision for given docid.
693
   * @param docId
694
   * @return is a vector which contains Integer object
695
   * @throws SQLException
696
   */
697
  public static Vector<Integer> getRevListFromRevisionTable(String docIdWithoutRev) throws SQLException
698
  {
699
      Vector<Integer> list = new Vector<Integer>();
700
      int rev = 1;
701
      PreparedStatement pStmt = null;
702
      DBConnection dbConn = null;
703
      int serialNumber = -1;
704
      // get rid of rev
705
      //docId = MetaCatUtil.getDocIdFromString(docId);
706
      try {
707
          //check out DBConnection
708
          dbConn = DBConnectionPool
709
                  .getDBConnection("getRevListFromRevisionTable");
710
          serialNumber = dbConn.getCheckOutSerialNumber();
711

    
712
          pStmt = dbConn
713
                  .prepareStatement("SELECT rev FROM xml_revisions WHERE docid='"
714
                          + docIdWithoutRev + "'");
715
          pStmt.execute();
716

    
717
          ResultSet rs = pStmt.getResultSet();
718
          boolean hasRow = rs.next();
719
          while (hasRow) {
720
              rev = rs.getInt(1);
721
              logMetacat.warn("rev "+ rev +" is added to list");
722
              list.add(new Integer(rev));
723
              hasRow = rs.next();
724
              
725
          }
726
          pStmt.close();
727
      }//try
728
      finally {
729
          try {
730
              pStmt.close();
731
          } catch (Exception ee) {
732
        	  logMetacat.error("Error in DocumentImpl."
733
                      + "getLatestRevisionNumber: " + ee.getMessage());
734
          } finally {
735
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
736
          }
737
      }//finally
738

    
739
      return list;
740
  }//getLatestRevisionNumber
741
  
742
  /**
743
   * Get last revision number from database for a docid If couldn't find an
744
   * entry, -1 will return The return value is integer because we want compare
745
   * it to there new one
746
   *
747
   * @param docid
748
   *            <sitecode>. <uniqueid>part of Accession Number
749
   */
750
  public static int getLatestRevisionInDocumentTable(String docIdWithoutRev) throws SQLException
751
  {
752
      int rev = 1;
753
      PreparedStatement pStmt = null;
754
      DBConnection dbConn = null;
755
      int serialNumber = -1;
756
      try {
757
          //check out DBConnection
758
          dbConn = DBConnectionPool
759
                  .getDBConnection("DBUtil.getLatestRevisionInDocumentTable");
760
          serialNumber = dbConn.getCheckOutSerialNumber();
761

    
762
          pStmt = dbConn
763
                  .prepareStatement("SELECT rev FROM xml_documents WHERE docid='"
764
                          + docIdWithoutRev + "'");
765
          pStmt.execute();
766

    
767
          ResultSet rs = pStmt.getResultSet();
768
          boolean hasRow = rs.next();
769
          if (hasRow) {
770
              rev = rs.getInt(1);
771
              pStmt.close();
772
          } else {
773
              rev = -1;
774
              pStmt.close();
775
          }
776
      }//try
777
      finally {
778
          try {
779
              pStmt.close();
780
          } catch (Exception ee) {
781
        	  logMetacat.error("Error in DBUtil."
782
                      + "getLatestRevisionInDocumentTable: " + ee.getMessage());
783
          } finally {
784
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
785
          }
786
      }//finally
787

    
788
      return rev;
789
  }//getLatestRevisionNumber
790
   
791
}
(25-25/67)