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: daigle $'
9
 *     '$Date: 2008-08-29 10:20:19 -0700 (Fri, 29 Aug 2008) $'
10
 * '$Revision: 4335 $'
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.metacat.service.DatabaseService;
30
import edu.ucsb.nceas.metacat.service.PropertyService;
31
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
32
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
33

    
34
import java.sql.*;
35
import java.util.*;
36
import java.util.Date;
37
import java.lang.Thread;
38
import java.io.*;
39
import java.net.*;
40
import java.text.*;
41

    
42
import org.apache.log4j.Logger;
43
import org.xml.sax.AttributeList;
44
import org.xml.sax.ContentHandler;
45
import org.xml.sax.DTDHandler;
46
import org.xml.sax.EntityResolver;
47
import org.xml.sax.ErrorHandler;
48
import org.xml.sax.InputSource;
49
import org.xml.sax.XMLReader;
50
import org.xml.sax.SAXException;
51
import org.xml.sax.SAXParseException;
52
import org.xml.sax.helpers.XMLReaderFactory;
53
import org.xml.sax.helpers.DefaultHandler;
54

    
55

    
56

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

    
79
  public ReplicationHandler(int serverCheckCode)
80
  {
81
    //this.out = o;
82
    this.serverCheckCode = serverCheckCode;
83
    serverList = new ReplicationServerList();
84
  }
85

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

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

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

    
141

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

    
170
        logMetacat.info("docid: "+server+" "+result);
171
        //check if result have error or not, if has skip it.
172
        if (result.indexOf("<error>")!=-1 && result.indexOf("</error>")!=-1)
173
        {
174
          MetacatReplication.replErrorLog("Failed to get updated doc list "+
175
                          "for server " + server + " because "+result);
176
          logMetacat.info( "Failed to get updated doc list "+
177
                       "for server " + server + " because "+result);
178
          continue;
179
        }
180
        //Add result to vector
181
        responses.add(result);
182
    }
183

    
184
    //make sure that there is updated file list
185
    //If response is null, metacat don't need do anything
186
    if (responses==null || responses.isEmpty())
187
    {
188
        MetacatReplication.replErrorLog("No updated doc list for "+
189
                           "every server and failed to replicate");
190
        logMetacat.info( "No updated doc list for "+
191
                           "every server and failed to replicate");
192
        return;
193
    }
194

    
195

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

    
269
    //updated last_checked
270
    for (int i=0;i<serverList.size(); i++)
271
    {
272
       // Get ReplicationServer object from server list
273
       replServer = serverList.serverAt(i);
274
       try
275
       {
276
         updateLastCheckTimeForSingleServer(replServer);
277
       }
278
       catch(Exception e)
279
       {
280
         continue;
281
       }
282
    }//for
283

    
284
  }//update
285

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

    
305
      // Get docid content
306
      String newxmldoc = MetacatReplication.getURLContent(u);
307
      // If couldn't get skip it
308
      if ( newxmldoc.indexOf("<error>")!= -1 && newxmldoc.indexOf("</error>")!=-1)
309
      {
310
         throw new Exception(newxmldoc);
311
      }
312
      //logMetacat.info("xml documnet:");
313
      //logMetacat.info(newxmldoc);
314

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

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

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

    
417

    
418

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

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

    
460

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

    
511
    }//try
512
    catch(Exception e)
513
    {
514
      /*MetacatReplication.replErrorLog("Failed to try wrote datafile " + accNumber +
515
                                      " because " +e.getMessage());*/
516
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
517
      {
518
        MetacatReplication.replErrorLog("" +DOCERRORNUMBER + " Failed to write data file " + accNumber +
519
                                     " into "+tableName + " from " +
520
                                         remoteserver + " because "+e.getMessage());
521
        DOCERRORNUMBER++;
522
      }
523
      else
524
      {
525
          MetacatReplication.replErrorLog("" +REVERRORNUMBER + " Failed to write data file" + accNumber +
526
                  " into "+tableName + " from " +
527
                      remoteserver +" because "+e.getMessage());
528
          REVERRORNUMBER++;
529
      }
530
      logMetacat.error("Failed to try wrote datafile " + accNumber +
531
                                      " because " +e.getMessage());
532
      throw e;
533
    }
534
    finally
535
    {
536
       //return DBConnection
537
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
538
    }//finally
539
  }
540

    
541

    
542

    
543
  /* Handle delete single document*/
544
  private void handleDeleteSingleDocument(String docId, String notifyServer)
545
               throws Exception
546
  {
547
    logMetacat.info("Try delete doc: "+docId);
548
    DBConnection dbConn = null;
549
    int serialNumber = -1;
550
    try
551
    {
552
      // Get DBConnection from pool
553
      dbConn=DBConnectionPool.
554
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
555
      serialNumber=dbConn.getCheckOutSerialNumber();
556
      if(!alreadyDeleted(docId))
557
      {
558

    
559
         //because delete method docid should have rev number
560
         //so we just add one for it. This rev number is no sence.
561
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
562
         //System.out.println("accnum: "+accnum);
563
         DocumentImpl.delete(accnum, null, null, notifyServer);
564
         logMetacat.info("Successfully deleted doc " + docId);
565
         MetacatReplication.replLog("Doc " + docId + " deleted");
566
         URL u = new URL("https://"+notifyServer);
567
         String ip = getIpFromURL(u);
568
         EventLog.getInstance().log(ip, MetacatReplication.REPLICATIONUSER, docId, "delete");
569
      }
570

    
571
    }//try
572
    catch(Exception e)
573
    {
574
      MetacatReplication.replErrorLog("Failed to delete doc " + docId +
575
                                      " in db because " +e.getMessage());
576
      logMetacat.error("Failed to delete doc " + docId +
577
                                 " in db because because " + e.getMessage());
578
      throw e;
579
    }
580
    finally
581
    {
582
       //return DBConnection
583
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
584
    }//finally
585
  }
586

    
587
  /* Handle updateLastCheckTimForSingleServer*/
588
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
589
                                                  throws Exception
590
  {
591
    String server = repServer.getServerName();
592
    DBConnection dbConn = null;
593
    int serialNumber = -1;
594
    PreparedStatement pstmt = null;
595
    try
596
    {
597
      // Get DBConnection from pool
598
      dbConn=DBConnectionPool.
599
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
600
      serialNumber=dbConn.getCheckOutSerialNumber();
601

    
602
      logMetacat.info("Try to update last_check for server: "+server);
603
      // Get time from remote server
604
      URL dateurl = new URL("https://" + server + "?server="+
605
      MetaCatUtil.getLocalReplicationServerName()+"&action=gettime");
606
      String datexml = MetacatReplication.getURLContent(dateurl);
607
      logMetacat.info("datexml: "+datexml);
608
      if (datexml!=null && !datexml.equals(""))
609
      {
610
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
611
         StringBuffer sql = new StringBuffer();
612
         /*sql.append("update xml_replication set last_checked = to_date('");
613
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
614
         sql.append("server like '").append(server).append("'");*/
615
         sql.append("update xml_replication set last_checked = ");
616
         sql.append(DatabaseService.getDBAdapter().toDate(datestr, "MM/DD/YY HH24:MI:SS"));
617
         sql.append(" where server like '").append(server).append("'");
618
         pstmt = dbConn.prepareStatement(sql.toString());
619

    
620
         pstmt.executeUpdate();
621
         dbConn.commit();
622
         pstmt.close();
623
         logMetacat.info("last_checked updated to "+datestr+" on "
624
                                      + server);
625
      }//if
626
      else
627
      {
628

    
629
         logMetacat.info("Failed to update last_checked for server "  +
630
                                  server + " in db because couldn't get time "
631
                                  );
632
         throw new Exception("Couldn't get time for server "+ server);
633
      }
634

    
635
    }//try
636
    catch(Exception e)
637
    {
638

    
639
      logMetacat.error("Failed to update last_checked for server " +
640
                                server + " in db because because " +
641
                                e.getMessage());
642
      throw e;
643
    }
644
    finally
645
    {
646
       //return DBConnection
647
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
648
    }//finally
649
  }
650

    
651

    
652

    
653
  /**
654
   * updates xml_catalog with entries from other servers.
655
   */
656
  private void updateCatalog()
657
  {
658
    logMetacat.info("Start of updateCatalog");
659
    // ReplicationServer object in server list
660
    ReplicationServer replServer = null;
661
    PreparedStatement pstmt = null;
662
    String server = null;
663

    
664

    
665
    // Go through each ReplicationServer object in sererlist
666
    for (int j=0; j<serverList.size(); j++)
667
    {
668
      Vector remoteCatalog = new Vector();
669
      Vector publicId = new Vector();
670
      try
671
      {
672
        // Get ReplicationServer object from server list
673
        replServer = serverList.serverAt(j);
674
        // Get server name from the ReplicationServer object
675
        server = replServer.getServerName();
676
        // Try to get catalog
677
        URL u = new URL("https://" + server + "?server="+
678
        MetaCatUtil.getLocalReplicationServerName()+"&action=getcatalog");
679
        logMetacat.info("sending message " + u.toString());
680
        String catxml = MetacatReplication.getURLContent(u);
681

    
682
        // Make sure there are not error, no empty string
683
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
684
        {
685
          throw new Exception("Couldn't get catalog list form server " +server);
686
        }
687
        logMetacat.info("catxml: " + catxml);
688
        CatalogMessageHandler cmh = new CatalogMessageHandler();
689
        XMLReader catparser = initParser(cmh);
690
        catparser.parse(new InputSource(new StringReader(catxml)));
691
        //parse the returned catalog xml and put it into a vector
692
        remoteCatalog = cmh.getCatalogVect();
693

    
694
        // Makse sure remoteCatalog is not empty
695
        if (remoteCatalog.isEmpty())
696
        {
697
          throw new Exception("Couldn't get catalog list form server " +server);
698
        }
699

    
700
        String localcatxml = MetacatReplication.getCatalogXML();
701

    
702
        // Make sure local catalog is no empty
703
        if (localcatxml==null||localcatxml.equals(""))
704
        {
705
          throw new Exception("Couldn't get catalog list form server " +server);
706
        }
707

    
708
        cmh = new CatalogMessageHandler();
709
        catparser = initParser(cmh);
710
        catparser.parse(new InputSource(new StringReader(localcatxml)));
711
        Vector localCatalog = cmh.getCatalogVect();
712

    
713
        //now we have the catalog from the remote server and this local server
714
        //we now need to compare the two and merge the differences.
715
        //the comparison is base on the public_id fields which is the 4th
716
        //entry in each row vector.
717
        publicId = new Vector();
718
        for(int i=0; i<localCatalog.size(); i++)
719
        {
720
          Vector v = new Vector((Vector)localCatalog.elementAt(i));
721
          logMetacat.info("v1: " + v.toString());
722
          publicId.add(new String((String)v.elementAt(3)));
723
          //System.out.println("adding " + (String)v.elementAt(3));
724
        }
725
      }//try
726
      catch (Exception e)
727
      {
728
        MetacatReplication.replErrorLog("Failed to update catalog for server "+
729
                                    server + " because " +e.getMessage());
730
        logMetacat.error("Failed to update catalog for server "+
731
                                    server + " because " +e.getMessage());
732
      }//catch
733

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

    
791
  /**
792
   * Method that returns true if docid has already been "deleted" from metacat.
793
   * This method really implements a truth table for deleted documents
794
   * The table is (a docid in one of the tables is represented by the X):
795
   * xml_docs      xml_revs      deleted?
796
   * ------------------------------------
797
   *   X             X             FALSE
798
   *   X             _             FALSE
799
   *   _             X             TRUE
800
   *   _             _             TRUE
801
   */
802
  private static boolean alreadyDeleted(String docid) throws Exception
803
  {
804
    DBConnection dbConn = null;
805
    int serialNumber = -1;
806
    PreparedStatement pstmt = null;
807
    try
808
    {
809
      dbConn=DBConnectionPool.
810
                  getDBConnection("ReplicationHandler.alreadyDeleted");
811
      serialNumber=dbConn.getCheckOutSerialNumber();
812
      boolean xml_docs = false;
813
      boolean xml_revs = false;
814

    
815
      StringBuffer sb = new StringBuffer();
816
      sb.append("select docid from xml_revisions where docid like '");
817
      sb.append(docid).append("'");
818
      pstmt = dbConn.prepareStatement(sb.toString());
819
      pstmt.execute();
820
      ResultSet rs = pstmt.getResultSet();
821
      boolean tablehasrows = rs.next();
822
      if(tablehasrows)
823
      {
824
        xml_revs = true;
825
      }
826

    
827
      sb = new StringBuffer();
828
      sb.append("select docid from xml_documents where docid like '");
829
      sb.append(docid).append("'");
830
      pstmt.close();
831
      pstmt = dbConn.prepareStatement(sb.toString());
832
      //increase usage count
833
      dbConn.increaseUsageCount(1);
834
      pstmt.execute();
835
      rs = pstmt.getResultSet();
836
      tablehasrows = rs.next();
837
      pstmt.close();
838
      if(tablehasrows)
839
      {
840
        xml_docs = true;
841
      }
842

    
843
      if(xml_docs && xml_revs)
844
      {
845
        return false;
846
      }
847
      else if(xml_docs && !xml_revs)
848
      {
849
        return false;
850
      }
851
      else if(!xml_docs && xml_revs)
852
      {
853
        return true;
854
      }
855
      else if(!xml_docs && !xml_revs)
856
      {
857
        return true;
858
      }
859
    }
860
    catch(Exception e)
861
    {
862
      logMetacat.error("error in ReplicationHandler.alreadyDeleted: " +
863
                          e.getMessage());
864
      throw e;
865
    }
866
    finally
867
    {
868
      try
869
      {
870
        pstmt.close();
871
      }//try
872
      catch (SQLException ee)
873
      {
874
        logMetacat.error("Error in replicationHandler.alreadyDeleted "+
875
                          "to close pstmt: "+ee.getMessage());
876
        throw ee;
877
      }//catch
878
      finally
879
      {
880
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
881
      }//finally
882
    }//finally
883
    return false;
884
  }
885

    
886

    
887
  /**
888
   * Method to initialize the message parser
889
   */
890
  public static XMLReader initParser(DefaultHandler dh)
891
          throws Exception
892
  {
893
    XMLReader parser = null;
894

    
895
    try {
896
      ContentHandler chandler = dh;
897

    
898
      // Get an instance of the parser
899
      String parserName = PropertyService.getProperty("xml.saxparser");
900
      parser = XMLReaderFactory.createXMLReader(parserName);
901

    
902
      // Turn off validation
903
      parser.setFeature("http://xml.org/sax/features/validation", false);
904

    
905
      parser.setContentHandler((ContentHandler)chandler);
906
      parser.setErrorHandler((ErrorHandler)chandler);
907

    
908
    } catch (Exception e) {
909
      throw e;
910
    }
911

    
912
    return parser;
913
  }
914

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

    
951
  /*
952
   * parse a given string to Time in short format.
953
   * For example, given time is 10:00 AM, the date will be return as
954
   * Jan 1 1970, 10:00 AM
955
   */
956
  private static Date parseTime(String timeString) throws Exception
957
  {
958
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
959
    Date time = format.parse(timeString); 
960
    logMetacat.info("Date string is after parse a time string "
961
                              +time.toString());
962
    return time;
963

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

    
1036
			try {
1037
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1038
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1039
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1040
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1041
				} else {
1042
					continue;
1043
				}
1044

    
1045
			} catch (Exception e) {
1046
				logMetacat.error("error to handle update doc in " + tableName
1047
						+ " in time replication" + e.getMessage());
1048
				continue;
1049
			}
1050

    
1051
		}// for update docs
1052

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

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

    
1130
        // this is for data file
1131
       if(flag && dataFile)
1132
       {
1133
         try
1134
         {
1135
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1136
         }
1137
         catch(Exception e)
1138
         {
1139
           // skip this datafile
1140
           throw e;
1141
         }
1142

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

    
1197
        // this is for data file
1198
       if(flag && dataFile)
1199
       {
1200
         try
1201
         {
1202
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1203
         }
1204
         catch(Exception e)
1205
         {
1206
           // skip this datafile
1207
           throw e;
1208
         }
1209

    
1210
       }//for datafile
1211
   }
1212
   
1213
   /*
1214
    * Return a ip address for given url
1215
    */
1216
   private String getIpFromURL(URL url)
1217
   {
1218
	   String ip = null;
1219
	   try
1220
	   {
1221
	      InetAddress address = InetAddress.getByName(url.getHost());
1222
	      ip = address.getHostAddress();
1223
	   }
1224
	   catch(UnknownHostException e)
1225
	   {
1226
		   logMetacat.error("Error in get ip address for host: "
1227
                   +e.getMessage());
1228
	   }
1229

    
1230
	   return ip;
1231
   }
1232
  
1233
}
1234

    
(60-60/67)