Project

General

Profile

1
/**
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: tao $'
10
 *     '$Date: 2003-04-18 20:33:22 -0700 (Fri, 18 Apr 2003) $'
11
 * '$Revision: 1585 $'
12
 *
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
 */
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
import java.text.*;
36
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
import org.xml.sax.helpers.DefaultHandler;
47

    
48

    
49

    
50
/**
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
  int serverCheckCode = 1;
58
  MetaCatUtil util = new MetaCatUtil();
59
  ReplicationServerList serverList = null; 
60
  PrintWriter out;
61
  
62
  public ReplicationHandler(PrintWriter o)
63
  {
64
    this.out = o;
65
    serverList = new ReplicationServerList();
66
  }
67
  
68
  public ReplicationHandler(PrintWriter o, int serverCheckCode)
69
  {
70
    this.out = o;
71
    this.serverCheckCode = serverCheckCode;
72
    serverList = new ReplicationServerList();
73
  }
74
  
75
  /**
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
      //if serverList is null, metacat don't need to replication
87
      if (serverList==null||serverList.isEmpty())
88
      {
89
        return;
90
      }
91
      updateCatalog();
92
      update();
93
      //conn.close();
94
    }//try
95
    catch (Exception e)
96
    {
97
      MetaCatUtil.debugMessage("Error in replicationHandler.run():"
98
                                                    +e.getMessage(), 30);
99
      e.printStackTrace();
100
    }//catch
101
  }
102
  
103
  /**
104
   * Method that uses revision taging for replication instead of update_date.
105
   */
106
  private void update()
107
  {
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
    
122
    ReplicationServer replServer = null; // Variable to store the 
123
                                        // ReplicationServer got from 
124
                                        // Server list
125
    String server; // Variable to store server name
126
    String update;
127
    ReplMessageHandler message = new ReplMessageHandler();
128
    Vector responses = new Vector();
129
    boolean flag=false; // If a document need to update
130
    boolean dataFile=false;
131
    String action = new String();
132
    XMLReader parser;
133
    URL u;
134
    
135
  
136
    try
137
    {
138
      parser = initParser(message);
139
    }
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
        // Get ReplicationServer object from server list
154
        replServer = serverList.serverAt(i);
155
        // Get server name from ReplicationServer object
156
        server = replServer.getServerName();
157
        String result = null;
158
        MetacatReplication.replLog("full update started to: " + server);
159
        // Send command to that server to get updated docid information
160
        try
161
        {
162
          u = new URL("https://" + server + "?server="
163
          +util.getLocalReplicationServerName()+"&action=update");
164
          MetaCatUtil.debugMessage("Sending infomation " +u.toString(), 50);
165
          result = MetacatReplication.getURLContent(u);
166
        }
167
        catch (Exception e)
168
        {
169
          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
          continue;
174
        }
175
        
176
        MetaCatUtil.debugMessage("docid: "+server+" "+result, 50);
177
        //check if result have error or not, if has skip it.
178
        if (result.indexOf("error")!=-1)
179
        {
180
          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
          continue;
185
        }
186
        //Add result to vector
187
        responses.add(result);
188
    }
189
      
190
    //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
        return;
199
    }
200
     
201
      
202
    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
                     new StringReader(
211
                     (String)(responses.elementAt(i)))));
212
        }
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
        //v is the list of updated documents
222
        Vector updateList = new Vector(message.getUpdatesVect());
223
        //System.out.println("v: " + v.toString());
224
        //d is the list of deleted documents
225
        Vector deleteList = new Vector(message.getDeletesVect());
226
        //System.out.println("d: " + d.toString());
227
        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
        {
232
          //initial dataFile is false
233
          dataFile=false;
234
          //w is information for one document, information contain
235
          //docid, rev, server or datafile.
236
          Vector w = new Vector((Vector)(updateList.elementAt(j)));
237
          //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
          //System.out.println("w: " + w.toString());
244
          // Get docid
245
          String docid = (String)w.elementAt(0);
246
          MetaCatUtil.debugMessage("docid: " + docid, 40);
247
          // Get revision number
248
          int rev = Integer.parseInt((String)w.elementAt(1));
249
          MetaCatUtil.debugMessage("rev: " + rev, 40);
250
          // 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
          
254
          
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
            if(localrev == rev)
283
            {
284
              // Local meatacat has the same rev to remote host, don't need 
285
              // update and flag set false
286
              flag = false;
287
            }
288
            else if(localrev < rev)
289
            {
290
              //this document needs to be updated so send an read request
291
              action = "UPDATE";
292
              flag = true;
293
            }
294
          }
295
    
296
          // this is non-data file
297
          if(flag && !dataFile)
298
          { 
299
            try
300
            {
301
              handleSingleXMLDocument(remoteServer, action, docid);
302
            }
303
            catch(Exception e)
304
            {
305
              // skip this document
306
              continue;
307
            }
308
          }//if for non-data file
309
          
310
           // this is for data file
311
          if(flag && dataFile)
312
          { 
313
            try
314
            {
315
              handleSingleDataFile(remoteServer, action, docid);
316
            }
317
            catch(Exception e)
318
            {
319
              // skip this datafile
320
              continue;
321
            }
322
         
323
          }//for datafile
324
        }//for update docs
325
        
326
        //handle deleted docs
327
        for(int k=0; k<deleteList.size(); k++)
328
        { //delete the deleted documents;
329
          Vector w = new Vector((Vector)deleteList.elementAt(k));
330
          String docId = (String)w.elementAt(0);
331
          try
332
          {
333
            handleDeleteSingleDocument(docId);
334
          }
335
          catch (Exception ee)
336
          {
337
            continue;
338
          }
339
        }//for delete docs
340
    }//for response
341
      
342
    //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
      {
381
         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
    catch(Exception e)
432
    {
433
      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
    }
439
    finally
440
    {
441
       //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
      {
495
         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
      {
507
         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
      {
543
          
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
    }//finally
567
  }
568
  
569
  /* Handle updateLastCheckTimForSingleServer*/
570
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer) 
571
                                                  throws Exception
572
  {
573
    String server = repServer.getServerName();
574
    DBConnection dbConn = null;
575
    int serialNumber = -1;
576
    PreparedStatement pstmt = null;
577
    try
578
    {
579
      // Get DBConnection from pool
580
      dbConn=DBConnectionPool.
581
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
582
      serialNumber=dbConn.getCheckOutSerialNumber();
583
      
584
      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
        // 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
        URL u = new URL("https://" + server + "?server="+
657
        util.getLocalReplicationServerName()+"&action=getcatalog");
658
        MetaCatUtil.debugMessage("sending message " + u.toString(), 50);
659
        String catxml = MetacatReplication.getURLContent(u);
660
        
661
        // Make sure there are not error, no empty string
662
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
663
        {
664
          throw new Exception("Couldn't get catalog list form server " +server);
665
        }
666
        MetaCatUtil.debugMessage("catxml: " + catxml, 40);
667
        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
        remoteCatalog = cmh.getCatalogVect();
672
        
673
        // Makse sure remoteCatalog is not empty
674
        if (remoteCatalog.isEmpty())
675
        {
676
          throw new Exception("Couldn't get catalog list form server " +server);
677
        }
678
        
679
        String localcatxml = MetacatReplication.getCatalogXML();
680
        
681
        // Make sure local catalog is no empty
682
        if (localcatxml==null||localcatxml.equals(""))
683
        {
684
          throw new Exception("Couldn't get catalog list form server " +server);
685
        }
686
        
687
        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
        publicId = new Vector();
697
        for(int i=0; i<localCatalog.size(); i++)
698
        {
699
          Vector v = new Vector((Vector)localCatalog.elementAt(i));
700
          MetaCatUtil.debugMessage("v1: " + v.toString(), 50);
701
          publicId.add(new String((String)v.elementAt(3)));
702
          //System.out.println("adding " + (String)v.elementAt(3));
703
        }
704
      }//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
        {
721
            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
                              ("v.elementAt(3): " + (String)v.elementAt(3), 50);
731
           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
        }
754
        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
  }
769
  
770
  /**
771
   * Method that returns true if docid has already been "deleted" from metacat.
772
   * This method really implements a truth table for deleted documents
773
   * The table is (a docid in one of the tables is represented by the X):
774
   * xml_docs      xml_revs      deleted?
775
   * ------------------------------------
776
   *   X             X             FALSE
777
   *   X             _             FALSE
778
   *   _             X             TRUE
779
   *   _             _             TRUE
780
   */
781
  private static boolean alreadyDeleted(String docid) throws Exception
782
  {
783
    DBConnection dbConn = null;
784
    int serialNumber = -1;
785
    PreparedStatement pstmt = null;
786
    try
787
    {
788
      dbConn=DBConnectionPool.
789
                  getDBConnection("ReplicationHandler.alreadyDeleted");
790
      serialNumber=dbConn.getCheckOutSerialNumber();
791
      boolean xml_docs = false;
792
      boolean xml_revs = false;
793
      
794
      StringBuffer sb = new StringBuffer();
795
      sb.append("select docid from xml_revisions where docid like '");
796
      sb.append(docid).append("'");
797
      pstmt = dbConn.prepareStatement(sb.toString());
798
      pstmt.execute();
799
      ResultSet rs = pstmt.getResultSet();
800
      boolean tablehasrows = rs.next();
801
      if(tablehasrows)
802
      {
803
        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
      pstmt.close();
810
      pstmt = dbConn.prepareStatement(sb.toString());
811
      //increase usage count
812
      dbConn.increaseUsageCount(1);
813
      pstmt.execute();
814
      rs = pstmt.getResultSet();
815
      tablehasrows = rs.next();
816
      pstmt.close();
817
      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
        return true;
833
      }
834
      else if(!xml_docs && !xml_revs)
835
      {
836
        return true;
837
      }
838
    }
839
    catch(Exception e)
840
    {
841
      MetaCatUtil.debugMessage("error in ReplicationHandler.alreadyDeleted: " + 
842
                          e.getMessage(), 30);
843
      throw e;
844
    }
845
    finally
846
    {
847
      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
        throw ee;
856
      }//catch
857
      finally
858
      {
859
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
860
      }//finally
861
    }//finally
862
    return false;
863
  }
864

    
865
  
866
  /**
867
   * 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
  
895
 
896
}
897
   
(52-52/57)