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-23 12:04:13 -0700 (Wed, 23 Jul 2003) $'
11
 * '$Revision: 1751 $'
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, "YY-MM-DD HH24:MI:SS"));
612
         sql.append(" where server like '").append(server).append("'");
613
         pstmt = dbConn.prepareStatement(sql.toString());
614
         MetaCatUtil.debugMessage("6, new sql for todate:================== "+
615
                                   sql.toString(), 1);
616
         pstmt.executeUpdate();
617
         dbConn.commit();
618
         pstmt.close();
619
         MetaCatUtil.debugMessage("last_checked updated to "+datestr+" on " 
620
                                      + server, 45);
621
      }//if
622
      else
623
      {
624
         
625
         MetaCatUtil.debugMessage("Failed to update last_checked for server "  + 
626
                                  server + " in db because couldn't get time " 
627
                                  , 30);
628
         throw new Exception("Couldn't get time for server "+ server);
629
      }
630
   
631
    }//try      
632
    catch(Exception e)
633
    {
634
      
635
      MetaCatUtil.debugMessage("Failed to update last_checked for server " + 
636
                                server + " in db because because " +
637
                                e.getMessage(), 30);
638
      throw e;
639
    }
640
    finally
641
    {
642
       //return DBConnection
643
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
644
    }//finally
645
  }
646
  
647
  
648
  
649
  /**
650
   * updates xml_catalog with entries from other servers.
651
   */
652
  private void updateCatalog()
653
  {
654
    MetaCatUtil.debugMessage("Start of updateCatalog", 35 );
655
    // ReplicationServer object in server list
656
    ReplicationServer replServer = null;
657
    PreparedStatement pstmt = null;
658
    String server = null;
659
    
660
      
661
    // Go through each ReplicationServer object in sererlist
662
    for (int j=0; j<serverList.size(); j++)
663
    { 
664
      Vector remoteCatalog = new Vector();
665
      Vector publicId = new Vector();
666
      try
667
      {
668
        // Get ReplicationServer object from server list
669
        replServer = serverList.serverAt(j);
670
        // Get server name from the ReplicationServer object
671
        server = replServer.getServerName();
672
        // Try to get catalog
673
        URL u = new URL("https://" + server + "?server="+
674
        util.getLocalReplicationServerName()+"&action=getcatalog");
675
        MetaCatUtil.debugMessage("sending message " + u.toString(), 50);
676
        String catxml = MetacatReplication.getURLContent(u);
677
        
678
        // Make sure there are not error, no empty string
679
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
680
        {
681
          throw new Exception("Couldn't get catalog list form server " +server);
682
        }
683
        MetaCatUtil.debugMessage("catxml: " + catxml, 40);
684
        CatalogMessageHandler cmh = new CatalogMessageHandler();
685
        XMLReader catparser = initParser(cmh);
686
        catparser.parse(new InputSource(new StringReader(catxml)));
687
        //parse the returned catalog xml and put it into a vector
688
        remoteCatalog = cmh.getCatalogVect();
689
        
690
        // Makse sure remoteCatalog is not empty
691
        if (remoteCatalog.isEmpty())
692
        {
693
          throw new Exception("Couldn't get catalog list form server " +server);
694
        }
695
        
696
        String localcatxml = MetacatReplication.getCatalogXML();
697
        
698
        // Make sure local catalog is no empty
699
        if (localcatxml==null||localcatxml.equals(""))
700
        {
701
          throw new Exception("Couldn't get catalog list form server " +server);
702
        }
703
        
704
        cmh = new CatalogMessageHandler();
705
        catparser = initParser(cmh);
706
        catparser.parse(new InputSource(new StringReader(localcatxml)));
707
        Vector localCatalog = cmh.getCatalogVect();
708
        
709
        //now we have the catalog from the remote server and this local server
710
        //we now need to compare the two and merge the differences.
711
        //the comparison is base on the public_id fields which is the 4th
712
        //entry in each row vector.
713
        publicId = new Vector();
714
        for(int i=0; i<localCatalog.size(); i++)
715
        {
716
          Vector v = new Vector((Vector)localCatalog.elementAt(i));
717
          MetaCatUtil.debugMessage("v1: " + v.toString(), 50);
718
          publicId.add(new String((String)v.elementAt(3)));
719
          //System.out.println("adding " + (String)v.elementAt(3));
720
        }
721
      }//try
722
      catch (Exception e)
723
      {
724
        MetacatReplication.replErrorLog("Failed to update catalog for server "+
725
                                    server + " because " +e.getMessage());
726
        MetaCatUtil.debugMessage("Failed to update catalog for server "+
727
                                    server + " because " +e.getMessage(), 30);
728
      }//catch
729
      
730
      for(int i=0; i<remoteCatalog.size(); i++)
731
      {
732
         // DConnection
733
        DBConnection dbConn = null;
734
        // DBConnection checkout serial number
735
        int serialNumber = -1;
736
        try
737
        {
738
            dbConn=DBConnectionPool.
739
                  getDBConnection("ReplicationHandler.updateCatalog");
740
            serialNumber=dbConn.getCheckOutSerialNumber();
741
            Vector v = (Vector)remoteCatalog.elementAt(i);
742
            //System.out.println("v2: " + v.toString());
743
            //System.out.println("i: " + i);
744
            //System.out.println("remoteCatalog.size(): " + remoteCatalog.size());
745
            //System.out.println("publicID: " + publicId.toString());
746
            MetaCatUtil.debugMessage
747
                              ("v.elementAt(3): " + (String)v.elementAt(3), 50);
748
           if(!publicId.contains(v.elementAt(3)))
749
           { //so we don't have this public id in our local table so we need to
750
             //add it.
751
             //System.out.println("in if");
752
             StringBuffer sql = new StringBuffer();
753
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
754
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
755
             sql.append("?,?)");
756
             //System.out.println("sql: " + sql.toString());
757
             pstmt = dbConn.prepareStatement(sql.toString());
758
             pstmt.setString(1, (String)v.elementAt(0));
759
             pstmt.setString(2, (String)v.elementAt(1));
760
             pstmt.setString(3, (String)v.elementAt(2));
761
             pstmt.setString(4, (String)v.elementAt(3));
762
             pstmt.setString(5, (String)v.elementAt(4));
763
             pstmt.execute();
764
             pstmt.close();
765
             MetacatReplication.replLog("Success fully to insert new publicid "+
766
                               (String)v.elementAt(3) + " from server"+server);
767
             MetaCatUtil.debugMessage("Success fully to insert new publicid "+
768
                             (String)v.elementAt(3) + " from server" +server, 30);
769
           }
770
        }
771
        catch(Exception e)
772
        {
773
           MetacatReplication.replErrorLog("Failed to update catalog for server "+
774
                                    server + " because " +e.getMessage());
775
           MetaCatUtil.debugMessage("Failed to update catalog for server "+
776
                                    server + " because " +e.getMessage(), 30);
777
        }//catch
778
        finally
779
        {
780
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
781
        }//finall
782
      }//for remote catalog
783
    }//for server list
784
    MetaCatUtil.debugMessage("End of updateCatalog", 35);
785
  }
786
  
787
  /**
788
   * Method that returns true if docid has already been "deleted" from metacat.
789
   * This method really implements a truth table for deleted documents
790
   * The table is (a docid in one of the tables is represented by the X):
791
   * xml_docs      xml_revs      deleted?
792
   * ------------------------------------
793
   *   X             X             FALSE
794
   *   X             _             FALSE
795
   *   _             X             TRUE
796
   *   _             _             TRUE
797
   */
798
  private static boolean alreadyDeleted(String docid) throws Exception
799
  {
800
    DBConnection dbConn = null;
801
    int serialNumber = -1;
802
    PreparedStatement pstmt = null;
803
    try
804
    {
805
      dbConn=DBConnectionPool.
806
                  getDBConnection("ReplicationHandler.alreadyDeleted");
807
      serialNumber=dbConn.getCheckOutSerialNumber();
808
      boolean xml_docs = false;
809
      boolean xml_revs = false;
810
      
811
      StringBuffer sb = new StringBuffer();
812
      sb.append("select docid from xml_revisions where docid like '");
813
      sb.append(docid).append("'");
814
      pstmt = dbConn.prepareStatement(sb.toString());
815
      pstmt.execute();
816
      ResultSet rs = pstmt.getResultSet();
817
      boolean tablehasrows = rs.next();
818
      if(tablehasrows)
819
      {
820
        xml_revs = true;
821
      }
822
      
823
      sb = new StringBuffer();
824
      sb.append("select docid from xml_documents where docid like '");
825
      sb.append(docid).append("'");
826
      pstmt.close();
827
      pstmt = dbConn.prepareStatement(sb.toString());
828
      //increase usage count
829
      dbConn.increaseUsageCount(1);
830
      pstmt.execute();
831
      rs = pstmt.getResultSet();
832
      tablehasrows = rs.next();
833
      pstmt.close();
834
      if(tablehasrows)
835
      {
836
        xml_docs = true;
837
      }
838
      
839
      if(xml_docs && xml_revs)
840
      {
841
        return false;
842
      }
843
      else if(xml_docs && !xml_revs)
844
      {
845
        return false;
846
      }
847
      else if(!xml_docs && xml_revs)
848
      {
849
        return true;
850
      }
851
      else if(!xml_docs && !xml_revs)
852
      {
853
        return true;
854
      }
855
    }
856
    catch(Exception e)
857
    {
858
      MetaCatUtil.debugMessage("error in ReplicationHandler.alreadyDeleted: " + 
859
                          e.getMessage(), 30);
860
      throw e;
861
    }
862
    finally
863
    {
864
      try
865
      {
866
        pstmt.close();
867
      }//try
868
      catch (SQLException ee)
869
      {
870
        MetaCatUtil.debugMessage("Error in replicationHandler.alreadyDeleted "+
871
                          "to close pstmt: "+ee.getMessage(), 30);
872
        throw ee;
873
      }//catch
874
      finally
875
      {
876
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
877
      }//finally
878
    }//finally
879
    return false;
880
  }
881

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

    
891
    try {
892
      ContentHandler chandler = dh;
893

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

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

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

    
909
    return parser;
910
  }
911
  
912
 
913
}
914
   
(52-52/57)