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 1292 tao
    ReplicationServer replServer = null; // Variable to store the
123
                                        // ReplicationServer got from
124
                                        // Server list
125
    String server; // Variable to store server name
126 577 berkley
    String update;
127
    ReplMessageHandler message = new ReplMessageHandler();
128
    Vector responses = new Vector();
129 1292 tao
    boolean flag=false; // If a document need to update
130 1037 tao
    boolean dataFile=false;
131 577 berkley
    String action = new String();
132
    XMLReader parser;
133
    URL u;
134
135 1585 tao
136 577 berkley
    try
137
    {
138
      parser = initParser(message);
139 1585 tao
    }
140
    catch (Exception e)
141
    {
142
      MetacatReplication.replErrorLog("Failed to replicate becaue couldn't "+
143
                                 " initParser for message and" +e.getMessage());
144
      MetaCatUtil.debugMessage("Failed to replicate becaue couldn't " +
145
                            " initParser for message and " +e.getMessage(), 30);
146
       // stop replication
147
       return;
148
    }
149
    //Check for every server in server list to get updated list and put
150
    // them in to response
151
    for (int i=0; i<serverList.size(); i++)
152
    {
153 1292 tao
        // Get ReplicationServer object from server list
154
        replServer = serverList.serverAt(i);
155
        // Get server name from ReplicationServer object
156
        server = replServer.getServerName();
157 1585 tao
        String result = null;
158 584 berkley
        MetacatReplication.replLog("full update started to: " + server);
159 1292 tao
        // Send command to that server to get updated docid information
160
        try
161
        {
162 1585 tao
          u = new URL("https://" + server + "?server="
163
          +util.getLocalReplicationServerName()+"&action=update");
164
          MetaCatUtil.debugMessage("Sending infomation " +u.toString(), 50);
165 1292 tao
          result = MetacatReplication.getURLContent(u);
166 1585 tao
        }
167 1292 tao
        catch (Exception e)
168
        {
169 1585 tao
          MetacatReplication.replErrorLog("Failed to get updated doc list "+
170
                          "for server " + server + " because "+e.getMessage());
171
          MetaCatUtil.debugMessage( "Failed to get updated doc list "+
172
                       "for server " + server + " because "+e.getMessage(), 30);
173 1292 tao
          continue;
174 1585 tao
        }
175
176 1292 tao
        MetaCatUtil.debugMessage("docid: "+server+" "+result, 50);
177
        //check if result have error or not, if has skip it.
178 1102 tao
        if (result.indexOf("error")!=-1)
179
        {
180 1585 tao
          MetacatReplication.replErrorLog("Failed to get updated doc list "+
181
                          "for server " + server + " because "+result);
182
          MetaCatUtil.debugMessage( "Failed to get updated doc list "+
183
                       "for server " + server + " because "+result, 30);
184 1102 tao
          continue;
185
        }
186 1585 tao
        //Add result to vector
187 577 berkley
        responses.add(result);
188 1585 tao
    }
189 577 berkley
190 1585 tao
    //make sure that there is updated file list
191
    //If response is null, metacat don't need do anything
192
    if (responses==null || responses.isEmpty())
193
    {
194
        MetacatReplication.replErrorLog("No updated doc list for "+
195
                           "every server and failed to replicate");
196
        MetaCatUtil.debugMessage( "No updated doc list for "+
197
                           "every server and failed to replicate", 30);
198 1032 tao
        return;
199 1585 tao
    }
200 1292 tao
201 1032 tao
202 1585 tao
    MetaCatUtil.debugMessage("Responses from remote metacat about updated "+
203
                   "document information: "+ responses.toString(), 35);
204
    // go through response vector(it contains updated vector and delete vector
205
    for(int i=0; i<responses.size(); i++)
206
    {
207
        try
208
        {
209
          parser.parse(new InputSource(
210 577 berkley
                     new StringReader(
211
                     (String)(responses.elementAt(i)))));
212 1585 tao
        }
213
        catch(Exception e)
214
        {
215
          MetacatReplication.replErrorLog("Couldn't parse one responses "+
216
                           "because "+ e.getMessage());
217
          MetaCatUtil.debugMessage("Couldn't parse one responses "+
218
                                   "because "+ e.getMessage(), 30);
219
          continue;
220
        }
221 1037 tao
        //v is the list of updated documents
222 1585 tao
        Vector updateList = new Vector(message.getUpdatesVect());
223 577 berkley
        //System.out.println("v: " + v.toString());
224 1037 tao
        //d is the list of deleted documents
225 1585 tao
        Vector deleteList = new Vector(message.getDeletesVect());
226 1037 tao
        //System.out.println("d: " + d.toString());
227 1585 tao
        MetaCatUtil.debugMessage("Update vector size: "+ updateList.size(), 40);
228
        MetaCatUtil.debugMessage("Delete vector size: "+ deleteList.size(),40);
229
        // go though every element in updated document vector
230
        for(int j=0; j<updateList.size(); j++)
231 577 berkley
        {
232 1037 tao
          //initial dataFile is false
233
          dataFile=false;
234
          //w is information for one document, information contain
235
          //docid, rev, server or datafile.
236 1585 tao
          Vector w = new Vector((Vector)(updateList.elementAt(j)));
237 1037 tao
          //Check if the vector w contain "datafile"
238
          //If it has, this document is data file
239
          if (w.contains((String)util.getOption("datafileflag")))
240
          {
241
            dataFile=true;
242
          }
243 577 berkley
          //System.out.println("w: " + w.toString());
244 1292 tao
          // Get docid
245 577 berkley
          String docid = (String)w.elementAt(0);
246 1071 tao
          MetaCatUtil.debugMessage("docid: " + docid, 40);
247 1292 tao
          // Get revision number
248 577 berkley
          int rev = Integer.parseInt((String)w.elementAt(1));
249 1071 tao
          MetaCatUtil.debugMessage("rev: " + rev, 40);
250 1292 tao
          // Get remote server name (it is may not be doc homeserver because
251
          // the new hub feature
252
          String remoteServer = (String)w.elementAt(2);
253 1071 tao
254 1585 tao
255
          // compare the update rev and local rev to see what need happen
256
          int localrev = -1;
257
          try
258
          {
259
            localrev = DocumentImpl.getLatestRevisionNumber(docid);
260
          }
261
          catch (SQLException e)
262
          {
263
            MetaCatUtil.debugMessage("Local rev for docid "+ docid + " could not "+
264
                                   " be found because " + e.getMessage(), 45);
265
            MetacatReplication.replErrorLog("Docid "+ docid + " could not be "+
266
                    "written because error happend to find it's local revision");
267
            continue;
268
          }
269
          MetaCatUtil.debugMessage("Local rev for docid "+ docid + " is "+
270
                                  localrev, 45);
271
272
          //check the revs for an update because this document is in the
273
          //local DB, it might be out of date.
274
          if (localrev == -1)
275
          {
276
            //insert this document as new because it is not in the local DB
277
            action = "INSERT";
278
            flag = true;
279
          }
280
          else
281
          {
282 577 berkley
            if(localrev == rev)
283
            {
284 1292 tao
              // Local meatacat has the same rev to remote host, don't need
285
              // update and flag set false
286 577 berkley
              flag = false;
287
            }
288
            else if(localrev < rev)
289 1585 tao
            {
290
              //this document needs to be updated so send an read request
291 577 berkley
              action = "UPDATE";
292
              flag = true;
293
            }
294
          }
295 1585 tao
296 1037 tao
          // this is non-data file
297
          if(flag && !dataFile)
298 1585 tao
          {
299 625 berkley
            try
300
            {
301 1585 tao
              handleSingleXMLDocument(remoteServer, action, docid);
302 625 berkley
            }
303
            catch(Exception e)
304
            {
305 1585 tao
              // skip this document
306
              continue;
307 625 berkley
            }
308 1037 tao
          }//if for non-data file
309
310 1292 tao
           // this is for data file
311
          if(flag && dataFile)
312 1037 tao
          {
313
            try
314
            {
315 1585 tao
              handleSingleDataFile(remoteServer, action, docid);
316
            }
317 1037 tao
            catch(Exception e)
318
            {
319 1585 tao
              // skip this datafile
320
              continue;
321
            }
322
323 1037 tao
          }//for datafile
324
        }//for update docs
325 577 berkley
326 1037 tao
        //handle deleted docs
327 1585 tao
        for(int k=0; k<deleteList.size(); k++)
328 577 berkley
        { //delete the deleted documents;
329 1585 tao
          Vector w = new Vector((Vector)deleteList.elementAt(k));
330
          String docId = (String)w.elementAt(0);
331
          try
332 579 berkley
          {
333 1585 tao
            handleDeleteSingleDocument(docId);
334 579 berkley
          }
335 1585 tao
          catch (Exception ee)
336
          {
337
            continue;
338
          }
339 1037 tao
        }//for delete docs
340 1585 tao
    }//for response
341 1292 tao
342 1585 tao
    //updated last_checked
343
    for (int i=0;i<serverList.size(); i++)
344
    {
345
       // Get ReplicationServer object from server list
346
       replServer = serverList.serverAt(i);
347
       try
348
       {
349
         updateLastCheckTimeForSingleServer(replServer);
350
       }
351
       catch(Exception e)
352
       {
353
         continue;
354
       }
355
    }//for
356
357
  }//update
358
359
  /* Handle replicate single xml document*/
360
  private void handleSingleXMLDocument(String remoteserver, String actions,
361
                                       String docId)
362
               throws Exception
363
  {
364
    DBConnection dbConn = null;
365
    int serialNumber = -1;
366
    try
367
    {
368
      // Get DBConnection from pool
369
      dbConn=DBConnectionPool.
370
                  getDBConnection("ReplicationHandler.handleSingleXMLDocument");
371
      serialNumber=dbConn.getCheckOutSerialNumber();
372
      //if the document needs to be updated or inserted, this is executed
373
      URL u = new URL("https://" + remoteserver + "?server="+
374
              util.getLocalReplicationServerName()+"&action=read&docid="+docId);
375
376
      // Get docid content
377
      String newxmldoc = MetacatReplication.getURLContent(u);
378
      // If couldn't get skip it
379
      if ( newxmldoc.indexOf("error")!= -1)
380 1292 tao
      {
381 1585 tao
         throw new Exception(newxmldoc);
382
      }
383
      MetaCatUtil.debugMessage("xml documnet:", 45);
384
      MetaCatUtil.debugMessage(newxmldoc, 45);
385
386
      // Try get the docid info from remote server
387
      DocInfoHandler dih = new DocInfoHandler();
388
      XMLReader docinfoParser = initParser(dih);
389
      URL docinfoUrl = new URL("https://" + remoteserver +
390
                       "?server="+util.getLocalReplicationServerName()+
391
                       "&action=getdocumentinfo&docid="+docId);
392
      MetaCatUtil.debugMessage("Sending message: " +
393
                                                  docinfoUrl.toString(), 45);
394
      String docInfoStr = MetacatReplication.getURLContent(docinfoUrl);
395
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
396
      Hashtable docinfoHash = dih.getDocInfo();
397
      // Get home server of the docid
398
      String docHomeServer = (String)docinfoHash.get("home_server");
399
      MetaCatUtil.debugMessage("doc home server in repl: "+docHomeServer, 45);
400
401
      //docid should include rev number too
402
      String accnum=docId+util.getOption("accNumSeparator")+
403
                                              (String)docinfoHash.get("rev");
404
      MetaCatUtil.debugMessage("docid in repl: "+accnum, 45);
405
      String docType = (String)docinfoHash.get("doctype");
406
      MetaCatUtil.debugMessage("doctype in repl: "+docType, 45);
407
408
      String parserBase = null;
409
      // this for eml2 and we need user eml2 parser
410
      if (docType != null && (docType.trim()).equals(DocumentImpl.EMLNAMESPACE))
411
      {
412
         parserBase = DocumentImpl.EML2;
413
      }
414
      // Write the document into local host
415
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
416
      String newDocid = wrapper.writeReplication(dbConn,
417
                              new StringReader(newxmldoc),
418
                              (String)docinfoHash.get("public_access"),
419
                              null,  /* the dtd text */
420
                              actions,
421
                              accnum,
422
                              (String)docinfoHash.get("user_owner"),
423
                              null, /* null for groups[] */
424
                              docHomeServer,
425
                              remoteserver);
426
      MetaCatUtil.debugMessage("Successfully replicated doc " + accnum, 35);
427
      MetacatReplication.replLog("wrote doc " + accnum + " from " +
428
                                         remoteserver);
429
430
    }//try
431 577 berkley
    catch(Exception e)
432
    {
433 1585 tao
      MetacatReplication.replErrorLog("Failed to write doc " + docId +
434
                                      " into db because " +e.getMessage());
435
      MetaCatUtil.debugMessage("Failed to write doc " + docId +
436
                                      " into db because " +e.getMessage(), 30);
437
      throw e;
438 577 berkley
    }
439 667 berkley
    finally
440
    {
441 1585 tao
       //return DBConnection
442
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
443
    }//finally
444
  }
445
446
447
448
  /* Handle replicate single xml document*/
449
  private void handleSingleDataFile(String remoteserver, String actions,
450
                                    String docId)
451
               throws Exception
452
  {
453
    MetaCatUtil.debugMessage("Try to replicate data file: "+docId, 40);
454
    DBConnection dbConn = null;
455
    int serialNumber = -1;
456
    try
457
    {
458
      // Get DBConnection from pool
459
      dbConn=DBConnectionPool.
460
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
461
      serialNumber=dbConn.getCheckOutSerialNumber();
462
      // Try get docid info from remote server
463
      DocInfoHandler dih = new DocInfoHandler();
464
      XMLReader docinfoParser = initParser(dih);
465
      URL docinfoUrl = new URL("https://" + remoteserver +
466
                  "?server="+util.getLocalReplicationServerName()+
467
                  "&action=getdocumentinfo&docid="+docId);
468
469
      String docInfoStr = MetacatReplication.getURLContent(docinfoUrl);
470
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
471
      Hashtable docinfoHash = dih.getDocInfo();
472
      // Get doicd owner
473
      String user = (String)docinfoHash.get("user_owner");
474
      // Get docid name (such as acl or dataset)
475
      String docName = (String)docinfoHash.get("docname");
476
      // Get doc type (eml public id)
477
      String docType = (String)docinfoHash.get("doctype");
478
      // Get docid home sever. it might be different to remoteserver
479
      // becuause of hub feature
480
      String docHomeServer = (String)docinfoHash.get("home_server");
481
482
      //docid should include rev number too
483
      String accnum=docId+util.getOption("accNumSeparator")+
484
                                              (String)docinfoHash.get("rev");
485
      String datafilePath = util.getOption("datafilepath");
486
      // Get data file content
487
      URL u = new URL("https://" + remoteserver + "?server="+
488
                                        util.getLocalReplicationServerName()+
489
                                            "&action=readdata&docid="+accnum);
490
491
      //register data file into xml_documents table and wite data file
492
      //into file system
493
      if (u.openStream() != null)
494 667 berkley
      {
495 1585 tao
         DocumentImpl.writeDataFileInReplication(u.openStream(),
496
                                                        datafilePath,
497
                                                        docName,docType,
498
                                                        accnum, user,
499
                                                        docHomeServer,
500
                                                        remoteserver);
501
        MetaCatUtil.debugMessage("Successfully to write datafile " + docId, 30);
502
        MetacatReplication.replLog("wrote datafile " + accnum + " from " +
503
                                    remoteserver);
504
      }//if
505
      else
506 1217 tao
      {
507 1585 tao
         throw new Exception("Couldn't open the data file: " + accnum);
508
      }//else
509
510
    }//try
511
    catch(Exception e)
512
    {
513
      MetacatReplication.replErrorLog("Failed to try wrote datafile " + docId +
514
                                      " because " +e.getMessage());
515
      MetaCatUtil.debugMessage("Failed to try wrote datafile " + docId +
516
                                      " because " +e.getMessage(), 30);
517
      throw e;
518
    }
519
    finally
520
    {
521
       //return DBConnection
522
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
523
    }//finally
524
  }
525
526
527
528
  /* Handle delete single document*/
529
  private void handleDeleteSingleDocument(String docId)
530
               throws Exception
531
  {
532
    MetaCatUtil.debugMessage("Try delete doc: "+docId, 40);
533
    DBConnection dbConn = null;
534
    int serialNumber = -1;
535
    try
536
    {
537
      // Get DBConnection from pool
538
      dbConn=DBConnectionPool.
539
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
540
      serialNumber=dbConn.getCheckOutSerialNumber();
541
      if(!alreadyDeleted(docId))
542 1217 tao
      {
543 1585 tao
544
         //because delete method docid should have rev number
545
         //so we just add one for it. This rev number is no sence.
546
         String accnum=docId+util.getOption("accNumSeparator")+"1";
547
         //System.out.println("accnum: "+accnum);
548
         DocumentImpl.delete(accnum, null, null);
549
         MetaCatUtil.debugMessage("Successfully deleted doc " + docId, 30);
550
         MetacatReplication.replLog("Doc " + docId + " deleted");
551
      }
552
553
    }//try
554
    catch(Exception e)
555
    {
556
      MetacatReplication.replErrorLog("Failed to delete doc " + docId +
557
                                      " in db because " +e.getMessage());
558
      MetaCatUtil.debugMessage("Failed to delete doc " + docId +
559
                                 " in db because because " +e.getMessage(), 30);
560
      throw e;
561
    }
562
    finally
563
    {
564
       //return DBConnection
565
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
566 1037 tao
    }//finally
567 1585 tao
  }
568 577 berkley
569 1585 tao
  /* Handle updateLastCheckTimForSingleServer*/
570
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
571
                                                  throws Exception
572 590 berkley
  {
573 1585 tao
    String server = repServer.getServerName();
574 1217 tao
    DBConnection dbConn = null;
575
    int serialNumber = -1;
576
    PreparedStatement pstmt = null;
577 590 berkley
    try
578
    {
579 1585 tao
      // Get DBConnection from pool
580 1217 tao
      dbConn=DBConnectionPool.
581 1585 tao
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
582 1217 tao
      serialNumber=dbConn.getCheckOutSerialNumber();
583 1292 tao
584 1585 tao
      MetaCatUtil.debugMessage("Try to update last_check for server: "+server, 40);
585
      // Get time from remote server
586
      URL dateurl = new URL("https://" + server + "?server="+
587
      util.getLocalReplicationServerName()+"&action=gettime");
588
      String datexml = MetacatReplication.getURLContent(dateurl);
589
      MetaCatUtil.debugMessage("datexml: "+datexml, 45);
590
      if (datexml!=null && !datexml.equals(""))
591
      {
592
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
593
         StringBuffer sql = new StringBuffer();
594
         sql.append("update xml_replication set last_checked = to_date('");
595
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
596
         sql.append("server like '").append(server).append("'");
597
         //System.out.println("sql: " + sql.toString());
598
         pstmt = dbConn.prepareStatement(sql.toString());
599
         pstmt.executeUpdate();
600
         dbConn.commit();
601
         pstmt.close();
602
         MetaCatUtil.debugMessage("last_checked updated to "+datestr+" on "
603
                                      + server, 45);
604
      }//if
605
      else
606
      {
607
608
         MetaCatUtil.debugMessage("Failed to update last_checked for server "  +
609
                                  server + " in db because couldn't get time "
610
                                  , 30);
611
         throw new Exception("Couldn't get time for server "+ server);
612
      }
613
614
    }//try
615
    catch(Exception e)
616
    {
617
618
      MetaCatUtil.debugMessage("Failed to update last_checked for server " +
619
                                server + " in db because because " +
620
                                e.getMessage(), 30);
621
      throw e;
622
    }
623
    finally
624
    {
625
       //return DBConnection
626
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
627
    }//finally
628
  }
629
630
631
632
  /**
633
   * updates xml_catalog with entries from other servers.
634
   */
635
  private void updateCatalog()
636
  {
637
    MetaCatUtil.debugMessage("Start of updateCatalog", 35 );
638
    // ReplicationServer object in server list
639
    ReplicationServer replServer = null;
640
    PreparedStatement pstmt = null;
641
    String server = null;
642
643
644
    // Go through each ReplicationServer object in sererlist
645
    for (int j=0; j<serverList.size(); j++)
646
    {
647
      Vector remoteCatalog = new Vector();
648
      Vector publicId = new Vector();
649
      try
650
      {
651 1292 tao
        // Get ReplicationServer object from server list
652
        replServer = serverList.serverAt(j);
653
        // Get server name from the ReplicationServer object
654
        server = replServer.getServerName();
655
        // Try to get catalog
656 1011 tao
        URL u = new URL("https://" + server + "?server="+
657 1015 tao
        util.getLocalReplicationServerName()+"&action=getcatalog");
658 1292 tao
        MetaCatUtil.debugMessage("sending message " + u.toString(), 50);
659 590 berkley
        String catxml = MetacatReplication.getURLContent(u);
660 1292 tao
661
        // Make sure there are not error, no empty string
662
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
663
        {
664 1585 tao
          throw new Exception("Couldn't get catalog list form server " +server);
665 1292 tao
        }
666 1585 tao
        MetaCatUtil.debugMessage("catxml: " + catxml, 40);
667 590 berkley
        CatalogMessageHandler cmh = new CatalogMessageHandler();
668
        XMLReader catparser = initParser(cmh);
669
        catparser.parse(new InputSource(new StringReader(catxml)));
670
        //parse the returned catalog xml and put it into a vector
671 1585 tao
        remoteCatalog = cmh.getCatalogVect();
672 590 berkley
673 1292 tao
        // Makse sure remoteCatalog is not empty
674
        if (remoteCatalog.isEmpty())
675
        {
676 1585 tao
          throw new Exception("Couldn't get catalog list form server " +server);
677 1292 tao
        }
678
679 590 berkley
        String localcatxml = MetacatReplication.getCatalogXML();
680 1292 tao
681
        // Make sure local catalog is no empty
682
        if (localcatxml==null||localcatxml.equals(""))
683
        {
684 1585 tao
          throw new Exception("Couldn't get catalog list form server " +server);
685 1292 tao
        }
686
687 590 berkley
        cmh = new CatalogMessageHandler();
688
        catparser = initParser(cmh);
689
        catparser.parse(new InputSource(new StringReader(localcatxml)));
690
        Vector localCatalog = cmh.getCatalogVect();
691
692
        //now we have the catalog from the remote server and this local server
693
        //we now need to compare the two and merge the differences.
694
        //the comparison is base on the public_id fields which is the 4th
695
        //entry in each row vector.
696 1585 tao
        publicId = new Vector();
697 590 berkley
        for(int i=0; i<localCatalog.size(); i++)
698
        {
699
          Vector v = new Vector((Vector)localCatalog.elementAt(i));
700 1292 tao
          MetaCatUtil.debugMessage("v1: " + v.toString(), 50);
701 590 berkley
          publicId.add(new String((String)v.elementAt(3)));
702 595 berkley
          //System.out.println("adding " + (String)v.elementAt(3));
703 590 berkley
        }
704 1585 tao
      }//try
705
      catch (Exception e)
706
      {
707
        MetacatReplication.replErrorLog("Failed to update catalog for server "+
708
                                    server + " because " +e.getMessage());
709
        MetaCatUtil.debugMessage("Failed to update catalog for server "+
710
                                    server + " because " +e.getMessage(), 30);
711
      }//catch
712
713
      for(int i=0; i<remoteCatalog.size(); i++)
714
      {
715
         // DConnection
716
        DBConnection dbConn = null;
717
        // DBConnection checkout serial number
718
        int serialNumber = -1;
719
        try
720 590 berkley
        {
721 1585 tao
            dbConn=DBConnectionPool.
722
                  getDBConnection("ReplicationHandler.updateCatalog");
723
            serialNumber=dbConn.getCheckOutSerialNumber();
724
            Vector v = (Vector)remoteCatalog.elementAt(i);
725
            //System.out.println("v2: " + v.toString());
726
            //System.out.println("i: " + i);
727
            //System.out.println("remoteCatalog.size(): " + remoteCatalog.size());
728
            //System.out.println("publicID: " + publicId.toString());
729
            MetaCatUtil.debugMessage
730 1292 tao
                              ("v.elementAt(3): " + (String)v.elementAt(3), 50);
731 1585 tao
           if(!publicId.contains(v.elementAt(3)))
732
           { //so we don't have this public id in our local table so we need to
733
             //add it.
734
             //System.out.println("in if");
735
             StringBuffer sql = new StringBuffer();
736
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
737
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
738
             sql.append("?,?)");
739
             //System.out.println("sql: " + sql.toString());
740
             pstmt = dbConn.prepareStatement(sql.toString());
741
             pstmt.setString(1, (String)v.elementAt(0));
742
             pstmt.setString(2, (String)v.elementAt(1));
743
             pstmt.setString(3, (String)v.elementAt(2));
744
             pstmt.setString(4, (String)v.elementAt(3));
745
             pstmt.setString(5, (String)v.elementAt(4));
746
             pstmt.execute();
747
             pstmt.close();
748
             MetacatReplication.replLog("Success fully to insert new publicid "+
749
                               (String)v.elementAt(3) + " from server"+server);
750
             MetaCatUtil.debugMessage("Success fully to insert new publicid "+
751
                             (String)v.elementAt(3) + " from server" +server, 30);
752
           }
753 590 berkley
        }
754 1585 tao
        catch(Exception e)
755
        {
756
           MetacatReplication.replErrorLog("Failed to update catalog for server "+
757
                                    server + " because " +e.getMessage());
758
           MetaCatUtil.debugMessage("Failed to update catalog for server "+
759
                                    server + " because " +e.getMessage(), 30);
760
        }//catch
761
        finally
762
        {
763
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
764
        }//finall
765
      }//for remote catalog
766
    }//for server list
767
    MetaCatUtil.debugMessage("End of updateCatalog", 35);
768 590 berkley
  }
769
770
  /**
771 579 berkley
   * Method that returns true if docid has already been "deleted" from metacat.
772 582 berkley
   * This method really implements a truth table for deleted documents
773 590 berkley
   * The table is (a docid in one of the tables is represented by the X):
774 582 berkley
   * xml_docs      xml_revs      deleted?
775
   * ------------------------------------
776
   *   X             X             FALSE
777
   *   X             _             FALSE
778
   *   _             X             TRUE
779
   *   _             _             TRUE
780 579 berkley
   */
781 1585 tao
  private static boolean alreadyDeleted(String docid) throws Exception
782 579 berkley
  {
783 1217 tao
    DBConnection dbConn = null;
784
    int serialNumber = -1;
785
    PreparedStatement pstmt = null;
786 579 berkley
    try
787
    {
788 1217 tao
      dbConn=DBConnectionPool.
789
                  getDBConnection("ReplicationHandler.alreadyDeleted");
790
      serialNumber=dbConn.getCheckOutSerialNumber();
791 582 berkley
      boolean xml_docs = false;
792
      boolean xml_revs = false;
793
794 579 berkley
      StringBuffer sb = new StringBuffer();
795 582 berkley
      sb.append("select docid from xml_revisions where docid like '");
796 579 berkley
      sb.append(docid).append("'");
797 1217 tao
      pstmt = dbConn.prepareStatement(sb.toString());
798 579 berkley
      pstmt.execute();
799
      ResultSet rs = pstmt.getResultSet();
800
      boolean tablehasrows = rs.next();
801
      if(tablehasrows)
802
      {
803 582 berkley
        xml_revs = true;
804
      }
805
806
      sb = new StringBuffer();
807
      sb.append("select docid from xml_documents where docid like '");
808
      sb.append(docid).append("'");
809 667 berkley
      pstmt.close();
810 1217 tao
      pstmt = dbConn.prepareStatement(sb.toString());
811
      //increase usage count
812
      dbConn.increaseUsageCount(1);
813 582 berkley
      pstmt.execute();
814
      rs = pstmt.getResultSet();
815
      tablehasrows = rs.next();
816 667 berkley
      pstmt.close();
817 582 berkley
      if(tablehasrows)
818
      {
819
        xml_docs = true;
820
      }
821
822
      if(xml_docs && xml_revs)
823
      {
824
        return false;
825
      }
826
      else if(xml_docs && !xml_revs)
827
      {
828
        return false;
829
      }
830
      else if(!xml_docs && xml_revs)
831
      {
832 579 berkley
        return true;
833
      }
834 582 berkley
      else if(!xml_docs && !xml_revs)
835
      {
836
        return true;
837
      }
838 579 berkley
    }
839
    catch(Exception e)
840
    {
841 1585 tao
      MetaCatUtil.debugMessage("error in ReplicationHandler.alreadyDeleted: " +
842
                          e.getMessage(), 30);
843
      throw e;
844 579 berkley
    }
845 667 berkley
    finally
846
    {
847 1217 tao
      try
848
      {
849
        pstmt.close();
850
      }//try
851
      catch (SQLException ee)
852
      {
853
        MetaCatUtil.debugMessage("Error in replicationHandler.alreadyDeleted "+
854
                          "to close pstmt: "+ee.getMessage(), 30);
855 1585 tao
        throw ee;
856 1217 tao
      }//catch
857
      finally
858
      {
859
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
860
      }//finally
861
    }//finally
862 579 berkley
    return false;
863
  }
864 533 berkley
865
866
  /**
867 574 berkley
   * Method to initialize the message parser
868
   */
869
  public static XMLReader initParser(DefaultHandler dh)
870
          throws Exception
871
  {
872
    XMLReader parser = null;
873
874
    try {
875
      ContentHandler chandler = dh;
876
877
      // Get an instance of the parser
878
      MetaCatUtil util = new MetaCatUtil();
879
      String parserName = util.getOption("saxparser");
880
      parser = XMLReaderFactory.createXMLReader(parserName);
881
882
      // Turn off validation
883
      parser.setFeature("http://xml.org/sax/features/validation", false);
884
885
      parser.setContentHandler((ContentHandler)chandler);
886
      parser.setErrorHandler((ErrorHandler)chandler);
887
888
    } catch (Exception e) {
889
      throw e;
890
    }
891
892
    return parser;
893
  }
894 1011 tao
895 1015 tao
896 522 berkley
}