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: 2005-09-30 12:48:59 -0700 (Fri, 30 Sep 2005) $'
11
 * '$Revision: 2608 $'
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.util.Date;
34
import java.lang.Thread;
35
import java.io.*;
36
import java.net.*;
37
import java.text.*;
38
import org.xml.sax.AttributeList;
39
import org.xml.sax.ContentHandler;
40
import org.xml.sax.DTDHandler;
41
import org.xml.sax.EntityResolver;
42
import org.xml.sax.ErrorHandler;
43
import org.xml.sax.InputSource;
44
import org.xml.sax.XMLReader;
45
import org.xml.sax.SAXException;
46
import org.xml.sax.SAXParseException;
47
import org.xml.sax.helpers.XMLReaderFactory;
48
import org.xml.sax.helpers.DefaultHandler;
49

    
50

    
51

    
52
/**
53
 * This class handles deltaT replication checking.  Whenever this TimerTask
54
 * is fired it checks each server in xml_replication for updates and updates
55
 * the local db as needed.
56
 */
57
public class ReplicationHandler extends TimerTask
58
{
59
  int serverCheckCode = 1;
60
  MetaCatUtil util = new MetaCatUtil();
61
  ReplicationServerList serverList = null;
62
  //PrintWriter out;
63
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
64

    
65
 
66
  
67
  public ReplicationHandler()
68
  {
69
    //this.out = o;
70
    serverList = new ReplicationServerList();
71
  }
72

    
73
  public ReplicationHandler(int serverCheckCode)
74
  {
75
    //this.out = o;
76
    this.serverCheckCode = serverCheckCode;
77
    serverList = new ReplicationServerList();
78
  }
79

    
80
  /**
81
   * Method that implements TimerTask.run().  It runs whenever the timer is
82
   * fired.
83
   */
84
  public void run()
85
  {
86
    //find out the last_checked time of each server in the server list and
87
    //send a query to each server to see if there are any documents in
88
    //xml_documents with an update_date > last_checked
89
    try
90
    {
91
      //if serverList is null, metacat don't need to replication
92
      if (serverList==null||serverList.isEmpty())
93
      {
94
        return;
95
      }
96
      updateCatalog();
97
      update();
98
      //conn.close();
99
    }//try
100
    catch (Exception e)
101
    {
102
      MetaCatUtil.debugMessage("Error in replicationHandler.run():"
103
                                                    +e.getMessage(), 30);
104
      e.printStackTrace();
105
    }//catch
106
  }
107

    
108
  /**
109
   * Method that uses revision taging for replication instead of update_date.
110
   */
111
  private void update()
112
  {
113
    /*
114
     Pseudo-algorithm
115
     - request a doc list from each server in xml_replication
116
     - check the rev number of each of those documents agains the
117
       documents in the local database
118
     - pull any documents that have a lesser rev number on the local server
119
       from the remote server
120
     - delete any documents that still exist in the local xml_documents but
121
       are in the deletedDocuments tag of the remote host response.
122
     - update last_checked to keep track of the last time it was checked.
123
       (this info is theoretically not needed using this system but probably
124
       should be kept anyway)
125
    */
126

    
127
    ReplicationServer replServer = null; // Variable to store the
128
                                        // ReplicationServer got from
129
                                        // Server list
130
    String server = null; // Variable to store server name
131
    String update;
132
    ReplMessageHandler message = new ReplMessageHandler();
133
    Vector responses = new Vector();
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().trim();
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
        handleDocList(updateList, DocumentImpl.DOCUMENTTABLE);
233
        //handle deleted docs
234
        for(int k=0; k<deleteList.size(); k++)
235
        { //delete the deleted documents;
236
          Vector w = new Vector((Vector)deleteList.elementAt(k));
237
          String docId = (String)w.elementAt(0);
238
          try
239
          {
240
            handleDeleteSingleDocument(docId, server);
241
          }
242
          catch (Exception ee)
243
          {
244
            continue;
245
          }
246
        }//for delete docs
247
        
248
        // handle replicate doc in xml_revision
249
        Vector revisionList = new Vector(message.getRevisionsVect());
250
        handleDocList(revisionList, DocumentImpl.REVISIONTABLE);
251
    }//for response
252

    
253
    //updated last_checked
254
    for (int i=0;i<serverList.size(); i++)
255
    {
256
       // Get ReplicationServer object from server list
257
       replServer = serverList.serverAt(i);
258
       try
259
       {
260
         updateLastCheckTimeForSingleServer(replServer);
261
       }
262
       catch(Exception e)
263
       {
264
         continue;
265
       }
266
    }//for
267

    
268
  }//update
269

    
270
  /* Handle replicate single xml document*/
271
  private void handleSingleXMLDocument(String remoteserver, String actions,
272
                                       String docId, String tableName)
273
               throws Exception
274
  {
275
    DBConnection dbConn = null;
276
    int serialNumber = -1;
277
    try
278
    {
279
      // Get DBConnection from pool
280
      dbConn=DBConnectionPool.
281
                  getDBConnection("ReplicationHandler.handleSingleXMLDocument");
282
      serialNumber=dbConn.getCheckOutSerialNumber();
283
      //if the document needs to be updated or inserted, this is executed
284
      String readDocURLString = "https://" + remoteserver + "?server="+
285
              util.getLocalReplicationServerName()+"&action=read&docid="+docId;
286
      readDocURLString = MetaCatUtil.replaceWhiteSpaceForURL(readDocURLString);
287
      URL u = new URL(readDocURLString);
288

    
289
      // Get docid content
290
      String newxmldoc = MetacatReplication.getURLContent(u);
291
      // If couldn't get skip it
292
      if ( newxmldoc.indexOf("<error>")!= -1 && newxmldoc.indexOf("</error>")!=-1)
293
      {
294
         throw new Exception(newxmldoc);
295
      }
296
      MetaCatUtil.debugMessage("xml documnet:", 45);
297
      MetaCatUtil.debugMessage(newxmldoc, 45);
298

    
299
      // Try get the docid info from remote server
300
      DocInfoHandler dih = new DocInfoHandler();
301
      XMLReader docinfoParser = initParser(dih);
302
      String docInfoURLStr = "https://" + remoteserver +
303
                       "?server="+util.getLocalReplicationServerName()+
304
                       "&action=getdocumentinfo&docid="+docId;
305
      docInfoURLStr = MetaCatUtil.replaceWhiteSpaceForURL(docInfoURLStr);
306
      URL docinfoUrl = new URL(docInfoURLStr);
307
      MetaCatUtil.debugMessage("Sending message: " +
308
                                                  docinfoUrl.toString(), 45);
309
      String docInfoStr = MetacatReplication.getURLContent(docinfoUrl);
310
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
311
      Hashtable docinfoHash = dih.getDocInfo();
312
      // Get home server of the docid
313
      String docHomeServer = (String)docinfoHash.get("home_server");
314
      MetaCatUtil.debugMessage("doc home server in repl: "+docHomeServer, 45);
315

    
316
      //docid should include rev number too
317
      String accnum=docId+util.getOption("accNumSeparator")+
318
                                              (String)docinfoHash.get("rev");
319
      MetaCatUtil.debugMessage("docid in repl: "+accnum, 45);
320
      String docType = (String)docinfoHash.get("doctype");
321
      MetaCatUtil.debugMessage("doctype in repl: "+docType, 45);
322

    
323
      String parserBase = null;
324
      // this for eml2 and we need user eml2 parser
325
      if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
326
      {
327
         parserBase = DocumentImpl.EML200;
328
      }
329
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
330
      {
331
        parserBase = DocumentImpl.EML200;
332
      }
333
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
334
      {
335
        parserBase = DocumentImpl.EML210;
336
      }
337
      // Write the document into local host
338
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
339
      String newDocid = wrapper.writeReplication(dbConn,
340
                              new StringReader(newxmldoc),
341
                              (String)docinfoHash.get("public_access"),
342
                              null,  /* the dtd text */
343
                              actions,
344
                              accnum,
345
                              (String)docinfoHash.get("user_owner"),
346
                              null, /* null for groups[] */
347
                              docHomeServer,
348
                              remoteserver, tableName, true);// true is for time replication
349
      MetaCatUtil.debugMessage("Successfully replicated doc " + accnum, 35);
350
      MetacatReplication.replLog("wrote doc " + accnum + " from " +
351
                                         remoteserver);
352

    
353
    }//try
354
    catch(Exception e)
355
    {
356
      MetacatReplication.replErrorLog("Failed to write doc " + docId +
357
                                      " into db because " +e.getMessage());
358
      MetaCatUtil.debugMessage("Failed to write doc " + docId +
359
                                      " into db because " +e.getMessage(), 30);
360
      throw e;
361
    }
362
    finally
363
    {
364
       //return DBConnection
365
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
366
    }//finally
367
  }
368

    
369

    
370

    
371
  /* Handle replicate single xml document*/
372
  private void handleSingleDataFile(String remoteserver, String actions,
373
                                    String docId, String tableName)
374
               throws Exception
375
  {
376
    MetaCatUtil.debugMessage("Try to replicate data file: "+docId, 40);
377
    DBConnection dbConn = null;
378
    int serialNumber = -1;
379
    try
380
    {
381
      // Get DBConnection from pool
382
      dbConn=DBConnectionPool.
383
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
384
      serialNumber=dbConn.getCheckOutSerialNumber();
385
      // Try get docid info from remote server
386
      DocInfoHandler dih = new DocInfoHandler();
387
      XMLReader docinfoParser = initParser(dih);
388
      String docInfoURLString = "https://" + remoteserver +
389
                  "?server="+util.getLocalReplicationServerName()+
390
                  "&action=getdocumentinfo&docid="+docId;
391
      docInfoURLString = MetaCatUtil.replaceWhiteSpaceForURL(docInfoURLString);
392
      URL docinfoUrl = new URL(docInfoURLString);
393

    
394
      String docInfoStr = MetacatReplication.getURLContent(docinfoUrl);
395
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
396
      Hashtable docinfoHash = dih.getDocInfo();
397
      // Get doicd owner
398
      String user = (String)docinfoHash.get("user_owner");
399
      // Get docid name (such as acl or dataset)
400
      String docName = (String)docinfoHash.get("docname");
401
      // Get doc type (eml public id)
402
      String docType = (String)docinfoHash.get("doctype");
403
      // Get docid home sever. it might be different to remoteserver
404
      // becuause of hub feature
405
      String docHomeServer = (String)docinfoHash.get("home_server");
406

    
407
      //docid should include rev number too
408
      String accnum=docId+util.getOption("accNumSeparator")+
409
                                              (String)docinfoHash.get("rev");
410

    
411

    
412
      String datafilePath = util.getOption("datafilepath");
413
      // Get data file content
414
      String readDataURLString = "https://" + remoteserver + "?server="+
415
                                        util.getLocalReplicationServerName()+
416
                                            "&action=readdata&docid="+accnum;
417
      readDataURLString = MetaCatUtil.replaceWhiteSpaceForURL(readDataURLString);
418
      URL u = new URL(readDataURLString);
419
      InputStream input = u.openStream();
420
      //register data file into xml_documents table and wite data file
421
      //into file system
422
      if ( input != null)
423
      {
424
        DocumentImpl.writeDataFileInReplication(input,
425
                                                datafilePath,
426
                                                docName,docType,
427
                                                accnum, user,
428
                                                docHomeServer,
429
                                                remoteserver,
430
                                                tableName,
431
                                                true);//true means timed replication
432
        MetaCatUtil.debugMessage("Successfully to write datafile " + docId, 30);
433
        MetacatReplication.replLog("wrote datafile " + accnum + " from " +
434
                                    remoteserver);
435
      }//if
436
      else
437
      {
438
         MetaCatUtil.debugMessage("Couldn't open the data file: " + accnum, 30);
439
         throw new Exception("Couldn't open the data file: " + accnum);
440
      }//else
441

    
442
    }//try
443
    catch(Exception e)
444
    {
445
      MetacatReplication.replErrorLog("Failed to try wrote datafile " + docId +
446
                                      " because " +e.getMessage());
447
      MetaCatUtil.debugMessage("Failed to try wrote datafile " + docId +
448
                                      " because " +e.getMessage(), 30);
449
      throw e;
450
    }
451
    finally
452
    {
453
       //return DBConnection
454
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
455
    }//finally
456
  }
457

    
458

    
459

    
460
  /* Handle delete single document*/
461
  private void handleDeleteSingleDocument(String docId, String notifyServer)
462
               throws Exception
463
  {
464
    MetaCatUtil.debugMessage("Try delete doc: "+docId, 40);
465
    DBConnection dbConn = null;
466
    int serialNumber = -1;
467
    try
468
    {
469
      // Get DBConnection from pool
470
      dbConn=DBConnectionPool.
471
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
472
      serialNumber=dbConn.getCheckOutSerialNumber();
473
      if(!alreadyDeleted(docId))
474
      {
475

    
476
         //because delete method docid should have rev number
477
         //so we just add one for it. This rev number is no sence.
478
         String accnum=docId+util.getOption("accNumSeparator")+"1";
479
         //System.out.println("accnum: "+accnum);
480
         DocumentImpl.delete(accnum, null, null, notifyServer);
481
         MetaCatUtil.debugMessage("Successfully deleted doc " + docId, 30);
482
         MetacatReplication.replLog("Doc " + docId + " deleted");
483
      }
484

    
485
    }//try
486
    catch(Exception e)
487
    {
488
      MetacatReplication.replErrorLog("Failed to delete doc " + docId +
489
                                      " in db because " +e.getMessage());
490
      MetaCatUtil.debugMessage("Failed to delete doc " + docId +
491
                                 " in db because because " +e.getMessage(), 30);
492
      throw e;
493
    }
494
    finally
495
    {
496
       //return DBConnection
497
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
498
    }//finally
499
  }
500

    
501
  /* Handle updateLastCheckTimForSingleServer*/
502
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
503
                                                  throws Exception
504
  {
505
    String server = repServer.getServerName();
506
    DBConnection dbConn = null;
507
    int serialNumber = -1;
508
    PreparedStatement pstmt = null;
509
    try
510
    {
511
      // Get DBConnection from pool
512
      dbConn=DBConnectionPool.
513
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
514
      serialNumber=dbConn.getCheckOutSerialNumber();
515

    
516
      MetaCatUtil.debugMessage("Try to update last_check for server: "+server, 40);
517
      // Get time from remote server
518
      URL dateurl = new URL("https://" + server + "?server="+
519
      util.getLocalReplicationServerName()+"&action=gettime");
520
      String datexml = MetacatReplication.getURLContent(dateurl);
521
      MetaCatUtil.debugMessage("datexml: "+datexml, 45);
522
      if (datexml!=null && !datexml.equals(""))
523
      {
524
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
525
         StringBuffer sql = new StringBuffer();
526
         /*sql.append("update xml_replication set last_checked = to_date('");
527
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
528
         sql.append("server like '").append(server).append("'");*/
529
         sql.append("update xml_replication set last_checked = ");
530
         sql.append(dbAdapter.toDate(datestr, "MM/DD/YY HH24:MI:SS"));
531
         sql.append(" where server like '").append(server).append("'");
532
         pstmt = dbConn.prepareStatement(sql.toString());
533

    
534
         pstmt.executeUpdate();
535
         dbConn.commit();
536
         pstmt.close();
537
         MetaCatUtil.debugMessage("last_checked updated to "+datestr+" on "
538
                                      + server, 45);
539
      }//if
540
      else
541
      {
542

    
543
         MetaCatUtil.debugMessage("Failed to update last_checked for server "  +
544
                                  server + " in db because couldn't get time "
545
                                  , 30);
546
         throw new Exception("Couldn't get time for server "+ server);
547
      }
548

    
549
    }//try
550
    catch(Exception e)
551
    {
552

    
553
      MetaCatUtil.debugMessage("Failed to update last_checked for server " +
554
                                server + " in db because because " +
555
                                e.getMessage(), 30);
556
      throw e;
557
    }
558
    finally
559
    {
560
       //return DBConnection
561
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
562
    }//finally
563
  }
564

    
565

    
566

    
567
  /**
568
   * updates xml_catalog with entries from other servers.
569
   */
570
  private void updateCatalog()
571
  {
572
    MetaCatUtil.debugMessage("Start of updateCatalog", 35 );
573
    // ReplicationServer object in server list
574
    ReplicationServer replServer = null;
575
    PreparedStatement pstmt = null;
576
    String server = null;
577

    
578

    
579
    // Go through each ReplicationServer object in sererlist
580
    for (int j=0; j<serverList.size(); j++)
581
    {
582
      Vector remoteCatalog = new Vector();
583
      Vector publicId = new Vector();
584
      try
585
      {
586
        // Get ReplicationServer object from server list
587
        replServer = serverList.serverAt(j);
588
        // Get server name from the ReplicationServer object
589
        server = replServer.getServerName();
590
        // Try to get catalog
591
        URL u = new URL("https://" + server + "?server="+
592
        util.getLocalReplicationServerName()+"&action=getcatalog");
593
        MetaCatUtil.debugMessage("sending message " + u.toString(), 50);
594
        String catxml = MetacatReplication.getURLContent(u);
595

    
596
        // Make sure there are not error, no empty string
597
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
598
        {
599
          throw new Exception("Couldn't get catalog list form server " +server);
600
        }
601
        MetaCatUtil.debugMessage("catxml: " + catxml, 40);
602
        CatalogMessageHandler cmh = new CatalogMessageHandler();
603
        XMLReader catparser = initParser(cmh);
604
        catparser.parse(new InputSource(new StringReader(catxml)));
605
        //parse the returned catalog xml and put it into a vector
606
        remoteCatalog = cmh.getCatalogVect();
607

    
608
        // Makse sure remoteCatalog is not empty
609
        if (remoteCatalog.isEmpty())
610
        {
611
          throw new Exception("Couldn't get catalog list form server " +server);
612
        }
613

    
614
        String localcatxml = MetacatReplication.getCatalogXML();
615

    
616
        // Make sure local catalog is no empty
617
        if (localcatxml==null||localcatxml.equals(""))
618
        {
619
          throw new Exception("Couldn't get catalog list form server " +server);
620
        }
621

    
622
        cmh = new CatalogMessageHandler();
623
        catparser = initParser(cmh);
624
        catparser.parse(new InputSource(new StringReader(localcatxml)));
625
        Vector localCatalog = cmh.getCatalogVect();
626

    
627
        //now we have the catalog from the remote server and this local server
628
        //we now need to compare the two and merge the differences.
629
        //the comparison is base on the public_id fields which is the 4th
630
        //entry in each row vector.
631
        publicId = new Vector();
632
        for(int i=0; i<localCatalog.size(); i++)
633
        {
634
          Vector v = new Vector((Vector)localCatalog.elementAt(i));
635
          MetaCatUtil.debugMessage("v1: " + v.toString(), 50);
636
          publicId.add(new String((String)v.elementAt(3)));
637
          //System.out.println("adding " + (String)v.elementAt(3));
638
        }
639
      }//try
640
      catch (Exception e)
641
      {
642
        MetacatReplication.replErrorLog("Failed to update catalog for server "+
643
                                    server + " because " +e.getMessage());
644
        MetaCatUtil.debugMessage("Failed to update catalog for server "+
645
                                    server + " because " +e.getMessage(), 30);
646
      }//catch
647

    
648
      for(int i=0; i<remoteCatalog.size(); i++)
649
      {
650
         // DConnection
651
        DBConnection dbConn = null;
652
        // DBConnection checkout serial number
653
        int serialNumber = -1;
654
        try
655
        {
656
            dbConn=DBConnectionPool.
657
                  getDBConnection("ReplicationHandler.updateCatalog");
658
            serialNumber=dbConn.getCheckOutSerialNumber();
659
            Vector v = (Vector)remoteCatalog.elementAt(i);
660
            //System.out.println("v2: " + v.toString());
661
            //System.out.println("i: " + i);
662
            //System.out.println("remoteCatalog.size(): " + remoteCatalog.size());
663
            //System.out.println("publicID: " + publicId.toString());
664
            MetaCatUtil.debugMessage
665
                              ("v.elementAt(3): " + (String)v.elementAt(3), 50);
666
           if(!publicId.contains(v.elementAt(3)))
667
           { //so we don't have this public id in our local table so we need to
668
             //add it.
669
             //System.out.println("in if");
670
             StringBuffer sql = new StringBuffer();
671
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
672
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
673
             sql.append("?,?)");
674
             //System.out.println("sql: " + sql.toString());
675
             pstmt = dbConn.prepareStatement(sql.toString());
676
             pstmt.setString(1, (String)v.elementAt(0));
677
             pstmt.setString(2, (String)v.elementAt(1));
678
             pstmt.setString(3, (String)v.elementAt(2));
679
             pstmt.setString(4, (String)v.elementAt(3));
680
             pstmt.setString(5, (String)v.elementAt(4));
681
             pstmt.execute();
682
             pstmt.close();
683
             MetacatReplication.replLog("Success fully to insert new publicid "+
684
                               (String)v.elementAt(3) + " from server"+server);
685
             MetaCatUtil.debugMessage("Success fully to insert new publicid "+
686
                             (String)v.elementAt(3) + " from server" +server, 30);
687
           }
688
        }
689
        catch(Exception e)
690
        {
691
           MetacatReplication.replErrorLog("Failed to update catalog for server "+
692
                                    server + " because " +e.getMessage());
693
           MetaCatUtil.debugMessage("Failed to update catalog for server "+
694
                                    server + " because " +e.getMessage(), 30);
695
        }//catch
696
        finally
697
        {
698
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
699
        }//finall
700
      }//for remote catalog
701
    }//for server list
702
    MetaCatUtil.debugMessage("End of updateCatalog", 35);
703
  }
704

    
705
  /**
706
   * Method that returns true if docid has already been "deleted" from metacat.
707
   * This method really implements a truth table for deleted documents
708
   * The table is (a docid in one of the tables is represented by the X):
709
   * xml_docs      xml_revs      deleted?
710
   * ------------------------------------
711
   *   X             X             FALSE
712
   *   X             _             FALSE
713
   *   _             X             TRUE
714
   *   _             _             TRUE
715
   */
716
  private static boolean alreadyDeleted(String docid) throws Exception
717
  {
718
    DBConnection dbConn = null;
719
    int serialNumber = -1;
720
    PreparedStatement pstmt = null;
721
    try
722
    {
723
      dbConn=DBConnectionPool.
724
                  getDBConnection("ReplicationHandler.alreadyDeleted");
725
      serialNumber=dbConn.getCheckOutSerialNumber();
726
      boolean xml_docs = false;
727
      boolean xml_revs = false;
728

    
729
      StringBuffer sb = new StringBuffer();
730
      sb.append("select docid from xml_revisions where docid like '");
731
      sb.append(docid).append("'");
732
      pstmt = dbConn.prepareStatement(sb.toString());
733
      pstmt.execute();
734
      ResultSet rs = pstmt.getResultSet();
735
      boolean tablehasrows = rs.next();
736
      if(tablehasrows)
737
      {
738
        xml_revs = true;
739
      }
740

    
741
      sb = new StringBuffer();
742
      sb.append("select docid from xml_documents where docid like '");
743
      sb.append(docid).append("'");
744
      pstmt.close();
745
      pstmt = dbConn.prepareStatement(sb.toString());
746
      //increase usage count
747
      dbConn.increaseUsageCount(1);
748
      pstmt.execute();
749
      rs = pstmt.getResultSet();
750
      tablehasrows = rs.next();
751
      pstmt.close();
752
      if(tablehasrows)
753
      {
754
        xml_docs = true;
755
      }
756

    
757
      if(xml_docs && xml_revs)
758
      {
759
        return false;
760
      }
761
      else if(xml_docs && !xml_revs)
762
      {
763
        return false;
764
      }
765
      else if(!xml_docs && xml_revs)
766
      {
767
        return true;
768
      }
769
      else if(!xml_docs && !xml_revs)
770
      {
771
        return true;
772
      }
773
    }
774
    catch(Exception e)
775
    {
776
      MetaCatUtil.debugMessage("error in ReplicationHandler.alreadyDeleted: " +
777
                          e.getMessage(), 30);
778
      throw e;
779
    }
780
    finally
781
    {
782
      try
783
      {
784
        pstmt.close();
785
      }//try
786
      catch (SQLException ee)
787
      {
788
        MetaCatUtil.debugMessage("Error in replicationHandler.alreadyDeleted "+
789
                          "to close pstmt: "+ee.getMessage(), 30);
790
        throw ee;
791
      }//catch
792
      finally
793
      {
794
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
795
      }//finally
796
    }//finally
797
    return false;
798
  }
799

    
800

    
801
  /**
802
   * Method to initialize the message parser
803
   */
804
  public static XMLReader initParser(DefaultHandler dh)
805
          throws Exception
806
  {
807
    XMLReader parser = null;
808

    
809
    try {
810
      ContentHandler chandler = dh;
811

    
812
      // Get an instance of the parser
813
      MetaCatUtil util = new MetaCatUtil();
814
      String parserName = util.getOption("saxparser");
815
      parser = XMLReaderFactory.createXMLReader(parserName);
816

    
817
      // Turn off validation
818
      parser.setFeature("http://xml.org/sax/features/validation", false);
819

    
820
      parser.setContentHandler((ContentHandler)chandler);
821
      parser.setErrorHandler((ErrorHandler)chandler);
822

    
823
    } catch (Exception e) {
824
      throw e;
825
    }
826

    
827
    return parser;
828
  }
829

    
830
  /**
831
   * This method will combinate given time string(in short format) to
832
   * current date. If the given time (e.g 10:00 AM) passed the current time
833
   * (e.g 2:00 PM Aug 21, 2005), then the time will set to second day,
834
   * 10:00 AM Aug 22, 2005. If the given time (e.g 10:00 AM) haven't passed
835
   * the current time (e.g 8:00 AM Aug 21, 2005) The time will set to be
836
   * 10:00 AM Aug 21, 2005.
837
   * @param givenTime  the format should be "10:00 AM " or "2:00 PM"
838
   * @return
839
   * @throws Exception
840
   */
841
  public static Date combinateCurrentDateAndGivenTime(String givenTime) throws Exception
842
  {
843
     Date givenDate = parseTime(givenTime);
844
     Date newDate = null;
845
     Date now = new Date();
846
     String currentTimeString = getTimeString(now);
847
     Date currentTime = parseTime(currentTimeString); 
848
     if ( currentTime.getTime() >= givenDate.getTime())
849
     {
850
        MetaCatUtil.debugMessage("Today already pass the given time, we should set it as tomorrow", 30);
851
        String dateAndTime = getDateString(now) + " " + givenTime;
852
        Date combinationDate = parseDateTime(dateAndTime);
853
        // new date should plus 24 hours to make is the second day
854
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
855
     }
856
     else
857
     {
858
         MetaCatUtil.debugMessage("Today haven't pass the given time, we should it as today", 2);
859
         String dateAndTime = getDateString(now) + " " + givenTime;
860
         newDate = parseDateTime(dateAndTime);
861
     }
862
     MetaCatUtil.debugMessage("final setting time is "+ newDate.toString(), 20);
863
     return newDate;
864
  }
865

    
866
  /*
867
   * parse a given string to Time in short format.
868
   * For example, given time is 10:00 AM, the date will be return as
869
   * Jan 1 1970, 10:00 AM
870
   */
871
  private static Date parseTime(String timeString) throws Exception
872
  {
873
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
874
    Date time = format.parse(timeString); 
875
    System.out.println("Date string is after parse a time string "+time.toString());
876
    return time;
877

    
878
  }
879
  
880
  /*
881
   * Pasre a given string to date and time. Date format is long and time
882
   * format is short.
883
   */
884
  private static Date parseDateTime(String timeString) throws Exception
885
  {
886
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
887
    Date time = format.parse(timeString);
888
    System.out.println("Date string is after parse a time string "+time.toString());
889
    return time;
890
  }
891
  
892
  /*
893
   * Get a date string from a Date object. The date format will be long
894
   */
895
  private static String getDateString(Date now)
896
  {
897
     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
898
     String s = df.format(now);
899
     System.out.println("Today is " + s);
900
     return s;
901
  }
902
  
903
  /*
904
   * Get a time string from a Date object, the time format will be short
905
   */
906
  private static String getTimeString(Date now)
907
  {
908
     DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
909
     String s = df.format(now);
910
     System.out.println("Time is " + s);
911
     return s;
912
  }
913
  
914
  
915
  /*
916
   * This method will go through the docid list both in xml_Documents table
917
   * and in xml_revisions table
918
   * @author tao
919
   */
920
   private void handleDocList(Vector docList, String tableName)
921
   {
922
       boolean dataFile=false;
923
       for(int j=0; j<docList.size(); j++)
924
       {
925
         //initial dataFile is false
926
         dataFile=false;
927
         //w is information for one document, information contain
928
         //docid, rev, server or datafile.
929
         Vector w = new Vector((Vector)(docList.elementAt(j)));
930
         //Check if the vector w contain "datafile"
931
         //If it has, this document is data file
932
         if (w.contains((String)util.getOption("datafileflag")))
933
         {
934
           dataFile=true;
935
         }
936
         //System.out.println("w: " + w.toString());
937
         // Get docid
938
         String docid = (String)w.elementAt(0);
939
         MetaCatUtil.debugMessage("docid: " + docid, 40);
940
         // Get revision number
941
         int rev = Integer.parseInt((String)w.elementAt(1));
942
         MetaCatUtil.debugMessage("rev: " + rev, 40);
943
         // Get remote server name (it is may not be doc homeserver because
944
         // the new hub feature
945
         String remoteServer = (String)w.elementAt(2);
946
         remoteServer = remoteServer.trim();
947

    
948
         try
949
         {
950
             if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
951
             {
952
                 handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
953
             }
954
             else if (tableName.equals(DocumentImpl.REVISIONTABLE))
955
             {
956
                 handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
957
             }
958
             else
959
             {
960
                 continue;
961
             }
962
                 
963
         }
964
         catch (Exception e)
965
         {
966
             MetaCatUtil.debugMessage("error to handle update doc in "+ 
967
                     tableName +" in time replication"+e.getMessage(), 30);
968
             continue;
969
         }
970
        
971
       }//for update docs
972

    
973
   }
974
   
975
   /*
976
    * This method will handle doc in xml_documents table.
977
    */
978
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
979
                                        throws Exception
980
   {
981
       // compare the update rev and local rev to see what need happen
982
       int localrev = -1;
983
       String action = null;
984
       boolean flag = false;
985
       try
986
       {
987
         localrev = DocumentImpl.getLatestRevisionNumber(docid);
988
       }
989
       catch (SQLException e)
990
       {
991
         MetaCatUtil.debugMessage("Local rev for docid "+ docid + " could not "+
992
                                " be found because " + e.getMessage(), 45);
993
         MetacatReplication.replErrorLog("Docid "+ docid + " could not be "+
994
                 "written because error happend to find it's local revision");
995
         throw new Exception (e.getMessage());
996
       }
997
       MetaCatUtil.debugMessage("Local rev for docid "+ docid + " is "+
998
                               localrev, 45);
999

    
1000
       //check the revs for an update because this document is in the
1001
       //local DB, it might be out of date.
1002
       if (localrev == -1)
1003
       {
1004
         //insert this document as new because it is not in the local DB
1005
         action = "INSERT";
1006
         flag = true;
1007
       }
1008
       else
1009
       {
1010
         if(localrev == rev)
1011
         {
1012
           // Local meatacat has the same rev to remote host, don't need
1013
           // update and flag set false
1014
           flag = false;
1015
         }
1016
         else if(localrev < rev)
1017
         {
1018
           //this document needs to be updated so send an read request
1019
           action = "UPDATE";
1020
           flag = true;
1021
         }
1022
       }
1023

    
1024
       // this is non-data file
1025
       if(flag && !dataFile)
1026
       {
1027
         try
1028
         {
1029
           handleSingleXMLDocument(remoteServer, action, docid, DocumentImpl.DOCUMENTTABLE);
1030
         }
1031
         catch(Exception e)
1032
         {
1033
           // skip this document
1034
           throw e;
1035
         }
1036
       }//if for non-data file
1037

    
1038
        // this is for data file
1039
       if(flag && dataFile)
1040
       {
1041
         try
1042
         {
1043
           handleSingleDataFile(remoteServer, action, docid, DocumentImpl.DOCUMENTTABLE);
1044
         }
1045
         catch(Exception e)
1046
         {
1047
           // skip this datafile
1048
           throw e;
1049
         }
1050

    
1051
       }//for datafile
1052
   }
1053
   
1054
   /*
1055
    * This method will handle doc in xml_documents table.
1056
    */
1057
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile) 
1058
                                        throws Exception
1059
   {
1060
       // compare the update rev and local rev to see what need happen
1061
       Vector localrev = null;
1062
       String action = "INSERT";
1063
       boolean flag = false;
1064
       try
1065
       {
1066
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1067
       }
1068
       catch (SQLException e)
1069
       {
1070
         MetaCatUtil.debugMessage("Local rev for docid "+ docid + " could not "+
1071
                                " be found because " + e.getMessage(), 45);
1072
         MetacatReplication.replErrorLog("Docid "+ docid + " could not be "+
1073
                 "written because error happend to find it's local revision");
1074
         throw new Exception (e.getMessage());
1075
       }
1076
       MetaCatUtil.debugMessage("rev list in xml_revision table for docid "+ docid + " is "+
1077
                               localrev.toString(), 45);
1078
       
1079
       // if the rev is not in the xml_revision, we need insert it
1080
       if (!localrev.contains(new Integer(rev)))
1081
       {
1082
           flag = true;    
1083
       }
1084

    
1085
       // this is non-data file
1086
       if(flag && !dataFile)
1087
       {
1088
         try
1089
         {
1090
           handleSingleXMLDocument(remoteServer, action, docid, DocumentImpl.REVISIONTABLE);
1091
         }
1092
         catch(Exception e)
1093
         {
1094
           // skip this document
1095
           throw e;
1096
         }
1097
       }//if for non-data file
1098

    
1099
        // this is for data file
1100
       if(flag && dataFile)
1101
       {
1102
         try
1103
         {
1104
           handleSingleDataFile(remoteServer, action, docid, DocumentImpl.REVISIONTABLE);
1105
         }
1106
         catch(Exception e)
1107
         {
1108
           // skip this datafile
1109
           throw e;
1110
         }
1111

    
1112
       }//for datafile
1113
   }
1114
  
1115
}
1116

    
(58-58/64)