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: 2011-12-01 13:10:58 -0800 (Thu, 01 Dec 2011) $'
13
 * '$Revision: 6724 $'
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
  private static final int MAXMUM = -2;
62
  public static final int NONEEXIST = -1;
63

    
64
  /**
65
   * main routine used for testing.
66
   * <p>
67
   * Usage: java DBUtil <-dt|-dg>
68
   *
69
   * @param -dt for selecting all doctypes
70
   *        -dg for selecting DataGuide
71
   */
72
  static public void main(String[] args) {
73
     
74
     if (args.length < 1)
75
     {
76
        System.err.println("Wrong number of arguments!!!");
77
        System.err.println("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<String> doctypeList = new Vector<String>();
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 - SQL error: " + 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("DBUtil.readDTDSchema - Non-registered doctype: " + doctype);
202
      }
203
      pstmt.close();
204

    
205
    } catch (SQLException e) {
206
      throw new SQLException("DBUtil.readDTDSchema - " + 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("DBUtil.readDTDSchema - Malformed URL Error: " + e.getMessage());
240
    } catch (IOException e) {
241
    	throw new IOException("DBUtil.readDTDSchema - I/O error: " + e.getMessage());
242
    } catch (SecurityException e) {
243
    	throw new IOException("DBUtil.readDTDSchema - Security error: " + e.getMessage());
244
    }
245
    
246
   return cbuff.toString();
247
  }
248

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

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

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

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

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

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

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

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

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

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

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

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

    
490
			pstmt.close();
491

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

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

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

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

    
585
    return resultVector;
586
  }
587
  
588
  /**
589
   * To a given docid, found a dataset docid which contains the the given docid
590
   * This will be done by searching xml_relation table
591
   * If couldn't find, null will be return
592
   * @param givenDocId, the docid which we want to find
593
   */
594
  public static String findDataSetDocIdForGivenDocument(String givenDocId)
595
  {
596
    // Prepared statement for sql
597
    PreparedStatement pStmt = null;
598
    // Result set
599
    ResultSet resultSet = null;
600
    // String to store the data set docid
601
    String dataSetDocId = null;
602
    // DBConnection will be checkout
603
    DBConnection dbConn = null;
604
    int serialNumber = -1;
605
    // String to store the sql command
606
    String sqlCommand = null;
607
    try
608
    {
609
      // Checkout DBConnection from pool
610
      dbConn=DBConnectionPool.
611
                  getDBConnection("DBUtil.findDataSetDocIdForGivenDocument");
612
      serialNumber=dbConn.getCheckOutSerialNumber();
613
      // SQL command to chose a docid from xm_relation table
614
      sqlCommand = "select docid from xml_relation where object like ? or " 
615
                                                    + "subject like ?";
616
      // Prepared statement
617
      pStmt = dbConn.prepareStatement(sqlCommand);
618
      // Bind variable
619
      pStmt.setString(1, givenDocId);
620
      pStmt.setString(2, givenDocId);
621
      // Execute prepared statement
622
      pStmt.execute();
623
      // Get result set
624
      resultSet = pStmt.getResultSet();
625
      
626
      // There has record
627
      if (resultSet.next())
628
      {
629
        // Put the docid into dataSetDocid
630
        dataSetDocId = resultSet.getString(1);
631
        return dataSetDocId;
632
      }//if
633
      else
634
      {
635
        // No record in xml_relation table for given doicd, null returned
636
        return dataSetDocId;
637
      }//else
638
    
639
    }//try
640
    catch ( SQLException e)
641
    {
642
      // Print out exception
643
      logMetacat.error("DBUtil.findDataSetDocIdForGivenDocument - " +
644
    		  "SQL error: " + e.getMessage());
645
      // return null
646
      return dataSetDocId;
647
     
648
    }//catch
649
    finally
650
    {
651
      try
652
      {
653
        // Close result set
654
        resultSet.close();
655
        // Close preparedStatement
656
        pStmt.close();
657
      }//try
658
      catch ( SQLException e)
659
      {
660
        // Print out exception
661
    	  logMetacat.error("DBUtil.findDataSetDocIdForGivenDocument - " +
662
    			  "error closing db resources: "  + e.getMessage());
663
     
664
      }//catch
665
      finally
666
      {
667
        // Return DBConnection to the pool
668
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
669
      }//finally
670
    }//finally
671
        
672
  }//findDataSetDocIdForGivenDocument
673
  
674
  /**
675
   * Method to get current revision and doctype for a given docid
676
   * The output will look like "rev;doctype"
677
   * @param givenDocId, the docid which we want 
678
   */
679
  public String getCurrentRevisionAndDocTypeForGivenDocument(String givenDocId)
680
                                                 throws SQLException
681
  {
682
    // DBConection for JDBC
683
    DBConnection dbConn = null;
684
    int serialNumber = -1;
685
    // Prepared Statement
686
    PreparedStatement pstmt = null;
687
    // String to store a docid without rev
688
    String docIdWithoutRevision = null;
689
    // SQL command
690
    String sqlCommand = null;
691
    // Result set
692
    ResultSet rs = null;
693
    // String to store the revision
694
    String revision = null;
695
    // String to store the doctype
696
    String docType = null;
697
    
698
    // Get docid without rev
699
    docIdWithoutRevision = DocumentUtil.getDocIdFromString(givenDocId);
700
    // SQL command is:
701
    sqlCommand = "select rev, doctype from xml_documents where docid like ?";
702
    
703
    try
704
    {
705
      // Check out the connection
706
      dbConn=DBConnectionPool.
707
         getDBConnection("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument");
708
      serialNumber=dbConn.getCheckOutSerialNumber();
709
      
710
      // Prepare the sql command
711
      pstmt = dbConn.prepareStatement(sqlCommand);
712
      // Bin variable
713
      pstmt.setString(1, docIdWithoutRevision);
714
      // Execute the prepared statement
715
      pstmt.execute();
716
      // Get result set
717
      rs = pstmt.getResultSet();
718
      // If there is some record
719
      if (rs.next())
720
      {
721
        revision = rs.getString(1);
722
        docType = rs.getString(2);
723
      }//if
724
      else
725
      {
726
        //search xml_revision table
727
        Vector<Integer> revisionList = getRevListFromRevisionTable(docIdWithoutRevision);
728
        if(revisionList == null || revisionList.isEmpty())
729
        {
730
          // No record, throw a exception
731
          throw new 
732
                SQLException("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument - " + 
733
                    "There is no record for given docid: " + givenDocId);
734
        }
735
        else
736
        {
737
          int maxRev = getMaxmumNumber(revisionList);
738
          if(maxRev == MAXMUM)
739
          {
740
            throw new 
741
            SQLException("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument - " + 
742
                "There is no record for given docid: " + givenDocId);
743
          }
744
          revision = (new Integer(maxRev)).toString();
745
          sqlCommand = "select doctype from xml_revisions where docid like '"+docIdWithoutRevision+"' and rev="+maxRev;
746
          pstmt = dbConn.prepareStatement(sqlCommand);
747
          // Execute the prepared statement
748
          pstmt.execute();
749
          // Get result set
750
          rs = pstmt.getResultSet();
751
          // If there is some record
752
          if (rs.next())
753
          {
754
            docType = rs.getString(1);
755
          }//if
756
        }
757
       
758
      }//else
759
        
760
    }
761
    finally
762
    {
763
      try
764
      {
765
        // Close result set
766
        rs.close();
767
        // Close preparedStatement
768
        pstmt.close();
769
      }//try
770
      catch ( SQLException e)
771
      {
772
        // Print out exception
773
    	  logMetacat.error("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument - " + 
774
    			  "Error closing db resources: " + e.getMessage());
775
     
776
      }//catch
777
      finally
778
      {
779
        // Return DBConnection to the pool
780
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
781
      }//finally
782
    }
783
    return revision+";"+docType;
784
  }//getCurrentRevisionAndDocTypeForGivenDocument
785
  
786
  /*
787
   * Gets the maxium number in a given vector.
788
   */
789
  private static int getMaxmumNumber(Vector<Integer>list)
790
  {
791
    Integer max = null;
792
    if(list != null)
793
    {
794
      for(int i=0; i<list.size(); i++)
795
      {
796
        if(i ==0)
797
        {
798
          max = list.elementAt(i);
799
        }
800
        else
801
        {
802
          if(max == null)
803
          {
804
            max = list.elementAt(i);
805
          }
806
          else
807
          {
808
            Integer current = list.elementAt(i);
809
            if(current != null && current.intValue() > max.intValue())
810
            {
811
              max = current;
812
            }
813
          }
814
        }
815
      }
816
    }
817
    if(max != null)
818
    {
819
      return max.intValue();
820
    }
821
    else
822
    {
823
      return MAXMUM;
824
    }
825
  }
826
 
827
  /**
828
   * Method to return max rev number in xml_revision for given docid.
829
   * @param docId
830
   * @return integer that holds max revision number
831
   * @throws SQLException
832
   */
833
  public static int getMaxRevFromRevisionTable(String docIdWithoutRev) throws SQLException
834
  {
835
	  int rev = NONEEXIST;
836
	  
837
	  Vector<Integer> revList = getRevListFromRevisionTable(docIdWithoutRev);
838
	  
839
	  for (Integer currentRev : revList) {
840
		  if (currentRev > rev) {
841
			  rev = currentRev;
842
		  }
843
	  }
844
	  
845
	  return rev;
846
  }
847
  
848
  /**
849
   * Method to return a rev list in xml_revision for given docid.
850
   * @param docId
851
   * @return is a vector which contains Integer object
852
   * @throws SQLException
853
   */
854
  public static Vector<Integer> getRevListFromRevisionTable(String docIdWithoutRev) throws SQLException
855
  {
856
      Vector<Integer> list = new Vector<Integer>();
857
      int rev = 1;
858
      PreparedStatement pStmt = null;
859
      DBConnection dbConn = null;
860
      int serialNumber = -1;
861
      // get rid of rev
862
      //docId = MetacatUtil.getDocIdFromString(docId);
863
      try {
864
          //check out DBConnection
865
          dbConn = DBConnectionPool
866
                  .getDBConnection("getRevListFromRevisionTable");
867
          serialNumber = dbConn.getCheckOutSerialNumber();
868

    
869
          pStmt = dbConn
870
                  .prepareStatement("SELECT rev FROM xml_revisions WHERE docid = ? ORDER BY rev ASC");
871
          pStmt.setString(1, docIdWithoutRev);
872
          pStmt.execute();
873

    
874
          ResultSet rs = pStmt.getResultSet();
875
          boolean hasRow = rs.next();
876
          while (hasRow) {
877
              rev = rs.getInt(1);
878
              logMetacat.info("DBUtil.getRevListFromRevisionTable - rev: " + rev + 
879
            		  " is added to list for docid: " + docIdWithoutRev);
880
              list.add(new Integer(rev));
881
              hasRow = rs.next();
882
              
883
          }
884
          pStmt.close();
885
      }//try
886
      finally {
887
          try {
888
              pStmt.close();
889
          } catch (Exception ee) {
890
        	  logMetacat.error("DBUtil.getRevListFromRevisionTable - Error closing " + 
891
        			  "prepared statement: " + ee.getMessage());
892
          } finally {
893
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
894
          }
895
      }//finally
896

    
897
      return list;
898
  }//getLatestRevisionNumber
899
  
900
  /**
901
   * Get last revision number from database for a docid If couldn't find an
902
   * entry, -1 will return The return value is integer because we want compare
903
   * it to there new one
904
   *
905
   * @param docid
906
   *            <sitecode>. <uniqueid>part of Accession Number
907
   */
908
  public static int getLatestRevisionInDocumentTable(String docIdWithoutRev) throws SQLException
909
  {
910
      int rev = 1;
911
      PreparedStatement pStmt = null;
912
      DBConnection dbConn = null;
913
      int serialNumber = -1;
914
      try {
915
          //check out DBConnection
916
          dbConn = DBConnectionPool
917
                  .getDBConnection("DBUtil.getLatestRevisionInDocumentTable");
918
          serialNumber = dbConn.getCheckOutSerialNumber();
919

    
920
          pStmt = dbConn
921
                  .prepareStatement("SELECT rev FROM xml_documents WHERE docid = ?");
922
          pStmt.setString(1, docIdWithoutRev);
923
          pStmt.execute();
924

    
925
          ResultSet rs = pStmt.getResultSet();
926
          boolean hasRow = rs.next();
927
          if (hasRow) {
928
              rev = rs.getInt(1);
929
              pStmt.close();
930
          } else {
931
              rev = NONEEXIST;
932
              pStmt.close();
933
          }
934
      }//try
935
      finally {
936
          try {
937
              pStmt.close();
938
          } catch (Exception ee) {
939
        	  logMetacat.error("DBUtil.getLatestRevisionInDocumentTable - Error closing " + 
940
        			  " prepared statement: " + ee.getMessage());
941
          } finally {
942
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
943
          }
944
      }//finally
945

    
946
      return rev;
947
  }
948
  
949
  
950
}
(22-22/64)