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
 *
8
 *   '$Author: jones $'
9
 *     '$Date: 2006-11-10 10:25:38 -0800 (Fri, 10 Nov 2006) $'
10
 * '$Revision: 3077 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacat;
28

    
29
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
30
import java.sql.*;
31
import java.util.*;
32
import java.util.Date;
33
import java.lang.Thread;
34
import java.io.*;
35
import java.net.*;
36
import java.text.*;
37

    
38
import org.apache.log4j.Logger;
39
import org.xml.sax.AttributeList;
40
import org.xml.sax.ContentHandler;
41
import org.xml.sax.DTDHandler;
42
import org.xml.sax.EntityResolver;
43
import org.xml.sax.ErrorHandler;
44
import org.xml.sax.InputSource;
45
import org.xml.sax.XMLReader;
46
import org.xml.sax.SAXException;
47
import org.xml.sax.SAXParseException;
48
import org.xml.sax.helpers.XMLReaderFactory;
49
import org.xml.sax.helpers.DefaultHandler;
50

    
51

    
52

    
53
/**
54
 * This class handles deltaT replication checking.  Whenever this TimerTask
55
 * is fired it checks each server in xml_replication for updates and updates
56
 * the local db as needed.
57
 */
58
public class ReplicationHandler extends TimerTask
59
{
60
  int serverCheckCode = 1;
61
  MetaCatUtil util = new MetaCatUtil();
62
  ReplicationServerList serverList = null;
63
  //PrintWriter out;
64
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
65
  private static Logger logMetacat = Logger.getLogger(ReplicationHandler.class);
66
  private static int DOCINSERTNUMBER = 1;
67
  private static int DOCERRORNUMBER  = 1;
68
  private static int REVINSERTNUMBER = 1;
69
  private static int REVERRORNUMBER  = 1;
70
  public ReplicationHandler()
71
  {
72
    //this.out = o;
73
    serverList = new ReplicationServerList();
74
  }
75

    
76
  public ReplicationHandler(int serverCheckCode)
77
  {
78
    //this.out = o;
79
    this.serverCheckCode = serverCheckCode;
80
    serverList = new ReplicationServerList();
81
  }
82

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

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

    
130
    ReplicationServer replServer = null; // Variable to store the
131
                                        // ReplicationServer got from
132
                                        // Server list
133
    String server = null; // Variable to store server name
134
    String update;
135
    ReplMessageHandler message = new ReplMessageHandler();
136
    Vector responses = new Vector();
137
    XMLReader parser;
138
    URL u;
139

    
140

    
141
    try
142
    {
143
      parser = initParser(message);
144
    }
145
    catch (Exception e)
146
    {
147
      MetacatReplication.replErrorLog("Failed to replicate becaue couldn't "+
148
                                 " initParser for message and" +e.getMessage());
149
      logMetacat.error("Failed to replicate becaue couldn't " +
150
                            " initParser for message and " +e.getMessage());
151
       // stop replication
152
       return;
153
    }
154
    //Check for every server in server list to get updated list and put
155
    // them in to response
156
    for (int i=0; i<serverList.size(); i++)
157
    {
158
        // Get ReplicationServer object from server list
159
        replServer = serverList.serverAt(i);
160
        // Get server name from ReplicationServer object
161
        server = replServer.getServerName().trim();
162
        String result = null;
163
        MetacatReplication.replLog("full update started to: " + server);
164
        // Send command to that server to get updated docid information
165
        try
166
        {
167
          u = new URL("https://" + server + "?server="
168
          +util.getLocalReplicationServerName()+"&action=update");
169
          logMetacat.info("Sending infomation " +u.toString());
170
          result = MetacatReplication.getURLContent(u);
171
        }
172
        catch (Exception e)
173
        {
174
          MetacatReplication.replErrorLog("Failed to get updated doc list "+
175
                          "for server " + server + " because "+e.getMessage());
176
          logMetacat.error( "Failed to get updated doc list "+
177
                       "for server " + server + " because "+e.getMessage());
178
          continue;
179
        }
180

    
181
        logMetacat.info("docid: "+server+" "+result);
182
        //check if result have error or not, if has skip it.
183
        if (result.indexOf("<error>")!=-1 && result.indexOf("</error>")!=-1)
184
        {
185
          MetacatReplication.replErrorLog("Failed to get updated doc list "+
186
                          "for server " + server + " because "+result);
187
          logMetacat.info( "Failed to get updated doc list "+
188
                       "for server " + server + " because "+result);
189
          continue;
190
        }
191
        //Add result to vector
192
        responses.add(result);
193
    }
194

    
195
    //make sure that there is updated file list
196
    //If response is null, metacat don't need do anything
197
    if (responses==null || responses.isEmpty())
198
    {
199
        MetacatReplication.replErrorLog("No updated doc list for "+
200
                           "every server and failed to replicate");
201
        logMetacat.info( "No updated doc list for "+
202
                           "every server and failed to replicate");
203
        return;
204
    }
205

    
206

    
207
    logMetacat.info("Responses from remote metacat about updated "+
208
                   "document information: "+ responses.toString());
209
    // go through response vector(it contains updated vector and delete vector
210
    for(int i=0; i<responses.size(); i++)
211
    {
212
        try
213
        {
214
          parser.parse(new InputSource(
215
                     new StringReader(
216
                     (String)(responses.elementAt(i)))));
217
        }
218
        catch(Exception e)
219
        {
220
          MetacatReplication.replErrorLog("Couldn't parse one responses "+
221
                           "because "+ e.getMessage());
222
          logMetacat.error("Couldn't parse one responses "+
223
                                   "because "+ e.getMessage());
224
          continue;
225
        }
226
        //v is the list of updated documents
227
        Vector updateList = new Vector(message.getUpdatesVect());
228
        MetacatReplication.replLog("The document list size is "+updateList.size());
229
        //System.out.println("v: " + v.toString());
230
        //d is the list of deleted documents
231
        Vector deleteList = new Vector(message.getDeletesVect());
232
        //System.out.println("d: " + d.toString());
233
        logMetacat.info("Update vector size: "+ updateList.size());
234
        logMetacat.info("Delete vector size: "+ deleteList.size());
235
        MetacatReplication.replLog("The delete document list size is "+deleteList.size());
236
        // go though every element in updated document vector
237
        handleDocList(updateList, DocumentImpl.DOCUMENTTABLE);
238
        //handle deleted docs
239
        for(int k=0; k<deleteList.size(); k++)
240
        { //delete the deleted documents;
241
          Vector w = new Vector((Vector)deleteList.elementAt(k));
242
          String docId = (String)w.elementAt(0);
243
          try
244
          {
245
            handleDeleteSingleDocument(docId, server);
246
          }
247
          catch (Exception ee)
248
          {
249
            continue;
250
          }
251
        }//for delete docs
252
        
253
        // handle replicate doc in xml_revision
254
        Vector revisionList = new Vector(message.getRevisionsVect());
255
        MetacatReplication.replLog("The revision document list size is "+revisionList.size());
256
        handleDocList(revisionList, DocumentImpl.REVISIONTABLE);
257
        DOCINSERTNUMBER = 1;
258
        DOCERRORNUMBER  = 1;
259
        REVINSERTNUMBER = 1;
260
        REVERRORNUMBER  = 1;
261
    }//for response
262

    
263
    //updated last_checked
264
    for (int i=0;i<serverList.size(); i++)
265
    {
266
       // Get ReplicationServer object from server list
267
       replServer = serverList.serverAt(i);
268
       try
269
       {
270
         updateLastCheckTimeForSingleServer(replServer);
271
       }
272
       catch(Exception e)
273
       {
274
         continue;
275
       }
276
    }//for
277

    
278
  }//update
279

    
280
  /* Handle replicate single xml document*/
281
  private void handleSingleXMLDocument(String remoteserver, String actions,
282
                                       String accNumber, String tableName)
283
               throws Exception
284
  {
285
    DBConnection dbConn = null;
286
    int serialNumber = -1;
287
    try
288
    {
289
      // Get DBConnection from pool
290
      dbConn=DBConnectionPool.
291
                  getDBConnection("ReplicationHandler.handleSingleXMLDocument");
292
      serialNumber=dbConn.getCheckOutSerialNumber();
293
      //if the document needs to be updated or inserted, this is executed
294
      String readDocURLString = "https://" + remoteserver + "?server="+
295
              util.getLocalReplicationServerName()+"&action=read&docid="+accNumber;
296
      readDocURLString = MetaCatUtil.replaceWhiteSpaceForURL(readDocURLString);
297
      URL u = new URL(readDocURLString);
298

    
299
      // Get docid content
300
      String newxmldoc = MetacatReplication.getURLContent(u);
301
      // If couldn't get skip it
302
      if ( newxmldoc.indexOf("<error>")!= -1 && newxmldoc.indexOf("</error>")!=-1)
303
      {
304
         throw new Exception(newxmldoc);
305
      }
306
      //logMetacat.info("xml documnet:");
307
      //logMetacat.info(newxmldoc);
308

    
309
      // Try get the docid info from remote server
310
      DocInfoHandler dih = new DocInfoHandler();
311
      XMLReader docinfoParser = initParser(dih);
312
      String docInfoURLStr = "https://" + remoteserver +
313
                       "?server="+util.getLocalReplicationServerName()+
314
                       "&action=getdocumentinfo&docid="+accNumber;
315
      docInfoURLStr = MetaCatUtil.replaceWhiteSpaceForURL(docInfoURLStr);
316
      URL docinfoUrl = new URL(docInfoURLStr);
317
      logMetacat.info("Sending message: " +
318
                                                  docinfoUrl.toString());
319
      String docInfoStr = MetacatReplication.getURLContent(docinfoUrl);
320
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
321
      Hashtable docinfoHash = dih.getDocInfo();
322
      // Get home server of the docid
323
      String docHomeServer = (String)docinfoHash.get("home_server");
324
      logMetacat.info("doc home server in repl: "+docHomeServer);
325
      String createdDate = (String)docinfoHash.get("date_created");
326
      String updatedDate = (String)docinfoHash.get("date_updated");
327
      //docid should include rev number too
328
      /*String accnum=docId+util.getOption("accNumSeparator")+
329
                                              (String)docinfoHash.get("rev");*/
330
      logMetacat.info("docid in repl: "+accNumber);
331
      String docType = (String)docinfoHash.get("doctype");
332
      logMetacat.info("doctype in repl: "+docType);
333

    
334
      String parserBase = null;
335
      // this for eml2 and we need user eml2 parser
336
      if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
337
      {
338
         parserBase = DocumentImpl.EML200;
339
      }
340
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
341
      {
342
        parserBase = DocumentImpl.EML200;
343
      }
344
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
345
      {
346
        parserBase = DocumentImpl.EML210;
347
      }
348
      // Write the document into local host
349
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
350
      String newDocid = wrapper.writeReplication(dbConn,
351
                              new StringReader(newxmldoc),
352
                              (String)docinfoHash.get("public_access"),
353
                              null,  /* the dtd text */
354
                              actions,
355
                              accNumber,
356
                              (String)docinfoHash.get("user_owner"),
357
                              null, /* null for groups[] */
358
                              docHomeServer,
359
                              remoteserver, tableName, true,// true is for time replication 
360
                              createdDate,
361
                              updatedDate);
362
      logMetacat.info("Successfully replicated doc " + accNumber);
363
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
364
      {
365
        MetacatReplication.replLog("" +DOCINSERTNUMBER + " Wrote xml doc " + accNumber +
366
                                     " into "+tableName + " from " +
367
                                         remoteserver);
368
        DOCINSERTNUMBER++;
369
      }
370
      else
371
      {
372
          MetacatReplication.replLog("" +REVINSERTNUMBER + " Wrote xml doc " + accNumber +
373
                  " into "+tableName + " from " +
374
                      remoteserver);
375
          REVINSERTNUMBER++;
376
      }
377
      
378

    
379
    }//try
380
    catch(Exception e)
381
    {
382
        
383
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
384
        {
385
          MetacatReplication.replErrorLog("" +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
386
                                       " into "+tableName + " from " +
387
                                           remoteserver + " because "+e.getMessage());
388
          DOCERRORNUMBER++;
389
        }
390
        else
391
        {
392
            MetacatReplication.replErrorLog("" +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
393
                    " into "+tableName + " from " +
394
                        remoteserver +" because "+e.getMessage());
395
            REVERRORNUMBER++;
396
        }
397
       
398
      logMetacat.error("Failed to write doc " + accNumber +
399
                                      " into db because " +e.getMessage());
400
      throw e;
401
    }
402
    finally
403
    {
404
       //return DBConnection
405
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
406
    }//finally
407
  }
408

    
409

    
410

    
411
  /* Handle replicate single xml document*/
412
  private void handleSingleDataFile(String remoteserver, String actions,
413
                                    String accNumber, String tableName)
414
               throws Exception
415
  {
416
    logMetacat.info("Try to replicate data file: "+accNumber);
417
    DBConnection dbConn = null;
418
    int serialNumber = -1;
419
    try
420
    {
421
      // Get DBConnection from pool
422
      dbConn=DBConnectionPool.
423
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
424
      serialNumber=dbConn.getCheckOutSerialNumber();
425
      // Try get docid info from remote server
426
      DocInfoHandler dih = new DocInfoHandler();
427
      XMLReader docinfoParser = initParser(dih);
428
      String docInfoURLString = "https://" + remoteserver +
429
                  "?server="+util.getLocalReplicationServerName()+
430
                  "&action=getdocumentinfo&docid="+accNumber;
431
      docInfoURLString = MetaCatUtil.replaceWhiteSpaceForURL(docInfoURLString);
432
      URL docinfoUrl = new URL(docInfoURLString);
433

    
434
      String docInfoStr = MetacatReplication.getURLContent(docinfoUrl);
435
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
436
      Hashtable docinfoHash = dih.getDocInfo();
437
      // Get doicd owner
438
      String user = (String)docinfoHash.get("user_owner");
439
      // Get docid name (such as acl or dataset)
440
      String docName = (String)docinfoHash.get("docname");
441
      // Get doc type (eml public id)
442
      String docType = (String)docinfoHash.get("doctype");
443
      // Get docid home sever. it might be different to remoteserver
444
      // becuause of hub feature
445
      String docHomeServer = (String)docinfoHash.get("home_server");
446
      String createdDate = (String)docinfoHash.get("date_created");
447
      String updatedDate = (String)docinfoHash.get("date_updated");
448
      //docid should include rev number too
449
      /*String accnum=docId+util.getOption("accNumSeparator")+
450
                                              (String)docinfoHash.get("rev");*/
451

    
452

    
453
      String datafilePath = util.getOption("datafilepath");
454
      // Get data file content
455
      String readDataURLString = "https://" + remoteserver + "?server="+
456
                                        util.getLocalReplicationServerName()+
457
                                            "&action=readdata&docid="+accNumber;
458
      readDataURLString = MetaCatUtil.replaceWhiteSpaceForURL(readDataURLString);
459
      URL u = new URL(readDataURLString);
460
      InputStream input = u.openStream();
461
      //register data file into xml_documents table and wite data file
462
      //into file system
463
      if ( input != null)
464
      {
465
        DocumentImpl.writeDataFileInReplication(input,
466
                                                datafilePath,
467
                                                docName,docType,
468
                                                accNumber, user,
469
                                                docHomeServer,
470
                                                remoteserver,
471
                                                tableName,
472
                                                true, //true means timed replication
473
                                                createdDate,
474
                                                updatedDate);
475
                                         
476
        logMetacat.info("Successfully to write datafile " + accNumber);
477
        /*MetacatReplication.replLog("wrote datafile " + accNumber + " from " +
478
                                    remoteserver);*/
479
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
480
        {
481
          MetacatReplication.replLog("" +DOCINSERTNUMBER + " Wrote data file" + accNumber +
482
                                       " into "+tableName + " from " +
483
                                           remoteserver);
484
          DOCINSERTNUMBER++;
485
        }
486
        else
487
        {
488
            MetacatReplication.replLog("" +REVINSERTNUMBER + " Wrote data file" + accNumber +
489
                    " into "+tableName + " from " +
490
                        remoteserver);
491
            REVINSERTNUMBER++;
492
        }
493
        
494
      }//if
495
      else
496
      {
497
         logMetacat.info("Couldn't open the data file: " + accNumber);
498
         throw new Exception("Couldn't open the data file: " + accNumber);
499
      }//else
500

    
501
    }//try
502
    catch(Exception e)
503
    {
504
      /*MetacatReplication.replErrorLog("Failed to try wrote datafile " + accNumber +
505
                                      " because " +e.getMessage());*/
506
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
507
      {
508
        MetacatReplication.replErrorLog("" +DOCERRORNUMBER + " Failed to write data file " + accNumber +
509
                                     " into "+tableName + " from " +
510
                                         remoteserver + " because "+e.getMessage());
511
        DOCERRORNUMBER++;
512
      }
513
      else
514
      {
515
          MetacatReplication.replErrorLog("" +REVERRORNUMBER + " Failed to write data file" + accNumber +
516
                  " into "+tableName + " from " +
517
                      remoteserver +" because "+e.getMessage());
518
          REVERRORNUMBER++;
519
      }
520
      logMetacat.error("Failed to try wrote datafile " + accNumber +
521
                                      " because " +e.getMessage());
522
      throw e;
523
    }
524
    finally
525
    {
526
       //return DBConnection
527
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
528
    }//finally
529
  }
530

    
531

    
532

    
533
  /* Handle delete single document*/
534
  private void handleDeleteSingleDocument(String docId, String notifyServer)
535
               throws Exception
536
  {
537
    logMetacat.info("Try delete doc: "+docId);
538
    DBConnection dbConn = null;
539
    int serialNumber = -1;
540
    try
541
    {
542
      // Get DBConnection from pool
543
      dbConn=DBConnectionPool.
544
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
545
      serialNumber=dbConn.getCheckOutSerialNumber();
546
      if(!alreadyDeleted(docId))
547
      {
548

    
549
         //because delete method docid should have rev number
550
         //so we just add one for it. This rev number is no sence.
551
         String accnum=docId+util.getOption("accNumSeparator")+"1";
552
         //System.out.println("accnum: "+accnum);
553
         DocumentImpl.delete(accnum, null, null, notifyServer);
554
         logMetacat.info("Successfully deleted doc " + docId);
555
         MetacatReplication.replLog("Doc " + docId + " deleted");
556
      }
557

    
558
    }//try
559
    catch(Exception e)
560
    {
561
      MetacatReplication.replErrorLog("Failed to delete doc " + docId +
562
                                      " in db because " +e.getMessage());
563
      logMetacat.error("Failed to delete doc " + docId +
564
                                 " in db because because " + e.getMessage());
565
      throw e;
566
    }
567
    finally
568
    {
569
       //return DBConnection
570
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
571
    }//finally
572
  }
573

    
574
  /* Handle updateLastCheckTimForSingleServer*/
575
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
576
                                                  throws Exception
577
  {
578
    String server = repServer.getServerName();
579
    DBConnection dbConn = null;
580
    int serialNumber = -1;
581
    PreparedStatement pstmt = null;
582
    try
583
    {
584
      // Get DBConnection from pool
585
      dbConn=DBConnectionPool.
586
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
587
      serialNumber=dbConn.getCheckOutSerialNumber();
588

    
589
      logMetacat.info("Try to update last_check for server: "+server);
590
      // Get time from remote server
591
      URL dateurl = new URL("https://" + server + "?server="+
592
      util.getLocalReplicationServerName()+"&action=gettime");
593
      String datexml = MetacatReplication.getURLContent(dateurl);
594
      logMetacat.info("datexml: "+datexml);
595
      if (datexml!=null && !datexml.equals(""))
596
      {
597
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
598
         StringBuffer sql = new StringBuffer();
599
         /*sql.append("update xml_replication set last_checked = to_date('");
600
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
601
         sql.append("server like '").append(server).append("'");*/
602
         sql.append("update xml_replication set last_checked = ");
603
         sql.append(dbAdapter.toDate(datestr, "MM/DD/YY HH24:MI:SS"));
604
         sql.append(" where server like '").append(server).append("'");
605
         pstmt = dbConn.prepareStatement(sql.toString());
606

    
607
         pstmt.executeUpdate();
608
         dbConn.commit();
609
         pstmt.close();
610
         logMetacat.info("last_checked updated to "+datestr+" on "
611
                                      + server);
612
      }//if
613
      else
614
      {
615

    
616
         logMetacat.info("Failed to update last_checked for server "  +
617
                                  server + " in db because couldn't get time "
618
                                  );
619
         throw new Exception("Couldn't get time for server "+ server);
620
      }
621

    
622
    }//try
623
    catch(Exception e)
624
    {
625

    
626
      logMetacat.error("Failed to update last_checked for server " +
627
                                server + " in db because because " +
628
                                e.getMessage());
629
      throw e;
630
    }
631
    finally
632
    {
633
       //return DBConnection
634
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
635
    }//finally
636
  }
637

    
638

    
639

    
640
  /**
641
   * updates xml_catalog with entries from other servers.
642
   */
643
  private void updateCatalog()
644
  {
645
    logMetacat.info("Start of updateCatalog");
646
    // ReplicationServer object in server list
647
    ReplicationServer replServer = null;
648
    PreparedStatement pstmt = null;
649
    String server = null;
650

    
651

    
652
    // Go through each ReplicationServer object in sererlist
653
    for (int j=0; j<serverList.size(); j++)
654
    {
655
      Vector remoteCatalog = new Vector();
656
      Vector publicId = new Vector();
657
      try
658
      {
659
        // Get ReplicationServer object from server list
660
        replServer = serverList.serverAt(j);
661
        // Get server name from the ReplicationServer object
662
        server = replServer.getServerName();
663
        // Try to get catalog
664
        URL u = new URL("https://" + server + "?server="+
665
        util.getLocalReplicationServerName()+"&action=getcatalog");
666
        logMetacat.info("sending message " + u.toString());
667
        String catxml = MetacatReplication.getURLContent(u);
668

    
669
        // Make sure there are not error, no empty string
670
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
671
        {
672
          throw new Exception("Couldn't get catalog list form server " +server);
673
        }
674
        logMetacat.info("catxml: " + catxml);
675
        CatalogMessageHandler cmh = new CatalogMessageHandler();
676
        XMLReader catparser = initParser(cmh);
677
        catparser.parse(new InputSource(new StringReader(catxml)));
678
        //parse the returned catalog xml and put it into a vector
679
        remoteCatalog = cmh.getCatalogVect();
680

    
681
        // Makse sure remoteCatalog is not empty
682
        if (remoteCatalog.isEmpty())
683
        {
684
          throw new Exception("Couldn't get catalog list form server " +server);
685
        }
686

    
687
        String localcatxml = MetacatReplication.getCatalogXML();
688

    
689
        // Make sure local catalog is no empty
690
        if (localcatxml==null||localcatxml.equals(""))
691
        {
692
          throw new Exception("Couldn't get catalog list form server " +server);
693
        }
694

    
695
        cmh = new CatalogMessageHandler();
696
        catparser = initParser(cmh);
697
        catparser.parse(new InputSource(new StringReader(localcatxml)));
698
        Vector localCatalog = cmh.getCatalogVect();
699

    
700
        //now we have the catalog from the remote server and this local server
701
        //we now need to compare the two and merge the differences.
702
        //the comparison is base on the public_id fields which is the 4th
703
        //entry in each row vector.
704
        publicId = new Vector();
705
        for(int i=0; i<localCatalog.size(); i++)
706
        {
707
          Vector v = new Vector((Vector)localCatalog.elementAt(i));
708
          logMetacat.info("v1: " + v.toString());
709
          publicId.add(new String((String)v.elementAt(3)));
710
          //System.out.println("adding " + (String)v.elementAt(3));
711
        }
712
      }//try
713
      catch (Exception e)
714
      {
715
        MetacatReplication.replErrorLog("Failed to update catalog for server "+
716
                                    server + " because " +e.getMessage());
717
        logMetacat.error("Failed to update catalog for server "+
718
                                    server + " because " +e.getMessage());
719
      }//catch
720

    
721
      for(int i=0; i<remoteCatalog.size(); i++)
722
      {
723
         // DConnection
724
        DBConnection dbConn = null;
725
        // DBConnection checkout serial number
726
        int serialNumber = -1;
727
        try
728
        {
729
            dbConn=DBConnectionPool.
730
                  getDBConnection("ReplicationHandler.updateCatalog");
731
            serialNumber=dbConn.getCheckOutSerialNumber();
732
            Vector v = (Vector)remoteCatalog.elementAt(i);
733
            //System.out.println("v2: " + v.toString());
734
            //System.out.println("i: " + i);
735
            //System.out.println("remoteCatalog.size(): " + remoteCatalog.size());
736
            //System.out.println("publicID: " + publicId.toString());
737
            logMetacat.info
738
                              ("v.elementAt(3): " + (String)v.elementAt(3));
739
           if(!publicId.contains(v.elementAt(3)))
740
           { //so we don't have this public id in our local table so we need to
741
             //add it.
742
             //System.out.println("in if");
743
             StringBuffer sql = new StringBuffer();
744
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
745
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
746
             sql.append("?,?)");
747
             //System.out.println("sql: " + sql.toString());
748
             pstmt = dbConn.prepareStatement(sql.toString());
749
             pstmt.setString(1, (String)v.elementAt(0));
750
             pstmt.setString(2, (String)v.elementAt(1));
751
             pstmt.setString(3, (String)v.elementAt(2));
752
             pstmt.setString(4, (String)v.elementAt(3));
753
             pstmt.setString(5, (String)v.elementAt(4));
754
             pstmt.execute();
755
             pstmt.close();
756
             MetacatReplication.replLog("Success fully to insert new publicid "+
757
                               (String)v.elementAt(3) + " from server"+server);
758
             logMetacat.info("Success fully to insert new publicid "+
759
                             (String)v.elementAt(3) + " from server" +server);
760
           }
761
        }
762
        catch(Exception e)
763
        {
764
           MetacatReplication.replErrorLog("Failed to update catalog for server "+
765
                                    server + " because " +e.getMessage());
766
           logMetacat.error("Failed to update catalog for server "+
767
                                    server + " because " +e.getMessage());
768
        }//catch
769
        finally
770
        {
771
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
772
        }//finall
773
      }//for remote catalog
774
    }//for server list
775
    logMetacat.info("End of updateCatalog");
776
  }
777

    
778
  /**
779
   * Method that returns true if docid has already been "deleted" from metacat.
780
   * This method really implements a truth table for deleted documents
781
   * The table is (a docid in one of the tables is represented by the X):
782
   * xml_docs      xml_revs      deleted?
783
   * ------------------------------------
784
   *   X             X             FALSE
785
   *   X             _             FALSE
786
   *   _             X             TRUE
787
   *   _             _             TRUE
788
   */
789
  private static boolean alreadyDeleted(String docid) throws Exception
790
  {
791
    DBConnection dbConn = null;
792
    int serialNumber = -1;
793
    PreparedStatement pstmt = null;
794
    try
795
    {
796
      dbConn=DBConnectionPool.
797
                  getDBConnection("ReplicationHandler.alreadyDeleted");
798
      serialNumber=dbConn.getCheckOutSerialNumber();
799
      boolean xml_docs = false;
800
      boolean xml_revs = false;
801

    
802
      StringBuffer sb = new StringBuffer();
803
      sb.append("select docid from xml_revisions where docid like '");
804
      sb.append(docid).append("'");
805
      pstmt = dbConn.prepareStatement(sb.toString());
806
      pstmt.execute();
807
      ResultSet rs = pstmt.getResultSet();
808
      boolean tablehasrows = rs.next();
809
      if(tablehasrows)
810
      {
811
        xml_revs = true;
812
      }
813

    
814
      sb = new StringBuffer();
815
      sb.append("select docid from xml_documents where docid like '");
816
      sb.append(docid).append("'");
817
      pstmt.close();
818
      pstmt = dbConn.prepareStatement(sb.toString());
819
      //increase usage count
820
      dbConn.increaseUsageCount(1);
821
      pstmt.execute();
822
      rs = pstmt.getResultSet();
823
      tablehasrows = rs.next();
824
      pstmt.close();
825
      if(tablehasrows)
826
      {
827
        xml_docs = true;
828
      }
829

    
830
      if(xml_docs && xml_revs)
831
      {
832
        return false;
833
      }
834
      else if(xml_docs && !xml_revs)
835
      {
836
        return false;
837
      }
838
      else if(!xml_docs && xml_revs)
839
      {
840
        return true;
841
      }
842
      else if(!xml_docs && !xml_revs)
843
      {
844
        return true;
845
      }
846
    }
847
    catch(Exception e)
848
    {
849
      logMetacat.error("error in ReplicationHandler.alreadyDeleted: " +
850
                          e.getMessage());
851
      throw e;
852
    }
853
    finally
854
    {
855
      try
856
      {
857
        pstmt.close();
858
      }//try
859
      catch (SQLException ee)
860
      {
861
        logMetacat.error("Error in replicationHandler.alreadyDeleted "+
862
                          "to close pstmt: "+ee.getMessage());
863
        throw ee;
864
      }//catch
865
      finally
866
      {
867
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
868
      }//finally
869
    }//finally
870
    return false;
871
  }
872

    
873

    
874
  /**
875
   * Method to initialize the message parser
876
   */
877
  public static XMLReader initParser(DefaultHandler dh)
878
          throws Exception
879
  {
880
    XMLReader parser = null;
881

    
882
    try {
883
      ContentHandler chandler = dh;
884

    
885
      // Get an instance of the parser
886
      MetaCatUtil util = new MetaCatUtil();
887
      String parserName = util.getOption("saxparser");
888
      parser = XMLReaderFactory.createXMLReader(parserName);
889

    
890
      // Turn off validation
891
      parser.setFeature("http://xml.org/sax/features/validation", false);
892

    
893
      parser.setContentHandler((ContentHandler)chandler);
894
      parser.setErrorHandler((ErrorHandler)chandler);
895

    
896
    } catch (Exception e) {
897
      throw e;
898
    }
899

    
900
    return parser;
901
  }
902

    
903
  /**
904
   * This method will combinate given time string(in short format) to
905
   * current date. If the given time (e.g 10:00 AM) passed the current time
906
   * (e.g 2:00 PM Aug 21, 2005), then the time will set to second day,
907
   * 10:00 AM Aug 22, 2005. If the given time (e.g 10:00 AM) haven't passed
908
   * the current time (e.g 8:00 AM Aug 21, 2005) The time will set to be
909
   * 10:00 AM Aug 21, 2005.
910
   * @param givenTime  the format should be "10:00 AM " or "2:00 PM"
911
   * @return
912
   * @throws Exception
913
   */
914
  public static Date combinateCurrentDateAndGivenTime(String givenTime) throws Exception
915
  {
916
     Date givenDate = parseTime(givenTime);
917
     Date newDate = null;
918
     Date now = new Date();
919
     String currentTimeString = getTimeString(now);
920
     Date currentTime = parseTime(currentTimeString); 
921
     if ( currentTime.getTime() >= givenDate.getTime())
922
     {
923
        logMetacat.info("Today already pass the given time, we should set it as tomorrow");
924
        String dateAndTime = getDateString(now) + " " + givenTime;
925
        Date combinationDate = parseDateTime(dateAndTime);
926
        // new date should plus 24 hours to make is the second day
927
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
928
     }
929
     else
930
     {
931
         logMetacat.info("Today haven't pass the given time, we should it as today");
932
         String dateAndTime = getDateString(now) + " " + givenTime;
933
         newDate = parseDateTime(dateAndTime);
934
     }
935
     logMetacat.warn("final setting time is "+ newDate.toString());
936
     return newDate;
937
  }
938

    
939
  /*
940
   * parse a given string to Time in short format.
941
   * For example, given time is 10:00 AM, the date will be return as
942
   * Jan 1 1970, 10:00 AM
943
   */
944
  private static Date parseTime(String timeString) throws Exception
945
  {
946
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
947
    Date time = format.parse(timeString); 
948
    logMetacat.info("Date string is after parse a time string "
949
                              +time.toString());
950
    return time;
951

    
952
  }
953
  
954
  /*
955
   * Pasre a given string to date and time. Date format is long and time
956
   * format is short.
957
   */
958
  private static Date parseDateTime(String timeString) throws Exception
959
  {
960
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
961
    Date time = format.parse(timeString);
962
    logMetacat.info("Date string is after parse a time string "+
963
                             time.toString());
964
    return time;
965
  }
966
  
967
  /*
968
   * Get a date string from a Date object. The date format will be long
969
   */
970
  private static String getDateString(Date now)
971
  {
972
     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
973
     String s = df.format(now);
974
     logMetacat.info("Today is " + s);
975
     return s;
976
  }
977
  
978
  /*
979
   * Get a time string from a Date object, the time format will be short
980
   */
981
  private static String getTimeString(Date now)
982
  {
983
     DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
984
     String s = df.format(now);
985
     logMetacat.info("Time is " + s);
986
     return s;
987
  }
988
  
989
  
990
  /*
991
   * This method will go through the docid list both in xml_Documents table
992
   * and in xml_revisions table
993
   * @author tao
994
   */
995
   private void handleDocList(Vector docList, String tableName)
996
   {
997
       boolean dataFile=false;
998
       for(int j=0; j<docList.size(); j++)
999
       {
1000
         //initial dataFile is false
1001
         dataFile=false;
1002
         //w is information for one document, information contain
1003
         //docid, rev, server or datafile.
1004
         Vector w = new Vector((Vector)(docList.elementAt(j)));
1005
         //Check if the vector w contain "datafile"
1006
         //If it has, this document is data file
1007
         if (w.contains((String)util.getOption("datafileflag")))
1008
         {
1009
           dataFile=true;
1010
         }
1011
         //System.out.println("w: " + w.toString());
1012
         // Get docid
1013
         String docid = (String)w.elementAt(0);
1014
         logMetacat.info("docid: " + docid);
1015
         // Get revision number
1016
         int rev = Integer.parseInt((String)w.elementAt(1));
1017
         logMetacat.info("rev: " + rev);
1018
         // Get remote server name (it is may not be doc homeserver because
1019
         // the new hub feature
1020
         String remoteServer = (String)w.elementAt(2);
1021
         remoteServer = remoteServer.trim();
1022

    
1023
         try
1024
         {
1025
             if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
1026
             {
1027
                 handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1028
             }
1029
             else if (tableName.equals(DocumentImpl.REVISIONTABLE))
1030
             {
1031
                 handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1032
             }
1033
             else
1034
             {
1035
                 continue;
1036
             }
1037
                 
1038
         }
1039
         catch (Exception e)
1040
         {
1041
             logMetacat.error("error to handle update doc in "+ 
1042
                     tableName +" in time replication"+e.getMessage());
1043
             continue;
1044
         }
1045
        
1046
       }//for update docs
1047

    
1048
   }
1049
   
1050
   /*
1051
    * This method will handle doc in xml_documents table.
1052
    */
1053
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
1054
                                        throws Exception
1055
   {
1056
       // compare the update rev and local rev to see what need happen
1057
       int localrev = -1;
1058
       String action = null;
1059
       boolean flag = false;
1060
       try
1061
       {
1062
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1063
       }
1064
       catch (SQLException e)
1065
       {
1066
         logMetacat.error("Local rev for docid "+ docid + " could not "+
1067
                                " be found because " + e.getMessage());
1068
         MetacatReplication.replErrorLog(""+DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1069
                 "written because error happend to find it's local revision");
1070
         DOCERRORNUMBER++;
1071
         throw new Exception (e.getMessage());
1072
       }
1073
       logMetacat.info("Local rev for docid "+ docid + " is "+
1074
                               localrev);
1075

    
1076
       //check the revs for an update because this document is in the
1077
       //local DB, it might be out of date.
1078
       if (localrev == -1)
1079
       {
1080
          // check if the revision is in the revision table
1081
         Vector localRevVector = DBUtil.getRevListFromRevisionTable(docid);
1082
         if (localRevVector != null && localRevVector.contains(new Integer(rev)))
1083
         {
1084
             // this version was deleted, so don't need replicate
1085
             flag = false;
1086
         }
1087
         else
1088
         {
1089
           //insert this document as new because it is not in the local DB
1090
           action = "INSERT";
1091
           flag = true;
1092
         }
1093
       }
1094
       else
1095
       {
1096
         if(localrev == rev)
1097
         {
1098
           // Local meatacat has the same rev to remote host, don't need
1099
           // update and flag set false
1100
           flag = false;
1101
         }
1102
         else if(localrev < rev)
1103
         {
1104
           //this document needs to be updated so send an read request
1105
           action = "UPDATE";
1106
           flag = true;
1107
         }
1108
       }
1109
       
1110
       String accNumber = docid + MetaCatUtil.getOption("accNumSeparator") + rev;
1111
       // this is non-data file
1112
       if(flag && !dataFile)
1113
       {
1114
         try
1115
         {
1116
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1117
         }
1118
         catch(Exception e)
1119
         {
1120
           // skip this document
1121
           throw e;
1122
         }
1123
       }//if for non-data file
1124

    
1125
        // this is for data file
1126
       if(flag && dataFile)
1127
       {
1128
         try
1129
         {
1130
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1131
         }
1132
         catch(Exception e)
1133
         {
1134
           // skip this datafile
1135
           throw e;
1136
         }
1137

    
1138
       }//for datafile
1139
   }
1140
   
1141
   /*
1142
    * This method will handle doc in xml_documents table.
1143
    */
1144
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile) 
1145
                                        throws Exception
1146
   {
1147
       // compare the update rev and local rev to see what need happen
1148
       logMetacat.info("In handle repliation revsion table");
1149
       logMetacat.info("the docid is "+ docid);
1150
       logMetacat.info("The rev is "+rev);
1151
       Vector localrev = null;
1152
       String action = "INSERT";
1153
       boolean flag = false;
1154
       try
1155
       {
1156
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1157
       }
1158
       catch (SQLException e)
1159
       {
1160
         logMetacat.error("Local rev for docid "+ docid + " could not "+
1161
                                " be found because " + e.getMessage());
1162
         MetacatReplication.replErrorLog(""+REVERRORNUMBER+" Docid "+ docid + " could not be "+
1163
                 "written because error happend to find it's local revision");
1164
         REVERRORNUMBER++;
1165
         throw new Exception (e.getMessage());
1166
       }
1167
       logMetacat.info("rev list in xml_revision table for docid "+ docid + " is "+
1168
                               localrev.toString());
1169
       
1170
       // if the rev is not in the xml_revision, we need insert it
1171
       if (!localrev.contains(new Integer(rev)))
1172
       {
1173
           flag = true;    
1174
       }
1175
     
1176
       String accNumber = docid + MetaCatUtil.getOption("accNumSeparator") + rev;
1177
       // this is non-data file
1178
       if(flag && !dataFile)
1179
       {
1180
         try
1181
         {
1182
           
1183
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1184
         }
1185
         catch(Exception e)
1186
         {
1187
           // skip this document
1188
           throw e;
1189
         }
1190
       }//if for non-data file
1191

    
1192
        // this is for data file
1193
       if(flag && dataFile)
1194
       {
1195
         try
1196
         {
1197
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1198
         }
1199
         catch(Exception e)
1200
         {
1201
           // skip this datafile
1202
           throw e;
1203
         }
1204

    
1205
       }//for datafile
1206
   }
1207
  
1208
}
1209

    
(59-59/65)