Project

General

Profile

1 522 berkley
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A class to asyncronously do delta-T replication checking
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 522 berkley
 */
27
28
package edu.ucsb.nceas.metacat;
29
30
import java.sql.*;
31
import java.util.*;
32
import java.lang.Thread;
33
import java.io.*;
34
import java.net.*;
35 543 berkley
import java.text.*;
36 522 berkley
import org.xml.sax.AttributeList;
37
import org.xml.sax.ContentHandler;
38
import org.xml.sax.DTDHandler;
39
import org.xml.sax.EntityResolver;
40
import org.xml.sax.ErrorHandler;
41
import org.xml.sax.InputSource;
42
import org.xml.sax.XMLReader;
43
import org.xml.sax.SAXException;
44
import org.xml.sax.SAXParseException;
45
import org.xml.sax.helpers.XMLReaderFactory;
46 561 berkley
import org.xml.sax.helpers.DefaultHandler;
47 522 berkley
48 561 berkley
49
50 522 berkley
/**
51
 * This class handles deltaT replication checking.  Whenever this TimerTask
52
 * is fired it checks each server in xml_replication for updates and updates
53
 * the local db as needed.
54
 */
55
public class ReplicationHandler extends TimerTask
56
{
57 573 berkley
  int serverCheckCode = 1;
58 522 berkley
  MetaCatUtil util = new MetaCatUtil();
59 1292 tao
  ReplicationServerList serverList = null;
60 522 berkley
  PrintWriter out;
61
62
  public ReplicationHandler(PrintWriter o)
63
  {
64
    this.out = o;
65 1292 tao
    serverList = new ReplicationServerList();
66 522 berkley
  }
67
68 573 berkley
  public ReplicationHandler(PrintWriter o, int serverCheckCode)
69
  {
70
    this.out = o;
71
    this.serverCheckCode = serverCheckCode;
72 1292 tao
    serverList = new ReplicationServerList();
73 573 berkley
  }
74
75 522 berkley
  /**
76
   * Method that implements TimerTask.run().  It runs whenever the timer is
77
   * fired.
78
   */
79
  public void run()
80
  {
81
    //find out the last_checked time of each server in the server list and
82
    //send a query to each server to see if there are any documents in
83
    //xml_documents with an update_date > last_checked
84
    try
85
    {
86 1032 tao
      //if serverList is null, metacat don't need to replication
87
      if (serverList==null||serverList.isEmpty())
88
      {
89
        return;
90
      }
91 1292 tao
      updateCatalog();
92
      update();
93 1217 tao
      //conn.close();
94
    }//try
95 522 berkley
    catch (Exception e)
96
    {
97 1217 tao
      MetaCatUtil.debugMessage("Error in replicationHandler.run():"
98
                                                    +e.getMessage(), 30);
99 1292 tao
      e.printStackTrace();
100 1217 tao
    }//catch
101 522 berkley
  }
102
103
  /**
104 577 berkley
   * Method that uses revision taging for replication instead of update_date.
105
   */
106 1292 tao
  private void update()
107 577 berkley
  {
108
    /*
109
     Pseudo-algorithm
110
     - request a doc list from each server in xml_replication
111
     - check the rev number of each of those documents agains the
112
       documents in the local database
113
     - pull any documents that have a lesser rev number on the local server
114
       from the remote server
115
     - delete any documents that still exist in the local xml_documents but
116
       are in the deletedDocuments tag of the remote host response.
117
     - update last_checked to keep track of the last time it was checked.
118
       (this info is theoretically not needed using this system but probably
119
       should be kept anyway)
120
    */
121 683 berkley
122 1217 tao
    DBConnection dbConn = null;
123
    int serialNumber = -1;
124 1292 tao
125
    ReplicationServer replServer = null; // Variable to store the
126
                                        // ReplicationServer got from
127
                                        // Server list
128
    String server; // Variable to store server name
129 577 berkley
    String update;
130
    ReplMessageHandler message = new ReplMessageHandler();
131
    Vector responses = new Vector();
132 667 berkley
    PreparedStatement pstmt = null;
133 577 berkley
    ResultSet rs;
134
    boolean tablehasrows;
135 1292 tao
    boolean flag=false; // If a document need to update
136 1037 tao
    boolean dataFile=false;
137 577 berkley
    String action = new String();
138
    XMLReader parser;
139
    URL u;
140
141
    try
142
    {
143 1292 tao
      // Get DBConnection from pool
144 1217 tao
      dbConn=DBConnectionPool.
145
                  getDBConnection("ReplicationHandler.update");
146
      serialNumber=dbConn.getCheckOutSerialNumber();
147 1292 tao
      MetaCatUtil.debugMessage("init parser", 50);
148 577 berkley
      parser = initParser(message);
149 1292 tao
      //Check for every server in server list
150
      for (int i=0; i<serverList.size(); i++)
151 577 berkley
      {
152 1292 tao
        // Get ReplicationServer object from server list
153
        replServer = serverList.serverAt(i);
154
        // Get server name from ReplicationServer object
155
        server = replServer.getServerName();
156 584 berkley
        MetacatReplication.replLog("full update started to: " + server);
157 1292 tao
        // Send command to that server to get updated docid information
158 1011 tao
        u = new URL("https://" + server + "?server="
159 1015 tao
        +util.getLocalReplicationServerName()+"&action=update");
160 1292 tao
        MetaCatUtil.debugMessage("Sending infomation " +u.toString(), 50);
161
        // Get information from remote server
162
        String result = null;
163
        try
164
        {
165
          result = MetacatReplication.getURLContent(u);
166
        }//try
167
        catch (Exception e)
168
        {
169
170
          MetaCatUtil.debugMessage("Error in get docid information from "+
171
                                server+" :"+e.getMessage(), 30);
172
          continue;
173
        }//catch
174
        MetaCatUtil.debugMessage("docid: "+server+" "+result, 50);
175
        //check if result have error or not, if has skip it.
176 1102 tao
        if (result.indexOf("error")!=-1)
177
        {
178
          continue;
179
        }
180 577 berkley
        responses.add(result);
181
      }
182
183 1032 tao
      //make sure that there is updated file list
184 1292 tao
      //If response is null, metacat don't need do anything
185 1032 tao
       if (responses==null||responses.isEmpty())
186
      {
187
        return;
188
      }
189 1292 tao
190 1032 tao
191 1292 tao
      MetaCatUtil.debugMessage("Responses from remote metacat about updated "+
192
                   "document information: "+ responses.toString(), 30);
193 577 berkley
194
      for(int i=0; i<responses.size(); i++)
195
      { //check each server for updated files
196
        parser.parse(new InputSource(
197
                     new StringReader(
198
                     (String)(responses.elementAt(i)))));
199 1037 tao
        //v is the list of updated documents
200 577 berkley
        Vector v = new Vector(message.getUpdatesVect());
201
        //System.out.println("v: " + v.toString());
202 1037 tao
        //d is the list of deleted documents
203 577 berkley
        Vector d = new Vector(message.getDeletesVect());
204 1037 tao
        //System.out.println("d: " + d.toString());
205 1292 tao
        MetaCatUtil.debugMessage("Update vector size: "+ v.size(), 40);
206
        MetaCatUtil.debugMessage("Delete vector size: "+ d.size(),40);
207 577 berkley
        //check the revs in u to see if there are any newer ones than
208
        //in the local DB.
209
        for(int j=0; j<v.size(); j++)
210
        {
211 1037 tao
          //initial dataFile is false
212
          dataFile=false;
213
          //w is information for one document, information contain
214
          //docid, rev, server or datafile.
215 577 berkley
          Vector w = new Vector((Vector)(v.elementAt(j)));
216 1037 tao
          //Check if the vector w contain "datafile"
217
          //If it has, this document is data file
218
          if (w.contains((String)util.getOption("datafileflag")))
219
          {
220
            dataFile=true;
221
          }
222 577 berkley
          //System.out.println("w: " + w.toString());
223 1292 tao
          // Get docid
224 577 berkley
          String docid = (String)w.elementAt(0);
225 1071 tao
          MetaCatUtil.debugMessage("docid: " + docid, 40);
226 1292 tao
          // Get revision number
227 577 berkley
          int rev = Integer.parseInt((String)w.elementAt(1));
228 1071 tao
          MetaCatUtil.debugMessage("rev: " + rev, 40);
229 1292 tao
          // Get remote server name (it is may not be doc homeserver because
230
          // the new hub feature
231
          String remoteServer = (String)w.elementAt(2);
232 1071 tao
233 1292 tao
          // Choose revision number from local host
234
          pstmt = dbConn.prepareStatement("select rev from xml_documents where "
235
                                            + "docid like '" + docid + "'");
236 577 berkley
          pstmt.execute();
237
          rs = pstmt.getResultSet();
238
          tablehasrows = rs.next();
239
          if(tablehasrows)
240
          { //check the revs for an update because this document is in the
241 1292 tao
            //local DB, it might be out of date.
242 577 berkley
            int localrev = rs.getInt(1);
243
            if(localrev == rev)
244
            {
245 1292 tao
              // Local meatacat has the same rev to remote host, don't need
246
              // update and flag set false
247 577 berkley
              flag = false;
248
            }
249
            else if(localrev < rev)
250
            {//this document needs to be updated so send an read request
251
              action = "UPDATE";
252
              flag = true;
253
            }
254
          }
255
          else
256
          { //insert this document as new because it is not in the local DB
257
            action = "INSERT";
258
            flag = true;
259
          }
260
261 1292 tao
          // Close result set
262
          rs.close();
263
          // Close preparedstatement
264
          pstmt.close();
265
266 1037 tao
          // this is non-data file
267
          if(flag && !dataFile)
268 577 berkley
          { //if the document needs to be updated or inserted, this is executed
269 1292 tao
            u = new URL("https://" + remoteServer + "?server="+
270 1015 tao
              util.getLocalReplicationServerName()+"&action=read&docid="+docid);
271 1011 tao
            //System.out.println("Sending message: " + u.toString());
272 1292 tao
            // Get docid content
273 577 berkley
            String newxmldoc = MetacatReplication.getURLContent(u);
274 1292 tao
            // If couldn't get skip it
275 1098 tao
            if ( newxmldoc.indexOf("error")!= -1)
276
            {
277 1100 tao
              continue;
278 1098 tao
            }
279 1071 tao
            MetaCatUtil.debugMessage("xml documnet:", 50);
280
            MetaCatUtil.debugMessage(newxmldoc, 50);
281 1292 tao
282
            // Try get the docid info from remote server
283 577 berkley
            DocInfoHandler dih = new DocInfoHandler();
284
            XMLReader docinfoParser = initParser(dih);
285 1292 tao
            URL docinfoUrl = new URL("https://" + remoteServer +
286 1015 tao
                  "?server="+util.getLocalReplicationServerName()+
287 1011 tao
                  "&action=getdocumentinfo&docid="+docid);
288 1292 tao
            MetaCatUtil.debugMessage("Sending message: " +
289
                                                  docinfoUrl.toString(), 50);
290 577 berkley
            String docInfoStr = MetacatReplication.getURLContent(docinfoUrl);
291
            docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
292
            Hashtable docinfoHash = dih.getDocInfo();
293 1292 tao
            // Get home server of the docid
294 1068 tao
            String docHomeServer = (String)docinfoHash.get("home_server");
295 1292 tao
296 1011 tao
            //docid should include rev number too
297
            String accnum=docid+util.getOption("accNumSeparator")+
298
                                              (String)docinfoHash.get("rev");
299 625 berkley
            try
300
            {
301 1292 tao
              // Write the document into local host
302 1387 tao
              String newDocid = DocumentImplWrapper.writeReplication(dbConn,
303 577 berkley
                              new StringReader(newxmldoc),
304 697 bojilova
                              (String)docinfoHash.get("public_access"),
305
                              null,  /* the dtd text */
306 577 berkley
                              action,
307 1011 tao
                              accnum,
308 577 berkley
                              (String)docinfoHash.get("user_owner"),
309 804 bojilova
                              null, /* null for groups[] */
310 1068 tao
                              docHomeServer,
311 1292 tao
                              remoteServer);
312 1217 tao
              //increase usage
313
              dbConn.increaseUsageCount(1);
314 625 berkley
              MetacatReplication.replLog("wrote doc " + docid + " from " +
315 1292 tao
                                         remoteServer);
316 1011 tao
              /*System.out.println("wrote doc " + docid + " from " +
317
                                 docServer);*/
318 625 berkley
            }
319
            catch(Exception e)
320
            {
321 675 berkley
              System.out.println("error writing document in " +
322
                                 "ReplicationHandler.update: " + docid +
323
                                 ": " + e.getMessage());
324 625 berkley
            }
325 1037 tao
          }//if for non-data file
326
327 1292 tao
           // this is for data file
328
          if(flag && dataFile)
329 1037 tao
          {
330
            //if the document needs to be updated or inserted, this is executed
331 1292 tao
332
            // Try get docid info from remote server
333 1037 tao
            DocInfoHandler dih = new DocInfoHandler();
334
            XMLReader docinfoParser = initParser(dih);
335 1292 tao
            URL docinfoUrl = new URL("https://" + remoteServer +
336 1037 tao
                  "?server="+util.getLocalReplicationServerName()+
337
                  "&action=getdocumentinfo&docid="+docid);
338 1292 tao
339 1037 tao
            String docInfoStr = MetacatReplication.getURLContent(docinfoUrl);
340
            docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
341
            Hashtable docinfoHash = dih.getDocInfo();
342 1292 tao
            // Get doicd owner
343 1037 tao
            String user = (String)docinfoHash.get("user_owner");
344 1292 tao
            // Get docid name (such as acl or dataset)
345 1037 tao
            String docName = (String)docinfoHash.get("docname");
346 1292 tao
            // Get doc type (eml public id)
347 1037 tao
            String docType = (String)docinfoHash.get("doctype");
348 1292 tao
            // Get docid home sever. it might be different to remoteserver
349
            // becuause of hub feature
350 1066 tao
            String docHomeServer = (String)docinfoHash.get("home_server");
351 1292 tao
352 1037 tao
            //System.out.println("updating doc: " + docid +" action: "+ action);
353
            //docid should include rev number too
354
            String accnum=docid+util.getOption("accNumSeparator")+
355
                                              (String)docinfoHash.get("rev");
356
            String datafilePath = util.getOption("datafilepath");
357 1292 tao
            // Get data file content
358
            u = new URL("https://" + remoteServer + "?server="+
359 1037 tao
                                        util.getLocalReplicationServerName()+
360
                                            "&action=readdata&docid="+accnum);
361 1292 tao
362 1037 tao
            try
363
            {
364
              //register data file into xml_documents table and wite data file
365
              //into file system
366 1098 tao
              if (u.openStream() != null)
367
              {
368 1292 tao
                DocumentImpl.writeDataFileInReplication(u.openStream(),
369
                                                        datafilePath,
370
                                                        docName,docType,
371
                                                        accnum, user,
372
                                                        docHomeServer,
373
                                                        remoteServer);
374 1037 tao
375 1292 tao
                MetacatReplication.replLog("wrote doc " + docid + " from " +
376
                                         remoteServer);
377
              }//if
378 1098 tao
              else
379
              {
380 1292 tao
                // If get null, skip it
381 1100 tao
                continue;
382 1292 tao
              }//else
383
384
            }//try
385 1037 tao
            catch(Exception e)
386
            {
387
              System.out.println("error writing document in " +
388
                                 "ReplicationHandler.update: " + docid +
389
                                 ": " + e.getMessage());
390 1292 tao
            }//catch
391 1037 tao
          }//for datafile
392
        }//for update docs
393 577 berkley
394 1037 tao
        //handle deleted docs
395 577 berkley
        for(int k=0; k<d.size(); k++)
396
        { //delete the deleted documents;
397
          Vector w = new Vector((Vector)d.elementAt(k));
398
          String docid = (String)w.elementAt(0);
399 1217 tao
          if(!alreadyDeleted(docid))
400 579 berkley
          {
401 1037 tao
402
            //because delete method docid should have rev number
403
            //so we just add one for it. This rev number is no sence.
404
            String accnum=docid+util.getOption("accNumSeparator")+"1";
405
            //System.out.println("accnum: "+accnum);
406 1217 tao
            DocumentImpl.delete(accnum, null, null);
407 584 berkley
            MetacatReplication.replLog("doc " + docid + " deleted");
408 579 berkley
          }
409 1037 tao
        }//for delete docs
410 1292 tao
      }//for
411
412
      //updated last_checked
413
      for (int i=0;i<serverList.size(); i++)
414
      {
415
          // Get ReplicationServer object from server list
416
          replServer = serverList.serverAt(i);
417
          // Get server name from ReplicationServer object
418
          server = replServer.getServerName();
419
          // Get time from remote server
420 1011 tao
          URL dateurl = new URL("https://" + server + "?server="+
421 1015 tao
          util.getLocalReplicationServerName()+"&action=gettime");
422 577 berkley
          String datexml = MetacatReplication.getURLContent(dateurl);
423 1071 tao
          MetaCatUtil.debugMessage("datexml: "+datexml, 40);
424
          if (datexml!=null && !datexml.equals(""))
425
          {
426
            String datestr = datexml.substring(11, datexml.indexOf('<', 11));
427
            StringBuffer sql = new StringBuffer();
428
            sql.append("update xml_replication set last_checked = to_date('");
429
            sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
430
            sql.append("server like '").append(server).append("'");
431
            //System.out.println("sql: " + sql.toString());
432
            pstmt.close();
433 1217 tao
            pstmt = dbConn.prepareStatement(sql.toString());
434
            //increase usage count
435
            dbConn.increaseUsageCount(1);
436 1071 tao
            pstmt.executeUpdate();
437 1217 tao
            dbConn.commit();
438 1292 tao
            MetaCatUtil.debugMessage("last_checked updated to "+datestr+" on "
439
                                      + server, 45);
440
          }//if
441 1037 tao
      }//for
442
    }//try
443 577 berkley
    catch(Exception e)
444
    {
445 1011 tao
      /*System.out.println("error in ReplicationHandler.update: " +
446
                          e.getMessage());*/
447 577 berkley
      e.printStackTrace(System.out);
448
    }
449 667 berkley
    finally
450
    {
451
      try
452
      {
453 1292 tao
454
          pstmt.close();
455
456 1217 tao
      }//try
457
      catch(Exception ee)
458
      {
459
        MetaCatUtil.debugMessage("Error in ReplicationHandler.update to close"+
460
                                " pstmt: "+ee.getMessage(), 30);
461
      }//catch
462
      finally
463
      {
464
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
465
      }//finally
466 1037 tao
    }//finally
467
  }//update
468 577 berkley
469
  /**
470 590 berkley
   * updates xml_catalog with entries from other servers.
471
   */
472 1292 tao
  private void updateCatalog()
473 590 berkley
  {
474 1292 tao
    // DConnection
475 1217 tao
    DBConnection dbConn = null;
476 1292 tao
    // DBConnection checkout serial number
477 1217 tao
    int serialNumber = -1;
478 1292 tao
    // ReplicationServer object in server list
479
    ReplicationServer replServer = null;
480 1217 tao
    PreparedStatement pstmt = null;
481 590 berkley
    try
482
    {
483 1292 tao
484 1217 tao
      dbConn=DBConnectionPool.
485
                  getDBConnection("ReplicationHandler.updateCatalog");
486
      serialNumber=dbConn.getCheckOutSerialNumber();
487 590 berkley
      String server;
488 1292 tao
489
      // Go through each ReplicationServer object in sererlist
490
      for (int j=0; j<serverList.size(); j++)
491
      {
492
        // Get ReplicationServer object from server list
493
        replServer = serverList.serverAt(j);
494
        // Get server name from the ReplicationServer object
495
        server = replServer.getServerName();
496
        // Try to get catalog
497 1011 tao
        URL u = new URL("https://" + server + "?server="+
498 1015 tao
        util.getLocalReplicationServerName()+"&action=getcatalog");
499 1292 tao
        MetaCatUtil.debugMessage("sending message " + u.toString(), 50);
500 590 berkley
        String catxml = MetacatReplication.getURLContent(u);
501 1292 tao
502
        // Make sure there are not error, no empty string
503
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
504
        {
505
          continue;
506
        }
507
        MetaCatUtil.debugMessage("catxml: " + catxml, 50);
508 590 berkley
        CatalogMessageHandler cmh = new CatalogMessageHandler();
509
        XMLReader catparser = initParser(cmh);
510
        catparser.parse(new InputSource(new StringReader(catxml)));
511
        //parse the returned catalog xml and put it into a vector
512
        Vector remoteCatalog = cmh.getCatalogVect();
513
514 1292 tao
        // Makse sure remoteCatalog is not empty
515
        if (remoteCatalog.isEmpty())
516
        {
517
          continue;
518
        }
519
520 590 berkley
        String localcatxml = MetacatReplication.getCatalogXML();
521 1292 tao
522
        // Make sure local catalog is no empty
523
        if (localcatxml==null||localcatxml.equals(""))
524
        {
525
          continue;
526
        }
527
528 590 berkley
        cmh = new CatalogMessageHandler();
529
        catparser = initParser(cmh);
530
        catparser.parse(new InputSource(new StringReader(localcatxml)));
531
        Vector localCatalog = cmh.getCatalogVect();
532
533
        //now we have the catalog from the remote server and this local server
534
        //we now need to compare the two and merge the differences.
535
        //the comparison is base on the public_id fields which is the 4th
536
        //entry in each row vector.
537
        Vector publicId = new Vector();
538
        for(int i=0; i<localCatalog.size(); i++)
539
        {
540
          Vector v = new Vector((Vector)localCatalog.elementAt(i));
541 1292 tao
          MetaCatUtil.debugMessage("v1: " + v.toString(), 50);
542 590 berkley
          publicId.add(new String((String)v.elementAt(3)));
543 595 berkley
          //System.out.println("adding " + (String)v.elementAt(3));
544 590 berkley
        }
545
546
        for(int i=0; i<remoteCatalog.size(); i++)
547
        {
548
          Vector v = (Vector)remoteCatalog.elementAt(i);
549 595 berkley
          //System.out.println("v2: " + v.toString());
550 590 berkley
          //System.out.println("i: " + i);
551
          //System.out.println("remoteCatalog.size(): " + remoteCatalog.size());
552 595 berkley
          //System.out.println("publicID: " + publicId.toString());
553 1292 tao
          MetaCatUtil.debugMessage
554
                              ("v.elementAt(3): " + (String)v.elementAt(3), 50);
555 590 berkley
          if(!publicId.contains(v.elementAt(3)))
556
          { //so we don't have this public id in our local table so we need to
557
            //add it.
558 595 berkley
            //System.out.println("in if");
559 590 berkley
            StringBuffer sql = new StringBuffer();
560
            sql.append("insert into xml_catalog (entry_type, source_doctype, ");
561
            sql.append("target_doctype, public_id, system_id) values (?,?,?,");
562
            sql.append("?,?)");
563 595 berkley
            //System.out.println("sql: " + sql.toString());
564 1217 tao
            pstmt = dbConn.prepareStatement(sql.toString());
565
            //increase usage count 1
566
            dbConn.increaseUsageCount(1);
567 590 berkley
            pstmt.setString(1, (String)v.elementAt(0));
568
            pstmt.setString(2, (String)v.elementAt(1));
569
            pstmt.setString(3, (String)v.elementAt(2));
570
            pstmt.setString(4, (String)v.elementAt(3));
571
            pstmt.setString(5, (String)v.elementAt(4));
572
            pstmt.execute();
573 667 berkley
            pstmt.close();
574 590 berkley
          }
575
        }
576
      }
577 1292 tao
578 590 berkley
    }
579
    catch(Exception e)
580
    {
581 675 berkley
      System.out.println("error in ReplicationHandler.updateCatalog: " +
582
                          e.getMessage());
583 590 berkley
      e.printStackTrace(System.out);
584 1217 tao
    }//catch
585
    finally
586
    {
587 1292 tao
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
588 1217 tao
    }//finall
589 590 berkley
  }
590
591
  /**
592 579 berkley
   * Method that returns true if docid has already been "deleted" from metacat.
593 582 berkley
   * This method really implements a truth table for deleted documents
594 590 berkley
   * The table is (a docid in one of the tables is represented by the X):
595 582 berkley
   * xml_docs      xml_revs      deleted?
596
   * ------------------------------------
597
   *   X             X             FALSE
598
   *   X             _             FALSE
599
   *   _             X             TRUE
600
   *   _             _             TRUE
601 579 berkley
   */
602 1217 tao
  private static boolean alreadyDeleted(String docid)
603 579 berkley
  {
604 1217 tao
    DBConnection dbConn = null;
605
    int serialNumber = -1;
606
    PreparedStatement pstmt = null;
607 579 berkley
    try
608
    {
609 1217 tao
      dbConn=DBConnectionPool.
610
                  getDBConnection("ReplicationHandler.alreadyDeleted");
611
      serialNumber=dbConn.getCheckOutSerialNumber();
612 582 berkley
      boolean xml_docs = false;
613
      boolean xml_revs = false;
614
615 579 berkley
      StringBuffer sb = new StringBuffer();
616 582 berkley
      sb.append("select docid from xml_revisions where docid like '");
617 579 berkley
      sb.append(docid).append("'");
618 1217 tao
      pstmt = dbConn.prepareStatement(sb.toString());
619 579 berkley
      pstmt.execute();
620
      ResultSet rs = pstmt.getResultSet();
621
      boolean tablehasrows = rs.next();
622
      if(tablehasrows)
623
      {
624 582 berkley
        xml_revs = true;
625
      }
626
627
      sb = new StringBuffer();
628
      sb.append("select docid from xml_documents where docid like '");
629
      sb.append(docid).append("'");
630 667 berkley
      pstmt.close();
631 1217 tao
      pstmt = dbConn.prepareStatement(sb.toString());
632
      //increase usage count
633
      dbConn.increaseUsageCount(1);
634 582 berkley
      pstmt.execute();
635
      rs = pstmt.getResultSet();
636
      tablehasrows = rs.next();
637 667 berkley
      pstmt.close();
638 582 berkley
      if(tablehasrows)
639
      {
640
        xml_docs = true;
641
      }
642
643
      if(xml_docs && xml_revs)
644
      {
645
        return false;
646
      }
647
      else if(xml_docs && !xml_revs)
648
      {
649
        return false;
650
      }
651
      else if(!xml_docs && xml_revs)
652
      {
653 579 berkley
        return true;
654
      }
655 582 berkley
      else if(!xml_docs && !xml_revs)
656
      {
657
        return true;
658
      }
659 579 berkley
    }
660
    catch(Exception e)
661
    {
662 675 berkley
      System.out.println("error in ReplicationHandler.alreadyDeleted: " +
663
                          e.getMessage());
664 579 berkley
      e.printStackTrace(System.out);
665
    }
666 667 berkley
    finally
667
    {
668 1217 tao
      try
669
      {
670
        pstmt.close();
671
      }//try
672
      catch (SQLException ee)
673
      {
674
        MetaCatUtil.debugMessage("Error in replicationHandler.alreadyDeleted "+
675
                          "to close pstmt: "+ee.getMessage(), 30);
676
      }//catch
677
      finally
678
      {
679
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
680
      }//finally
681
    }//finally
682 579 berkley
    return false;
683
  }
684 533 berkley
685
686
  /**
687 574 berkley
   * Method to initialize the message parser
688
   */
689
  public static XMLReader initParser(DefaultHandler dh)
690
          throws Exception
691
  {
692
    XMLReader parser = null;
693
694
    try {
695
      ContentHandler chandler = dh;
696
697
      // Get an instance of the parser
698
      MetaCatUtil util = new MetaCatUtil();
699
      String parserName = util.getOption("saxparser");
700
      parser = XMLReaderFactory.createXMLReader(parserName);
701
702
      // Turn off validation
703
      parser.setFeature("http://xml.org/sax/features/validation", false);
704
705
      parser.setContentHandler((ContentHandler)chandler);
706
      parser.setErrorHandler((ErrorHandler)chandler);
707
708
    } catch (Exception e) {
709
      throw e;
710
    }
711
712
    return parser;
713
  }
714 1011 tao
715 1015 tao
716 522 berkley
}