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: leinfelder $'
9
 *     '$Date: 2008-10-07 16:40:24 -0700 (Tue, 07 Oct 2008) $'
10
 * '$Revision: 4419 $'
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
      
369
      //process extra access rules
370
      Vector accessControlList = (Vector) docinfoHash.get("accessControl");
371
      if (accessControlList != null) {
372
    	  for (int i = 0; i < accessControlList.size(); i++) {
373
        	  AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList.get(i);
374
        	  acfsf.insertPermissions();
375
          }
376
      }
377
      
378
      logMetacat.info("Successfully replicated doc " + accNumber);
379
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
380
      {
381
        MetacatReplication.replLog("" +DOCINSERTNUMBER + " Wrote xml doc " + accNumber +
382
                                     " into "+tableName + " from " +
383
                                         remoteserver);
384
        DOCINSERTNUMBER++;
385
      }
386
      else
387
      {
388
          MetacatReplication.replLog("" +REVINSERTNUMBER + " Wrote xml doc " + accNumber +
389
                  " into "+tableName + " from " +
390
                      remoteserver);
391
          REVINSERTNUMBER++;
392
      }
393
      String ip = getIpFromURL(u);
394
      EventLog.getInstance().log(ip, MetacatReplication.REPLICATIONUSER, accNumber, actions);
395
      
396

    
397
    }//try
398
    catch(Exception e)
399
    {
400
        
401
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
402
        {
403
          MetacatReplication.replErrorLog("" +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
404
                                       " into "+tableName + " from " +
405
                                           remoteserver + " because "+e.getMessage());
406
          DOCERRORNUMBER++;
407
        }
408
        else
409
        {
410
            MetacatReplication.replErrorLog("" +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
411
                    " into "+tableName + " from " +
412
                        remoteserver +" because "+e.getMessage());
413
            REVERRORNUMBER++;
414
        }
415
       
416
      logMetacat.error("Failed to write doc " + accNumber +
417
                                      " into db because " +e.getMessage());
418
      throw e;
419
    }
420
    finally
421
    {
422
       //return DBConnection
423
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
424
    }//finally
425
  }
426

    
427

    
428

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

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

    
470

    
471
      String datafilePath = PropertyService.getProperty("application.datafilepath");
472
      // Get data file content
473
      String readDataURLString = "https://" + remoteserver + "?server="+
474
                                        MetaCatUtil.getLocalReplicationServerName()+
475
                                            "&action=readdata&docid="+accNumber;
476
      readDataURLString = MetaCatUtil.replaceWhiteSpaceForURL(readDataURLString);
477
      URL u = new URL(readDataURLString);
478
      InputStream input = u.openStream();
479
      //register data file into xml_documents table and wite data file
480
      //into file system
481
      if ( input != null)
482
      {
483
        DocumentImpl.writeDataFileInReplication(input,
484
                                                datafilePath,
485
                                                docName,docType,
486
                                                accNumber, user,
487
                                                docHomeServer,
488
                                                remoteserver,
489
                                                tableName,
490
                                                true, //true means timed replication
491
                                                createdDate,
492
                                                updatedDate);
493
                                         
494
        //process extra access rules
495
        Vector accessControlList = (Vector) docinfoHash.get("accessControl");
496
        if (accessControlList != null) {
497
      	  for (int i = 0; i < accessControlList.size(); i++) {
498
          	  AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList.get(i);
499
          	  acfsf.insertPermissions();
500
            }
501
        }
502
        
503
        logMetacat.info("Successfully to write datafile " + accNumber);
504
        /*MetacatReplication.replLog("wrote datafile " + accNumber + " from " +
505
                                    remoteserver);*/
506
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
507
        {
508
          MetacatReplication.replLog("" +DOCINSERTNUMBER + " Wrote data file" + accNumber +
509
                                       " into "+tableName + " from " +
510
                                           remoteserver);
511
          DOCINSERTNUMBER++;
512
        }
513
        else
514
        {
515
            MetacatReplication.replLog("" +REVINSERTNUMBER + " Wrote data file" + accNumber +
516
                    " into "+tableName + " from " +
517
                        remoteserver);
518
            REVINSERTNUMBER++;
519
        }
520
        String ip = getIpFromURL(u);
521
        EventLog.getInstance().log(ip, MetacatReplication.REPLICATIONUSER, accNumber, actions);
522
        
523
      }//if
524
      else
525
      {
526
         logMetacat.info("Couldn't open the data file: " + accNumber);
527
         throw new Exception("Couldn't open the data file: " + accNumber);
528
      }//else
529

    
530
    }//try
531
    catch(Exception e)
532
    {
533
      /*MetacatReplication.replErrorLog("Failed to try wrote datafile " + accNumber +
534
                                      " because " +e.getMessage());*/
535
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
536
      {
537
        MetacatReplication.replErrorLog("" +DOCERRORNUMBER + " Failed to write data file " + accNumber +
538
                                     " into "+tableName + " from " +
539
                                         remoteserver + " because "+e.getMessage());
540
        DOCERRORNUMBER++;
541
      }
542
      else
543
      {
544
          MetacatReplication.replErrorLog("" +REVERRORNUMBER + " Failed to write data file" + accNumber +
545
                  " into "+tableName + " from " +
546
                      remoteserver +" because "+e.getMessage());
547
          REVERRORNUMBER++;
548
      }
549
      logMetacat.error("Failed to try wrote datafile " + accNumber +
550
                                      " because " +e.getMessage());
551
      throw e;
552
    }
553
    finally
554
    {
555
       //return DBConnection
556
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
557
    }//finally
558
  }
559

    
560

    
561

    
562
  /* Handle delete single document*/
563
  private void handleDeleteSingleDocument(String docId, String notifyServer)
564
               throws Exception
565
  {
566
    logMetacat.info("Try delete doc: "+docId);
567
    DBConnection dbConn = null;
568
    int serialNumber = -1;
569
    try
570
    {
571
      // Get DBConnection from pool
572
      dbConn=DBConnectionPool.
573
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
574
      serialNumber=dbConn.getCheckOutSerialNumber();
575
      if(!alreadyDeleted(docId))
576
      {
577

    
578
         //because delete method docid should have rev number
579
         //so we just add one for it. This rev number is no sence.
580
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
581
         //System.out.println("accnum: "+accnum);
582
         DocumentImpl.delete(accnum, null, null, notifyServer);
583
         logMetacat.info("Successfully deleted doc " + docId);
584
         MetacatReplication.replLog("Doc " + docId + " deleted");
585
         URL u = new URL("https://"+notifyServer);
586
         String ip = getIpFromURL(u);
587
         EventLog.getInstance().log(ip, MetacatReplication.REPLICATIONUSER, docId, "delete");
588
      }
589

    
590
    }//try
591
    catch(Exception e)
592
    {
593
      MetacatReplication.replErrorLog("Failed to delete doc " + docId +
594
                                      " in db because " +e.getMessage());
595
      logMetacat.error("Failed to delete doc " + docId +
596
                                 " in db because because " + e.getMessage());
597
      throw e;
598
    }
599
    finally
600
    {
601
       //return DBConnection
602
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
603
    }//finally
604
  }
605

    
606
  /* Handle updateLastCheckTimForSingleServer*/
607
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
608
                                                  throws Exception
609
  {
610
    String server = repServer.getServerName();
611
    DBConnection dbConn = null;
612
    int serialNumber = -1;
613
    PreparedStatement pstmt = null;
614
    try
615
    {
616
      // Get DBConnection from pool
617
      dbConn=DBConnectionPool.
618
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
619
      serialNumber=dbConn.getCheckOutSerialNumber();
620

    
621
      logMetacat.info("Try to update last_check for server: "+server);
622
      // Get time from remote server
623
      URL dateurl = new URL("https://" + server + "?server="+
624
      MetaCatUtil.getLocalReplicationServerName()+"&action=gettime");
625
      String datexml = MetacatReplication.getURLContent(dateurl);
626
      logMetacat.info("datexml: "+datexml);
627
      if (datexml!=null && !datexml.equals(""))
628
      {
629
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
630
         StringBuffer sql = new StringBuffer();
631
         /*sql.append("update xml_replication set last_checked = to_date('");
632
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
633
         sql.append("server like '").append(server).append("'");*/
634
         sql.append("update xml_replication set last_checked = ");
635
         sql.append(DatabaseService.getDBAdapter().toDate(datestr, "MM/DD/YY HH24:MI:SS"));
636
         sql.append(" where server like '").append(server).append("'");
637
         pstmt = dbConn.prepareStatement(sql.toString());
638

    
639
         pstmt.executeUpdate();
640
         dbConn.commit();
641
         pstmt.close();
642
         logMetacat.info("last_checked updated to "+datestr+" on "
643
                                      + server);
644
      }//if
645
      else
646
      {
647

    
648
         logMetacat.info("Failed to update last_checked for server "  +
649
                                  server + " in db because couldn't get time "
650
                                  );
651
         throw new Exception("Couldn't get time for server "+ server);
652
      }
653

    
654
    }//try
655
    catch(Exception e)
656
    {
657

    
658
      logMetacat.error("Failed to update last_checked for server " +
659
                                server + " in db because because " +
660
                                e.getMessage());
661
      throw e;
662
    }
663
    finally
664
    {
665
       //return DBConnection
666
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
667
    }//finally
668
  }
669

    
670

    
671

    
672
  /**
673
   * updates xml_catalog with entries from other servers.
674
   */
675
  private void updateCatalog()
676
  {
677
    logMetacat.info("Start of updateCatalog");
678
    // ReplicationServer object in server list
679
    ReplicationServer replServer = null;
680
    PreparedStatement pstmt = null;
681
    String server = null;
682

    
683

    
684
    // Go through each ReplicationServer object in sererlist
685
    for (int j=0; j<serverList.size(); j++)
686
    {
687
      Vector remoteCatalog = new Vector();
688
      Vector publicId = new Vector();
689
      try
690
      {
691
        // Get ReplicationServer object from server list
692
        replServer = serverList.serverAt(j);
693
        // Get server name from the ReplicationServer object
694
        server = replServer.getServerName();
695
        // Try to get catalog
696
        URL u = new URL("https://" + server + "?server="+
697
        MetaCatUtil.getLocalReplicationServerName()+"&action=getcatalog");
698
        logMetacat.info("sending message " + u.toString());
699
        String catxml = MetacatReplication.getURLContent(u);
700

    
701
        // Make sure there are not error, no empty string
702
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
703
        {
704
          throw new Exception("Couldn't get catalog list form server " +server);
705
        }
706
        logMetacat.info("catxml: " + catxml);
707
        CatalogMessageHandler cmh = new CatalogMessageHandler();
708
        XMLReader catparser = initParser(cmh);
709
        catparser.parse(new InputSource(new StringReader(catxml)));
710
        //parse the returned catalog xml and put it into a vector
711
        remoteCatalog = cmh.getCatalogVect();
712

    
713
        // Makse sure remoteCatalog is not empty
714
        if (remoteCatalog.isEmpty())
715
        {
716
          throw new Exception("Couldn't get catalog list form server " +server);
717
        }
718

    
719
        String localcatxml = MetacatReplication.getCatalogXML();
720

    
721
        // Make sure local catalog is no empty
722
        if (localcatxml==null||localcatxml.equals(""))
723
        {
724
          throw new Exception("Couldn't get catalog list form server " +server);
725
        }
726

    
727
        cmh = new CatalogMessageHandler();
728
        catparser = initParser(cmh);
729
        catparser.parse(new InputSource(new StringReader(localcatxml)));
730
        Vector localCatalog = cmh.getCatalogVect();
731

    
732
        //now we have the catalog from the remote server and this local server
733
        //we now need to compare the two and merge the differences.
734
        //the comparison is base on the public_id fields which is the 4th
735
        //entry in each row vector.
736
        publicId = new Vector();
737
        for(int i=0; i<localCatalog.size(); i++)
738
        {
739
          Vector v = new Vector((Vector)localCatalog.elementAt(i));
740
          logMetacat.info("v1: " + v.toString());
741
          publicId.add(new String((String)v.elementAt(3)));
742
          //System.out.println("adding " + (String)v.elementAt(3));
743
        }
744
      }//try
745
      catch (Exception e)
746
      {
747
        MetacatReplication.replErrorLog("Failed to update catalog for server "+
748
                                    server + " because " +e.getMessage());
749
        logMetacat.error("Failed to update catalog for server "+
750
                                    server + " because " +e.getMessage());
751
      }//catch
752

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

    
810
  /**
811
   * Method that returns true if docid has already been "deleted" from metacat.
812
   * This method really implements a truth table for deleted documents
813
   * The table is (a docid in one of the tables is represented by the X):
814
   * xml_docs      xml_revs      deleted?
815
   * ------------------------------------
816
   *   X             X             FALSE
817
   *   X             _             FALSE
818
   *   _             X             TRUE
819
   *   _             _             TRUE
820
   */
821
  private static boolean alreadyDeleted(String docid) throws Exception
822
  {
823
    DBConnection dbConn = null;
824
    int serialNumber = -1;
825
    PreparedStatement pstmt = null;
826
    try
827
    {
828
      dbConn=DBConnectionPool.
829
                  getDBConnection("ReplicationHandler.alreadyDeleted");
830
      serialNumber=dbConn.getCheckOutSerialNumber();
831
      boolean xml_docs = false;
832
      boolean xml_revs = false;
833

    
834
      StringBuffer sb = new StringBuffer();
835
      sb.append("select docid from xml_revisions where docid like '");
836
      sb.append(docid).append("'");
837
      pstmt = dbConn.prepareStatement(sb.toString());
838
      pstmt.execute();
839
      ResultSet rs = pstmt.getResultSet();
840
      boolean tablehasrows = rs.next();
841
      if(tablehasrows)
842
      {
843
        xml_revs = true;
844
      }
845

    
846
      sb = new StringBuffer();
847
      sb.append("select docid from xml_documents where docid like '");
848
      sb.append(docid).append("'");
849
      pstmt.close();
850
      pstmt = dbConn.prepareStatement(sb.toString());
851
      //increase usage count
852
      dbConn.increaseUsageCount(1);
853
      pstmt.execute();
854
      rs = pstmt.getResultSet();
855
      tablehasrows = rs.next();
856
      pstmt.close();
857
      if(tablehasrows)
858
      {
859
        xml_docs = true;
860
      }
861

    
862
      if(xml_docs && xml_revs)
863
      {
864
        return false;
865
      }
866
      else if(xml_docs && !xml_revs)
867
      {
868
        return false;
869
      }
870
      else if(!xml_docs && xml_revs)
871
      {
872
        return true;
873
      }
874
      else if(!xml_docs && !xml_revs)
875
      {
876
        return true;
877
      }
878
    }
879
    catch(Exception e)
880
    {
881
      logMetacat.error("error in ReplicationHandler.alreadyDeleted: " +
882
                          e.getMessage());
883
      throw e;
884
    }
885
    finally
886
    {
887
      try
888
      {
889
        pstmt.close();
890
      }//try
891
      catch (SQLException ee)
892
      {
893
        logMetacat.error("Error in replicationHandler.alreadyDeleted "+
894
                          "to close pstmt: "+ee.getMessage());
895
        throw ee;
896
      }//catch
897
      finally
898
      {
899
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
900
      }//finally
901
    }//finally
902
    return false;
903
  }
904

    
905

    
906
  /**
907
   * Method to initialize the message parser
908
   */
909
  public static XMLReader initParser(DefaultHandler dh)
910
          throws Exception
911
  {
912
    XMLReader parser = null;
913

    
914
    try {
915
      ContentHandler chandler = dh;
916

    
917
      // Get an instance of the parser
918
      String parserName = PropertyService.getProperty("xml.saxparser");
919
      parser = XMLReaderFactory.createXMLReader(parserName);
920

    
921
      // Turn off validation
922
      parser.setFeature("http://xml.org/sax/features/validation", false);
923

    
924
      parser.setContentHandler((ContentHandler)chandler);
925
      parser.setErrorHandler((ErrorHandler)chandler);
926

    
927
    } catch (Exception e) {
928
      throw e;
929
    }
930

    
931
    return parser;
932
  }
933

    
934
  /**
935
   * This method will combinate given time string(in short format) to
936
   * current date. If the given time (e.g 10:00 AM) passed the current time
937
   * (e.g 2:00 PM Aug 21, 2005), then the time will set to second day,
938
   * 10:00 AM Aug 22, 2005. If the given time (e.g 10:00 AM) haven't passed
939
   * the current time (e.g 8:00 AM Aug 21, 2005) The time will set to be
940
   * 10:00 AM Aug 21, 2005.
941
   * @param givenTime  the format should be "10:00 AM " or "2:00 PM"
942
   * @return
943
   * @throws Exception
944
   */
945
  public static Date combinateCurrentDateAndGivenTime(String givenTime) throws Exception
946
  {
947
     Date givenDate = parseTime(givenTime);
948
     Date newDate = null;
949
     Date now = new Date();
950
     String currentTimeString = getTimeString(now);
951
     Date currentTime = parseTime(currentTimeString); 
952
     if ( currentTime.getTime() >= givenDate.getTime())
953
     {
954
        logMetacat.info("Today already pass the given time, we should set it as tomorrow");
955
        String dateAndTime = getDateString(now) + " " + givenTime;
956
        Date combinationDate = parseDateTime(dateAndTime);
957
        // new date should plus 24 hours to make is the second day
958
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
959
     }
960
     else
961
     {
962
         logMetacat.info("Today haven't pass the given time, we should it as today");
963
         String dateAndTime = getDateString(now) + " " + givenTime;
964
         newDate = parseDateTime(dateAndTime);
965
     }
966
     logMetacat.warn("final setting time is "+ newDate.toString());
967
     return newDate;
968
  }
969

    
970
  /*
971
   * parse a given string to Time in short format.
972
   * For example, given time is 10:00 AM, the date will be return as
973
   * Jan 1 1970, 10:00 AM
974
   */
975
  private static Date parseTime(String timeString) throws Exception
976
  {
977
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
978
    Date time = format.parse(timeString); 
979
    logMetacat.info("Date string is after parse a time string "
980
                              +time.toString());
981
    return time;
982

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

    
1055
			try {
1056
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1057
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1058
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1059
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1060
				} else {
1061
					continue;
1062
				}
1063

    
1064
			} catch (Exception e) {
1065
				logMetacat.error("error to handle update doc in " + tableName
1066
						+ " in time replication" + e.getMessage());
1067
				continue;
1068
			}
1069

    
1070
		}// for update docs
1071

    
1072
	}
1073
   
1074
   /*
1075
	 * This method will handle doc in xml_documents table.
1076
	 */
1077
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
1078
                                        throws Exception
1079
   {
1080
       // compare the update rev and local rev to see what need happen
1081
       int localrev = -1;
1082
       String action = null;
1083
       boolean flag = false;
1084
       try
1085
       {
1086
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1087
       }
1088
       catch (SQLException e)
1089
       {
1090
         logMetacat.error("Local rev for docid "+ docid + " could not "+
1091
                                " be found because " + e.getMessage());
1092
         MetacatReplication.replErrorLog(""+DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1093
                 "written because error happend to find it's local revision");
1094
         DOCERRORNUMBER++;
1095
         throw new Exception (e.getMessage());
1096
       }
1097
       logMetacat.info("Local rev for docid "+ docid + " is "+
1098
                               localrev);
1099

    
1100
       //check the revs for an update because this document is in the
1101
       //local DB, it might be out of date.
1102
       if (localrev == -1)
1103
       {
1104
          // check if the revision is in the revision table
1105
         Vector localRevVector = DBUtil.getRevListFromRevisionTable(docid);
1106
         if (localRevVector != null && localRevVector.contains(new Integer(rev)))
1107
         {
1108
             // this version was deleted, so don't need replicate
1109
             flag = false;
1110
         }
1111
         else
1112
         {
1113
           //insert this document as new because it is not in the local DB
1114
           action = "INSERT";
1115
           flag = true;
1116
         }
1117
       }
1118
       else
1119
       {
1120
         if(localrev == rev)
1121
         {
1122
           // Local meatacat has the same rev to remote host, don't need
1123
           // update and flag set false
1124
           flag = false;
1125
         }
1126
         else if(localrev < rev)
1127
         {
1128
           //this document needs to be updated so send an read request
1129
           action = "UPDATE";
1130
           flag = true;
1131
         }
1132
       }
1133
       
1134
       String accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1135
       // this is non-data file
1136
       if(flag && !dataFile)
1137
       {
1138
         try
1139
         {
1140
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1141
         }
1142
         catch(Exception e)
1143
         {
1144
           // skip this document
1145
           throw e;
1146
         }
1147
       }//if for non-data file
1148

    
1149
        // this is for data file
1150
       if(flag && dataFile)
1151
       {
1152
         try
1153
         {
1154
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1155
         }
1156
         catch(Exception e)
1157
         {
1158
           // skip this datafile
1159
           throw e;
1160
         }
1161

    
1162
       }//for datafile
1163
   }
1164
   
1165
   /*
1166
    * This method will handle doc in xml_documents table.
1167
    */
1168
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile) 
1169
                                        throws Exception
1170
   {
1171
       // compare the update rev and local rev to see what need happen
1172
       logMetacat.info("In handle repliation revsion table");
1173
       logMetacat.info("the docid is "+ docid);
1174
       logMetacat.info("The rev is "+rev);
1175
       Vector localrev = null;
1176
       String action = "INSERT";
1177
       boolean flag = false;
1178
       try
1179
       {
1180
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1181
       }
1182
       catch (SQLException e)
1183
       {
1184
         logMetacat.error("Local rev for docid "+ docid + " could not "+
1185
                                " be found because " + e.getMessage());
1186
         MetacatReplication.replErrorLog(""+REVERRORNUMBER+" Docid "+ docid + " could not be "+
1187
                 "written because error happend to find it's local revision");
1188
         REVERRORNUMBER++;
1189
         throw new Exception (e.getMessage());
1190
       }
1191
       logMetacat.info("rev list in xml_revision table for docid "+ docid + " is "+
1192
                               localrev.toString());
1193
       
1194
       // if the rev is not in the xml_revision, we need insert it
1195
       if (!localrev.contains(new Integer(rev)))
1196
       {
1197
           flag = true;    
1198
       }
1199
     
1200
       String accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1201
       // this is non-data file
1202
       if(flag && !dataFile)
1203
       {
1204
         try
1205
         {
1206
           
1207
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1208
         }
1209
         catch(Exception e)
1210
         {
1211
           // skip this document
1212
           throw e;
1213
         }
1214
       }//if for non-data file
1215

    
1216
        // this is for data file
1217
       if(flag && dataFile)
1218
       {
1219
         try
1220
         {
1221
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1222
         }
1223
         catch(Exception e)
1224
         {
1225
           // skip this datafile
1226
           throw e;
1227
         }
1228

    
1229
       }//for datafile
1230
   }
1231
   
1232
   /*
1233
    * Return a ip address for given url
1234
    */
1235
   private String getIpFromURL(URL url)
1236
   {
1237
	   String ip = null;
1238
	   try
1239
	   {
1240
	      InetAddress address = InetAddress.getByName(url.getHost());
1241
	      ip = address.getHostAddress();
1242
	   }
1243
	   catch(UnknownHostException e)
1244
	   {
1245
		   logMetacat.error("Error in get ip address for host: "
1246
                   +e.getMessage());
1247
	   }
1248

    
1249
	   return ip;
1250
   }
1251
  
1252
}
1253

    
(60-60/67)