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-07-25 08:13:51 -0700 (Fri, 25 Jul 2003) $'
11
 * '$Revision: 1757 $'
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 edu.ucsb.nceas.dbadapter.AbstractDatabase;
31
import java.sql.*;
32
import java.util.*;
33
import java.lang.Thread; 
34
import java.io.*;
35
import java.net.*;
36
import java.text.*;
37
import org.xml.sax.AttributeList;
38
import org.xml.sax.ContentHandler;
39
import org.xml.sax.DTDHandler;
40
import org.xml.sax.EntityResolver;
41
import org.xml.sax.ErrorHandler;
42
import org.xml.sax.InputSource;
43
import org.xml.sax.XMLReader;
44
import org.xml.sax.SAXException;
45
import org.xml.sax.SAXParseException;
46
import org.xml.sax.helpers.XMLReaderFactory;
47
import org.xml.sax.helpers.DefaultHandler;
48

    
49

    
50

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

    
881
  
882
  /**
883
   * Method to initialize the message parser
884
   */
885
  public static XMLReader initParser(DefaultHandler dh)
886
          throws Exception
887
  {
888
    XMLReader parser = null;
889

    
890
    try {
891
      ContentHandler chandler = dh;
892

    
893
      // Get an instance of the parser
894
      MetaCatUtil util = new MetaCatUtil();
895
      String parserName = util.getOption("saxparser");
896
      parser = XMLReaderFactory.createXMLReader(parserName);
897

    
898
      // Turn off validation
899
      parser.setFeature("http://xml.org/sax/features/validation", false);
900
      
901
      parser.setContentHandler((ContentHandler)chandler);
902
      parser.setErrorHandler((ErrorHandler)chandler);
903

    
904
    } catch (Exception e) {
905
      throw e;
906
    }
907

    
908
    return parser;
909
  }
910
  
911
 
912
}
913
   
(53-53/58)