Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A class that gets Accession Number, check for uniqueness
4
 *             and register it into db
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Jivka Bojilova, Matt Jones
8
 *    Release: @release@
9
 *
10
 *   '$Author: sgarg $'
11
 *     '$Date: 2004-08-19 18:20:39 -0700 (Thu, 19 Aug 2004) $'
12
 * '$Revision: 2246 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

    
31
import java.net.*;
32
import java.sql.*;
33

    
34
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
35

    
36
/**
37
 * (on insert of XML document)
38
 * Generates a unique Accession Number or if provided check it
39
 * for uniqueness and register it into the db connection
40
 * (on update or delete of XML document)
41
 * Check for existance of provided Accession Number
42
 *
43
 */
44
public class AccessionNumber  {
45

    
46
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
47

    
48
  //private Connection conn = null;
49
  private String sitecode = null;
50
  private String sep = null;
51
  private String docid = null;
52
  private String rev = null;
53

    
54
  /**
55
   * Construct an AccessionNumber
56
   */
57
  //public AccessionNumber ()
58
         //throws SQLException, ClassNotFoundException
59
  //{
60
    // Open a connection to the database from here
61
    //this((new MetaCatUtil()).openDBConnection());
62
  //}
63

    
64
  /**
65
   * Construct an AccessionNumber
66
   *
67
   * @param conn the db connection to read from and write Accession# to
68
   */
69
  public AccessionNumber ()
70
  {
71
    this.sitecode = MetaCatUtil.getOption("sitecode");
72
    this.sep = MetaCatUtil.getOption("accNumSeparator");
73
    //this.conn = conn;
74
  }
75

    
76
  /** NEW - WHEN CLIENT ALWAYS PROVIDE ACCESSION NUMBER INCLUDING REV IN IT
77
   * Construct an AccessionNumber
78
   *
79
   * @param conn the db connection to read Accession number from
80
   * @param accnum the accession number to be checked for validness
81
   */
82
  public AccessionNumber (String accnum, String action)
83
           throws AccessionNumberException, SQLException, NumberFormatException
84
 {
85
    this();
86

    
87
    this.rev = null;
88
    this.docid = accnum;
89
    if ( accnum != null ) {
90
      int firstIndex = accnum.indexOf(this.sep);
91
      int lastIndex = accnum.lastIndexOf(this.sep);
92
      if ( firstIndex != lastIndex ) {
93
        //this docid contains a revision number
94
        this.rev = accnum.substring(lastIndex + 1);
95
        this.docid = accnum.substring(0, lastIndex);
96
      }
97
    }
98

    
99
    // INSERT
100
    if ( action.equals("INSERT")) {
101

    
102
      // check accession number for validness
103
      if ( docid == null ) {
104
        throw new AccessionNumberException("Accession number is required.");
105

    
106
      // rev is not provided; throw an exception to prevent the insertion
107
      } else if ( rev == null ) {
108
        throw new AccessionNumberException
109
                  ("Revision number is required and must be 1.");
110

    
111
      // docid is used; throw an exception to prevent the insertion
112
      } else if ( accNumberUsed(docid) ) {
113
        throw new AccessionNumberException
114
                  ("Accession number " + docid + " is already in use.");
115

    
116
      // rev is <> 1; throw an exception to prevent the insertion
117
      } /*else if ( !rev.equals("1")) {
118
        throw new AccessionNumberException("Revision number must be 1.");
119
      }*/
120

    
121
    // UPDATE or DELETE
122
    } else if ( action.equals("UPDATE") || action.equals("DELETE")) {
123
      String l_rev = "";
124

    
125
      int reversionNumber = 1;
126

    
127
      if(rev != null){
128
        reversionNumber = Integer.parseInt(rev);
129
      }
130

    
131
      // Accession# is not provided; throw an exception to prevent the action
132
      if ( docid == null ) {
133
        throw new AccessionNumberException("Accession number is required.");
134

    
135
      // rev is not provided; throw an exception to prevent the action
136
      } else if ( rev == null ) {
137
        throw new AccessionNumberException
138
                  ("Revision number is required.");
139

    
140
      // Accession# is not current (not in xml_documents); throw an exception
141
      } else if ( !accNumberIsCurrent(docid) ) {
142
        throw new AccessionNumberException
143
                  ("Document not found for Accession number " + docid);
144

    
145
      //Revision number is less than or equal the recent one; throw a exception
146
      } else if ( action.equals("UPDATE") &&
147
                  reversionNumber <= getLastRevisionNumber(docid) ) {
148
        throw new AccessionNumberException
149
                 ("Next revision number couldn't be less than or equal "
150
                                              + getLastRevisionNumber(docid));
151

    
152
      // Revision number is not the recent one; throw an exception
153
      } else if ( action.equals("DELETE") &&
154
                  !rev.equals(l_rev = getLastRevision(docid)) ) {
155
        throw new AccessionNumberException
156
                  ("Last revision number is "+ l_rev);
157
      }
158
    }
159
  }
160

    
161
  /**
162
   * Generate an Accession Number of form <sidecode>.<uniqueid>.<revisionid>
163
   * where <revisionid> is always 1.
164
   *
165
   * @param docid <sitecode>.<uniqueid> part of Accession Number
166
   * @param action INSERT, UPDATE or DELETE action
167
   */
168
  public String generate(String docid, String action)
169
                throws AccessionNumberException, SQLException
170
  {
171
    return generate(docid, "1", action);
172
  }
173

    
174
  /**
175
   * Generate an Accession Number of form <sidecode>.<uniqueid>.<revisionid>
176
   *
177
   * @param docid <sitecode>.<uniqueid> part of Accession Number
178
   * @param rev <revisionid> of Accession Number
179
   * @param action INSERT, UPDATE or DELETE action
180
   */
181
  public String generate(String docid, String rev, String action)
182
                throws AccessionNumberException, SQLException
183
  {
184
    try {
185
      // INSERT
186
      if ( action.equals("INSERT")) {
187

    
188
        // get a new docid
189
        if ( docid == null ) {
190
          String sitecode = getSitecode();
191
          String uniqueid = getUniqueID(sitecode);
192

    
193
          return sitecode + sep + uniqueid;
194

    
195
        // docid is used; throw an exception to prevent the insertion
196
        } else if ( accNumberUsed(docid) ) {
197
          throw new AccessionNumberException
198
                    ("Accession number " + docid + " is already in use.");
199
        // rev is <> 1; throw an exception to prevent the insertion
200
        } else if ( !rev.equals("1") ) {
201
          throw new AccessionNumberException
202
                    ("Revision number must be 1.");
203
        // docid is not used and rev=1; return it
204
        } else {
205
          return docid;
206
        }
207

    
208
      // UPDATE or DELETE
209
      } else if ( action.equals("UPDATE") || action.equals("DELETE")) {
210

    
211
        // Accession# is not provided; throw an exception to prevent the action
212
        if ( docid == null ) {
213
          throw new AccessionNumberException("Accession number is required.");
214

    
215
        // Accession# is not current (not in xml_documents); throw an exception
216
        } else if ( !accNumberIsCurrent(docid) ) {
217
          throw new AccessionNumberException
218
          ("Document not found for Accession number " + docid);
219

    
220
        // Revision number is not the recent one; throw an exception
221
        } else if ( !rev.equals(getLastRevision(docid)) ) {
222
          throw new AccessionNumberException
223
          ("Revision number must be the recent.");
224

    
225
        // Accession# is current (present in xml_documents); return it
226
        } else {
227
          return docid;
228
        }
229
      }
230

    
231
    } catch (SQLException e) {
232
      throw new SQLException
233
      ("Error on AccessionNumber.generate(): " + e.getMessage());
234
    }
235

    
236
    // never comes here
237
    throw new
238
    AccessionNumberException("Fatal Error in accession number generation.");
239
  }
240

    
241
  // get local sitecode
242
  private String getSitecode()
243
  {
244
    return this.sitecode;
245
  }
246

    
247
  // get Unique ID from DB sequence
248
  private String getUniqueID (String sitecode) throws SQLException
249
  {
250
    String uniqueid;
251
    String sysdate = dbAdapter.getDateTimeFunction();
252
    DBConnection conn = null;
253
    int serialNumber = -1;
254
    try {
255
      PreparedStatement pstmt = null;
256

    
257
      //check out DBConnection
258
      conn=DBConnectionPool.getDBConnection("AccessionNumber.getUniqueID");
259
      serialNumber=conn.getCheckOutSerialNumber();
260
      pstmt = conn.prepareStatement
261
              ("INSERT INTO accession_number (site_code, date_created) " +
262
               "VALUES (?, " + sysdate + ")");
263
      pstmt.setString(1, sitecode);
264
      pstmt.execute();
265
      pstmt.close();
266

    
267
      uniqueid = "" + dbAdapter.getUniqueID(conn.getConnections(),
268
                                                          "accession_number");
269
      //because we only count the connection usage one when it check in
270
      //but it use twice. So we need to increase one
271
      conn.increaseUsageCount(1);
272

    
273
    } catch (SQLException e) {
274
      throw new
275
      SQLException("Error on AccessionNumber.getUniqueID(): "+e.getMessage());
276
    }
277
    finally
278
    {
279
      DBConnectionPool.returnDBConnection(conn, serialNumber);
280
    }
281
    return uniqueid;
282
  }
283

    
284
  /** check for existence of Accesssion Number xml_acc_numbers table */
285
  public static boolean accNumberUsed ( String accNumber )
286
                  throws SQLException {
287

    
288
    boolean hasAccNumber = false;
289
    DBConnection conn = null;
290
    int serialNumber = -1;
291

    
292
    try {
293
      PreparedStatement pstmt = null;
294
      //check out DBConnection
295
      conn=DBConnectionPool.getDBConnection("AccessionNumber.accNumberUsed");
296
      serialNumber=conn.getCheckOutSerialNumber();
297
      pstmt = conn.prepareStatement(
298
                "SELECT 'x' FROM xml_documents " +
299
                "WHERE docid = ? " +
300
                "UNION " +
301
                "SELECT 'x' FROM xml_revisions " +
302
                "WHERE docid = ?");
303
      pstmt.setString(1,accNumber);
304
      pstmt.setString(2,accNumber);
305
      pstmt.execute();
306
      ResultSet rs = pstmt.getResultSet();
307
      hasAccNumber = rs.next();
308
      pstmt.close();
309

    
310
    } catch (SQLException e) {
311
      throw new SQLException
312
      ("Error on AccessionNumber.accNumberUsed(accNumber): " + e.getMessage());
313
    }
314
    finally
315
    {
316
      DBConnectionPool.returnDBConnection(conn, serialNumber);
317
    }
318

    
319
    return hasAccNumber;
320
  }
321

    
322
  // check for existence of Accesssion Number in xml_documents table
323
  private boolean accNumberIsCurrent(String accNumber) throws SQLException {
324

    
325
    boolean hasCurrentAccNumber = false;
326
    DBConnection conn = null;
327
    int serialNumber = -1;
328

    
329
    try {
330
      PreparedStatement pstmt = null;
331
      //check out DBConnection
332
      conn=DBConnectionPool.getDBConnection("AccessionNumber.accNumberIsCurre");
333
      serialNumber=conn.getCheckOutSerialNumber();
334
      pstmt = conn.prepareStatement(
335
                "SELECT 'x' FROM xml_documents " +
336
                "WHERE docid = ?");
337
      pstmt.setString(1, accNumber);
338
      pstmt.execute();
339
      ResultSet rs = pstmt.getResultSet();
340
      hasCurrentAccNumber = rs.next();
341
      pstmt.close();
342

    
343
    } catch (SQLException e) {
344
      throw new SQLException(
345
          "Error on AccessionNumber.accNumberIsCurrent(String accNumber): " +
346
          e.getMessage());
347
    }
348
    finally
349
    {
350
      DBConnectionPool.returnDBConnection(conn, serialNumber);
351
    }
352

    
353
    return hasCurrentAccNumber;
354
  }
355

    
356
  // get the recent revision number for docid
357
  private String getLastRevision(String docid) throws SQLException
358
  {
359
    String rev = "";
360
    DBConnection conn = null;
361
    int serialNumber = -1;
362

    
363
    try {
364
      PreparedStatement pstmt = null;
365
      //check out DBConnection
366
      conn=DBConnectionPool.getDBConnection("AccessionNumber.getLastRevision");
367
      serialNumber=conn.getCheckOutSerialNumber();
368
      pstmt = conn.prepareStatement
369
              ("SELECT rev FROM xml_documents WHERE docid='" + docid + "'");
370
      pstmt.execute();
371

    
372
      ResultSet rs = pstmt.getResultSet();
373
      boolean hasRow = rs.next();
374
      rev = rs.getString(1);
375
      pstmt.close();
376

    
377
    } catch (SQLException e) {
378
      throw new SQLException(
379
      "Error on AccessionNumber.getLastRevision(): " + e.getMessage());
380
    }
381
    finally
382
    {
383
      DBConnectionPool.returnDBConnection(conn,serialNumber);
384
    }
385

    
386
    return rev;
387
  }
388

    
389
  /**
390
    * Get last revision number from database for a docid
391
    * The return value is integer because we want compare it to there new one
392
    * @param docid <sitecode>.<uniqueid> part of Accession Number
393
    */
394
  private int getLastRevisionNumber(String docId) throws SQLException
395
  {
396
    int rev = 1;
397
    DBConnection conn =null;
398
    int serialNumber = -1;
399

    
400
    try {
401
      PreparedStatement pStmt = null;
402
      //check out DBConnection
403
      conn=DBConnectionPool.getDBConnection("AccessionNumber.getLastRevisionN");
404
      serialNumber=conn.getCheckOutSerialNumber();
405

    
406
      pStmt = conn.prepareStatement
407
              ("SELECT rev FROM xml_documents WHERE docid='" + docId + "'");
408
      pStmt.execute();
409

    
410
      ResultSet rs = pStmt.getResultSet();
411
      boolean hasRow = rs.next();
412
      rev = rs.getInt(1);
413
      pStmt.close();
414

    
415
    } catch (SQLException e) {
416
      throw new SQLException(
417
      "Error on AccessionNumber.getLastRevision(): " + e.getMessage());
418
    }
419
    finally
420
    {
421
      DBConnectionPool.returnDBConnection(conn,serialNumber);
422
    }
423
    return rev;
424
  }
425

    
426
  // get the next revision number for docid
427
  private String getNextRevision(String docid) throws SQLException
428
  {
429
    String rev = "";
430
    DBConnection conn = null;
431
    int serialNumber = -1;
432
    try {
433
      PreparedStatement pstmt = null;
434
      //check out DBConnection
435
      conn=DBConnectionPool.getDBConnection("AccessionNumber.getNextRevision");
436
      serialNumber=conn.getCheckOutSerialNumber();
437
      pstmt = conn.prepareStatement
438
              ("SELECT rev+1 FROM xml_documents WHERE docid='" + docid + "'");
439
      pstmt.execute();
440

    
441
      ResultSet rs = pstmt.getResultSet();
442
      boolean hasRow = rs.next();
443
      rev = rs.getString(1);
444
      pstmt.close();
445

    
446
    } catch (SQLException e) {
447
      throw new SQLException(
448
      "Error on AccessionNumber.getNextRevision(): " + e.getMessage());
449
    }
450
    finally
451
    {
452
      DBConnectionPool.returnDBConnection(conn, serialNumber);
453
    }
454

    
455
    return rev;
456
  }
457

    
458
  /**
459
   * returns the docid encoded in this accession number
460
   */
461
  public String getDocid() {
462

    
463
    return this.docid;
464
  }
465

    
466
  /**
467
   * returns the revision number encoded in this accession number
468
   */
469
  public String getRev()
470
  {
471
    return this.rev;
472
  }
473

    
474
}
(6-6/62)