Project

General

Profile

1 301 bojilova
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements utility methods like:
4
 *             1/ Reding all doctypes from db connection
5 699 bojilova
 *             2/ Reading DTD or Schema file from Metacat catalog system
6
 *             3/ Reading Lore type Data Guide from db connection
7 301 bojilova
 *  Copyright: 2000 Regents of the University of California and the
8
 *             National Center for Ecological Analysis and Synthesis
9 315 bojilova
 *    Authors: Jivka Bojilova
10 301 bojilova
 *
11
 *   '$Author$'
12
 *     '$Date$'
13
 * '$Revision$'
14 669 jones
 *
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 301 bojilova
 */
29
30
package edu.ucsb.nceas.metacat;
31
32
import java.sql.SQLException;
33
import java.sql.PreparedStatement;
34
import java.sql.ResultSet;
35 699 bojilova
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 301 bojilova
import java.util.Enumeration;
43
import java.util.Vector;
44
45 2663 sgarg
import org.apache.log4j.Logger;
46
47 5015 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
48
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
49 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
50 5025 daigle
import edu.ucsb.nceas.metacat.util.DocumentUtil;
51 4080 daigle
import edu.ucsb.nceas.metacat.util.SystemUtil;
52
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
53
54 301 bojilova
/**
55 5167 daigle
 * A suite of utility classes for querying DB
56 301 bojilova
 */
57
public class DBUtil {
58
59 1217 tao
  //private Connection	conn = null;
60 2663 sgarg
  private static Logger logMetacat = Logger.getLogger(DBUtil.class);
61 301 bojilova
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 5167 daigle
        System.err.println("USAGE: java DBUtil <-dt | -ds [doctype] | -dl user>");
76 301 bojilova
        return;
77
     } else {
78
        try {
79
80
          // Open a connection to the database
81 1217 tao
          //Connection dbconn = util.openDBConnection();
82 301 bojilova
83 1217 tao
          DBUtil dbutil = new DBUtil();
84 301 bojilova
85
          if ( args[0].equals("-dt") ) {
86
            String doctypes = dbutil.readDoctypes();
87
            System.out.println(doctypes);
88 699 bojilova
          } 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 793 bojilova
          } else if ( args[0].equals("-dl") ) {
94 847 jones
            String scope = "";
95
            if ( args.length == 2 ) { scope = args[1]; }
96
            String docid = dbutil.getMaxDocid(scope);
97 793 bojilova
            System.out.println(docid);
98 301 bojilova
          } else {
99 699 bojilova
            System.err.println(
100
            "USAGE: java DBUtil <-dt | -ds [doctype] | -dg [doctype]>");
101 301 bojilova
          }
102
103
        } catch (Exception e) {
104 699 bojilova
          //System.err.println("error in DBUtil.main");
105
          //System.err.println(e.getMessage());
106 301 bojilova
          e.printStackTrace(System.err);
107
        }
108
     }
109
  }
110
111
  /**
112
   * Construct an instance of the utility class
113
   */
114 1217 tao
  public DBUtil() {
115
    //this.conn = conn;
116 301 bojilova
  }
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 5167 daigle
    Vector<String> doctypeList = new Vector<String>();
126 1217 tao
    DBConnection dbConn = null;
127
    int serialNumber = -1;
128
    PreparedStatement pstmt = null;
129 301 bojilova
    try {
130
131 1217 tao
      dbConn=DBConnectionPool.
132
                  getDBConnection("DBUtil.readDoctypes");
133
      serialNumber=dbConn.getCheckOutSerialNumber();
134
      pstmt =
135
        dbConn.prepareStatement("SELECT public_id FROM xml_catalog " +
136 413 bojilova
                              "WHERE entry_type = 'DTD'");
137 301 bojilova
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 5167 daigle
      throw new SQLException("DBUtil.readDoctypes - SQL error: " + e.getMessage());
150 301 bojilova
    }
151 1217 tao
    finally
152
    {
153
      try
154
      {
155
        pstmt.close();
156
      }//try
157
      finally
158
      {
159
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
160
      }//finally
161
    }//finally
162
163 301 bojilova
164
    return formatToXML(doctypeList, "doctype");
165
  }
166
167
  /**
168 699 bojilova
   * read DTD or Schema file from Metacat's XML catalog system
169
   */
170
  public String readDTDSchema(String doctype)
171 4080 daigle
        throws SQLException, MalformedURLException, IOException, PropertyNotFoundException
172 699 bojilova
  {
173
    String systemID = null;
174 1217 tao
    PreparedStatement pstmt = null;
175 699 bojilova
    StringBuffer cbuff = new StringBuffer();
176 1217 tao
    DBConnection dbConn = null;
177
    int serialNumber = -1;
178 699 bojilova
    // get doctype's System ID from db catalog
179
    try {
180 4080 daigle
181 1217 tao
      dbConn=DBConnectionPool.
182
                  getDBConnection("DBUtil.readDTDSchema");
183
      serialNumber=dbConn.getCheckOutSerialNumber();
184
      pstmt = dbConn.prepareStatement("SELECT system_id " +
185 699 bojilova
                                    "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 4080 daigle
        // system id may not have server url on front.  Add it if not.
195
        if (!systemID.startsWith("http://")) {
196 4123 daigle
        	systemID = SystemUtil.getContextURL() + systemID;
197 4080 daigle
        }
198 699 bojilova
      } else {
199 5167 daigle
        throw new SQLException("DBUtil.readDTDSchema - Non-registered doctype: " + doctype);
200 699 bojilova
      }
201
      pstmt.close();
202
203
    } catch (SQLException e) {
204 5167 daigle
      throw new SQLException("DBUtil.readDTDSchema - " + e.getMessage());
205 699 bojilova
    }
206 1217 tao
    finally
207
    {
208
      try
209
      {
210
        pstmt.close();
211
      }//try
212
      finally
213
      {
214
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
215
      }//finally
216
    }//finally
217 699 bojilova
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 5167 daigle
    	throw new MalformedURLException("DBUtil.readDTDSchema - Malformed URL Error: " + e.getMessage());
238 699 bojilova
    } catch (IOException e) {
239 5167 daigle
    	throw new IOException("DBUtil.readDTDSchema - I/O error: " + e.getMessage());
240 699 bojilova
    } catch (SecurityException e) {
241 5167 daigle
    	throw new IOException("DBUtil.readDTDSchema - Security error: " + e.getMessage());
242 699 bojilova
    }
243
244
   return cbuff.toString();
245
  }
246
247 5167 daigle
//  /**
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 374 bojilova
287 5167 daigle
//  /**
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 374 bojilova
316
  /**
317 301 bojilova
   * format the ResultSet to XML
318
   */
319 5167 daigle
  private String formatToXML(Vector<String> resultset, String tag) {
320 301 bojilova
321
    String val = null;
322
    StringBuffer result = new StringBuffer();
323 5167 daigle
    Enumeration<String> rs = resultset.elements();
324 301 bojilova
325
    result.append("<?xml version=\"1.0\"?>\n");
326
    result.append("<resultset>\n");
327
    while (rs.hasMoreElements()) {
328 5167 daigle
        val = rs.nextElement();
329 301 bojilova
        result.append("   <" + tag + ">" + val + "</" + tag + ">\n");
330
    }
331
    result.append("</resultset>\n");
332
333
    return result.toString();
334
  }
335
336 793 bojilova
  /**
337 5167 daigle
   * get the latest Accession Number from a particular scope
338 793 bojilova
   */
339 847 jones
  public String getMaxDocid(String scope)
340 793 bojilova
        throws SQLException  {
341 301 bojilova
342 793 bojilova
    String accnum = null;
343 4080 daigle
    String sep = ".";
344
    try {
345 4212 daigle
    	PropertyService.getProperty("document.accNumSeparator");
346 4080 daigle
    } catch (PropertyNotFoundException pnfe) {
347 5167 daigle
    	logMetacat.error("DBUtil.getMaxDocid - could not get property " +
348
    			"'accNumSeparator'.  setting to '.': " + pnfe.getMessage());
349 4080 daigle
    }
350 1217 tao
    PreparedStatement pstmt = null;
351
    DBConnection dbConn = null;
352
    int serialNumber = -1;
353 793 bojilova
    try {
354 1217 tao
        dbConn=DBConnectionPool.
355
                  getDBConnection("DBUtil.getMaxDocid");
356
        serialNumber=dbConn.getCheckOutSerialNumber();
357
        pstmt =
358
        dbConn.prepareStatement(
359 2560 sgarg
            "SELECT docid, max(rev) FROM " +
360 847 jones
            "( " +
361 2560 sgarg
                "SELECT docid, rev " +
362 847 jones
                "FROM xml_documents " +
363
                "WHERE docid LIKE ? " +
364
            "UNION " +
365 2560 sgarg
                "SELECT docid, rev " +
366 847 jones
                "FROM xml_revisions " +
367 2698 sgarg
                "WHERE docid LIKE ?" +
368 2810 sgarg
            ") subquery GROUP BY docid"
369 847 jones
            );
370
371
      pstmt.setString(1,scope + sep + "%");
372
      pstmt.setString(2,scope + sep + "%");
373 793 bojilova
      pstmt.execute();
374
      ResultSet rs = pstmt.getResultSet();
375 2560 sgarg
376 2984 jones
      long max = 0;
377 2560 sgarg
      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 2984 jones
    			  long localid = Long.parseLong(temp);
385
    			  if (localid > max) {
386 2560 sgarg
    				  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 793 bojilova
      }
395
396
      pstmt.close();
397
398
    } catch (SQLException e) {
399 847 jones
      throw new SQLException("DBUtil.getMaxDocid(). " + e.getMessage());
400 793 bojilova
    }
401 1217 tao
    finally
402
    {
403
      try
404
      {
405
        pstmt.close();
406
      }//try
407
      finally
408
      {
409
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
410
      }//finally
411
    }//finally
412 793 bojilova
413
    return accnum;
414
  }
415 1292 tao
416
  /**
417 3143 berkley
   * 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 5167 daigle
    Vector<String> v = getAllDocids(null);
424 3143 berkley
    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 5094 leinfelder
   * return all docids with a given doctype
437
   */
438 5167 daigle
  public Vector<String> getAllDocidsByType(String doctype, boolean includeRevs) throws SQLException {
439 5094 leinfelder
		Vector<String> resultVector = new Vector<String>();
440
		String sep = ".";
441
	    try {
442
	    	PropertyService.getProperty("document.accNumSeparator");
443
	    } catch (PropertyNotFoundException pnfe) {
444 5167 daigle
	    	logMetacat.error("DBUtil.getAllDocidsByType - could not get property " +
445
	    			"'accNumSeparator'.  setting to '.': " + pnfe.getMessage());
446 5094 leinfelder
	    }
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 5167 daigle
   * get the latest Accession Number from a particular scope
506 3140 berkley
   */
507 4485 daigle
  public Vector<String> getAllDocids(String scope)
508 3140 berkley
        throws SQLException  {
509 4485 daigle
    Vector<String> resultVector = new Vector<String>();
510 5167 daigle
//    String accnum = null;
511 4080 daigle
    String sep = ".";
512
    try {
513 4212 daigle
    	PropertyService.getProperty("document.accNumSeparator");
514 4080 daigle
    } catch (PropertyNotFoundException pnfe) {
515
    	logMetacat.error("could not get property 'accNumSeparator'.  setting to '.': "
516
    			+ pnfe.getMessage());
517
    }
518 3140 berkley
    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 5167 daigle
//      long max = 0;
555 3140 berkley
      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 5167 daigle
      throw new SQLException("DBUtil.getAllDocids - SQL error:  " + e.getMessage());
570 3140 berkley
    }
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 5167 daigle
   * To a given docid, found a dataset docid which contains the the given docid
588 1292 tao
   * 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 5167 daigle
      // SQL command to chose a docid from xm_relation table
612 1292 tao
      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 5167 daigle
      // Execute prepared statement
620 1292 tao
      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 5167 daigle
      // Print out exception
641
      logMetacat.error("DBUtil.findDataSetDocIdForGivenDocument - " +
642
    		  "SQL error: " + e.getMessage());
643 1292 tao
      // 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 5167 daigle
        // Print out exception
659
    	  logMetacat.error("DBUtil.findDataSetDocIdForGivenDocument - " +
660
    			  "error closing db resources: "  + e.getMessage());
661 1292 tao
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 5167 daigle
    // SQL command
688 1292 tao
    String sqlCommand = null;
689 5167 daigle
    // Result set
690 1292 tao
    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 5025 daigle
    docIdWithoutRevision = DocumentUtil.getDocIdFromString(givenDocId);
698 5167 daigle
    // SQL command is:
699 1292 tao
    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 5167 daigle
      // Bin variable
711 1292 tao
      pstmt.setString(1, docIdWithoutRevision);
712 5167 daigle
      // Execute the prepared statement
713 1292 tao
      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 5167 daigle
              SQLException("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument - " +
727
            		  "There is no record for given docid: " + givenDocId);
728 1292 tao
      }//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 5167 daigle
        // Print out exception
743
    	  logMetacat.error("DBUtil.getCurrentRevisionAndDocTypeForGivenDocument - " +
744
    			  "Error closing db resources: " + e.getMessage());
745 1292 tao
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 2606 tao
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 4466 daigle
  public static Vector<Integer> getRevListFromRevisionTable(String docIdWithoutRev) throws SQLException
763 2606 tao
  {
764 4466 daigle
      Vector<Integer> list = new Vector<Integer>();
765 2606 tao
      int rev = 1;
766
      PreparedStatement pStmt = null;
767
      DBConnection dbConn = null;
768
      int serialNumber = -1;
769
      // get rid of rev
770 4698 daigle
      //docId = MetacatUtil.getDocIdFromString(docId);
771 2606 tao
      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 2750 tao
                          + docIdWithoutRev + "'");
780 2606 tao
          pStmt.execute();
781
782
          ResultSet rs = pStmt.getResultSet();
783
          boolean hasRow = rs.next();
784
          while (hasRow) {
785
              rev = rs.getInt(1);
786 5167 daigle
              logMetacat.info("DBUtil.getRevListFromRevisionTable - rev: " + rev +
787
            		  " is added to list for docid: " + docIdWithoutRev);
788 2606 tao
              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 5167 daigle
        	  logMetacat.error("DBUtil.getRevListFromRevisionTable - Error closing " +
799
        			  "prepared statement: " + ee.getMessage());
800 2606 tao
          } finally {
801
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
802
          }
803
      }//finally
804
805
      return list;
806
  }//getLatestRevisionNumber
807 2641 tao
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 5167 daigle
        	  logMetacat.error("DBUtil.getLatestRevisionInDocumentTable - Error closing " +
848
        			  " prepared statement: " + ee.getMessage());
849 2641 tao
          } finally {
850
              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
851
          }
852
      }//finally
853
854
      return rev;
855 5167 daigle
  }
856 1292 tao
857 301 bojilova
}