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: berkley $'
9
 *     '$Date: 2010-07-22 12:32:09 -0700 (Thu, 22 Jul 2010) $'
10
 * '$Revision: 5440 $'
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.replication;
28

    
29
import edu.ucsb.nceas.metacat.CatalogMessageHandler;
30
import edu.ucsb.nceas.metacat.DBUtil;
31
import edu.ucsb.nceas.metacat.DocInfoHandler;
32
import edu.ucsb.nceas.metacat.DocumentImpl;
33
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
34
import edu.ucsb.nceas.metacat.EventLog;
35
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
36
import edu.ucsb.nceas.metacat.accesscontrol.XMLAccessDAO;
37
import edu.ucsb.nceas.metacat.database.DBConnection;
38
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
39
import edu.ucsb.nceas.metacat.database.DatabaseService;
40
import edu.ucsb.nceas.metacat.properties.PropertyService;
41
import edu.ucsb.nceas.metacat.shared.HandlerException;
42
import edu.ucsb.nceas.metacat.util.MetacatUtil;
43
import edu.ucsb.nceas.metacat.IdentifierManager;
44
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
45

    
46
import java.sql.*;
47
import java.util.*;
48
import java.util.Date;
49
import java.io.*;
50
import java.net.*;
51
import java.text.*;
52

    
53
import org.apache.log4j.Logger;
54
import org.xml.sax.ContentHandler;
55
import org.xml.sax.ErrorHandler;
56
import org.xml.sax.InputSource;
57
import org.xml.sax.SAXException;
58
import org.xml.sax.XMLReader;
59
import org.xml.sax.helpers.XMLReaderFactory;
60
import org.xml.sax.helpers.DefaultHandler;
61

    
62

    
63

    
64
/**
65
 * This class handles deltaT replication checking.  Whenever this TimerTask
66
 * is fired it checks each server in xml_replication for updates and updates
67
 * the local db as needed.
68
 */
69
public class ReplicationHandler extends TimerTask
70
{
71
  int serverCheckCode = 1;
72
  ReplicationServerList serverList = null;
73
  //PrintWriter out;
74
//  private static final AbstractDatabase dbAdapter = MetacatUtil.dbAdapter;
75
  private static Logger logReplication = Logger.getLogger("ReplicationLogging");
76
  private static Logger logMetacat = Logger.getLogger(ReplicationHandler.class);
77
  private static Logger logD1 = Logger.getLogger("DataOneLogger");
78
  
79
  private static int DOCINSERTNUMBER = 1;
80
  private static int DOCERRORNUMBER  = 1;
81
  private static int REVINSERTNUMBER = 1;
82
  private static int REVERRORNUMBER  = 1;
83
  
84
  private static int _xmlDocQueryCount = 0;
85
  private static int _xmlRevQueryCount = 0;
86
  private static long _xmlDocQueryTime = 0;
87
  private static long _xmlRevQueryTime = 0;
88
  
89
  
90
  public ReplicationHandler()
91
  {
92
    //this.out = o;
93
    serverList = new ReplicationServerList();
94
  }
95

    
96
  public ReplicationHandler(int serverCheckCode)
97
  {
98
    //this.out = o;
99
    this.serverCheckCode = serverCheckCode;
100
    serverList = new ReplicationServerList();
101
  }
102

    
103
  /**
104
   * Method that implements TimerTask.run().  It runs whenever the timer is
105
   * fired.
106
   */
107
  public void run()
108
  {
109
    //find out the last_checked time of each server in the server list and
110
    //send a query to each server to see if there are any documents in
111
    //xml_documents with an update_date > last_checked
112
	  
113
      //if serverList is null, metacat don't need to replication
114
      if (serverList==null||serverList.isEmpty())
115
      {
116
        return;
117
      }
118
      updateCatalog();
119
      update();
120
      //conn.close();
121
  }
122

    
123
  /**
124
   * Method that uses revision tagging for replication instead of update_date.
125
   */
126
  private void update()
127
  {
128
	  
129
	  _xmlDocQueryCount = 0;
130
	  _xmlRevQueryCount = 0;
131
	  _xmlDocQueryTime = 0;
132
	  _xmlRevQueryTime = 0;
133
    /*
134
     Pseudo-algorithm
135
     - request a doc list from each server in xml_replication
136
     - check the rev number of each of those documents agains the
137
       documents in the local database
138
     - pull any documents that have a lesser rev number on the local server
139
       from the remote server
140
     - delete any documents that still exist in the local xml_documents but
141
       are in the deletedDocuments tag of the remote host response.
142
     - update last_checked to keep track of the last time it was checked.
143
       (this info is theoretically not needed using this system but probably
144
       should be kept anyway)
145
    */
146

    
147
    ReplicationServer replServer = null; // Variable to store the
148
                                        // ReplicationServer got from
149
                                        // Server list
150
    String server = null; // Variable to store server name
151
//    String update;
152
    Vector<String> responses = new Vector<String>();
153
    URL u;
154
    long replicationStartTime = System.currentTimeMillis();
155
    long timeToGetServerList = 0;
156
    
157
    //Check for every server in server list to get updated list and put
158
    // them in to response
159
    long startTimeToGetServers = System.currentTimeMillis();
160
    for (int i=0; i<serverList.size(); i++)
161
    {
162
        // Get ReplicationServer object from server list
163
        replServer = serverList.serverAt(i);
164
        // Get server name from ReplicationServer object
165
        server = replServer.getServerName().trim();
166
        String result = null;
167
        logReplication.info("ReplicationHandler.update - full update started to: " + server);
168
        // Send command to that server to get updated docid information
169
        try
170
        {
171
          u = new URL("https://" + server + "?server="
172
          +MetacatUtil.getLocalReplicationServerName()+"&action=update");
173
          logReplication.info("ReplicationHandler.update - Sending infomation " +u.toString());
174
          result = ReplicationService.getURLContent(u);
175
        }
176
        catch (Exception e)
177
        {
178
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
179
          logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
180
                       "for server " + server + " because "+e.getMessage());
181
          continue;
182
        }
183

    
184
        //logReplication.info("ReplicationHandler.update - docid: "+server+" "+result);
185
        //check if result have error or not, if has skip it.
186
        if (result.indexOf("<error>")!=-1 && result.indexOf("</error>")!=-1)
187
        {
188
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
189
          logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
190
                       "for server " + server + " because "+result);
191
          continue;
192
        }
193
        //Add result to vector
194
        responses.add(result);
195
    }
196
    timeToGetServerList = System.currentTimeMillis() - startTimeToGetServers;
197

    
198
    //make sure that there is updated file list
199
    //If response is null, metacat don't need do anything
200
    if (responses==null || responses.isEmpty())
201
    {
202
    	logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
203
        logReplication.info( "ReplicationHandler.update - No updated doc list for "+
204
                           "every server and failed to replicate");
205
        return;
206
    }
207

    
208

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

    
284
    //updated last_checked
285
    for (int i=0;i<serverList.size(); i++)
286
    {
287
       // Get ReplicationServer object from server list
288
       replServer = serverList.serverAt(i);
289
       try
290
       {
291
         updateLastCheckTimeForSingleServer(replServer);
292
       }
293
       catch(Exception e)
294
       {
295
         continue;
296
       }
297
    }//for
298
    
299
    long replicationEndTime = System.currentTimeMillis();
300
    logMetacat.debug("ReplicationHandler.update - Total replication time: " + 
301
    		(replicationEndTime - replicationStartTime));
302
    logMetacat.debug("ReplicationHandler.update - time to get server list: " + 
303
    		timeToGetServerList);
304
    logMetacat.debug("ReplicationHandler.update - server list parse time: " + 
305
    		totalServerListParseTime);
306
    logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query count: " + 
307
    		_xmlDocQueryCount);
308
    logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query time: " + 
309
    		_xmlDocQueryTime + " ms");
310
    logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query count: " + 
311
    		_xmlRevQueryCount);
312
    logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query time: " + 
313
    		_xmlRevQueryTime + " ms");;
314

    
315
  }//update
316

    
317
  /* Handle replicate single xml document*/
318
  private void handleSingleXMLDocument(String remoteserver, String actions,
319
                                       String accNumber, String tableName)
320
               throws HandlerException
321
  {
322
    DBConnection dbConn = null;
323
    int serialNumber = -1;
324
    try
325
    {
326
      // Get DBConnection from pool
327
      dbConn=DBConnectionPool.
328
                  getDBConnection("ReplicationHandler.handleSingleXMLDocument");
329
      serialNumber=dbConn.getCheckOutSerialNumber();
330
      //if the document needs to be updated or inserted, this is executed
331
      String readDocURLString = "https://" + remoteserver + "?server="+
332
              MetacatUtil.getLocalReplicationServerName()+"&action=read&docid="+accNumber;
333
      readDocURLString = MetacatUtil.replaceWhiteSpaceForURL(readDocURLString);
334
      URL u = new URL(readDocURLString);
335

    
336
      // Get docid content
337
      String newxmldoc = ReplicationService.getURLContent(u);
338
      // If couldn't get skip it
339
      if ( newxmldoc.indexOf("<error>")!= -1 && newxmldoc.indexOf("</error>")!=-1)
340
      {
341
         throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - " + newxmldoc);
342
      }
343
      //logReplication.info("xml documnet:");
344
      //logReplication.info(newxmldoc);
345

    
346
      // Try get the docid info from remote server
347
      DocInfoHandler dih = new DocInfoHandler();
348
      XMLReader docinfoParser = initParser(dih);
349
      String docInfoURLStr = "https://" + remoteserver +
350
                       "?server="+MetacatUtil.getLocalReplicationServerName()+
351
                       "&action=getdocumentinfo&docid="+accNumber;
352
      docInfoURLStr = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLStr);
353
      URL docinfoUrl = new URL(docInfoURLStr);
354
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Sending message: " +
355
                                                  docinfoUrl.toString());
356
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
357
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
358
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
359
      // Get home server of the docid
360
      String docHomeServer = docinfoHash.get("home_server");
361
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doc home server in repl: "+docHomeServer);
362
      String createdDate = docinfoHash.get("date_created");
363
      String updatedDate = docinfoHash.get("date_updated");
364
      //docid should include rev number too
365
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
366
                                              (String)docinfoHash.get("rev");*/
367
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - docid in repl: "+accNumber);
368
      String docType = docinfoHash.get("doctype");
369
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doctype in repl: "+docType);
370

    
371
      String parserBase = null;
372
      // this for eml2 and we need user eml2 parser
373
      if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
374
      {
375
         parserBase = DocumentImpl.EML200;
376
      }
377
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
378
      {
379
        parserBase = DocumentImpl.EML200;
380
      }
381
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
382
      {
383
        parserBase = DocumentImpl.EML210;
384
      }
385
      // Write the document into local host
386
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
387
      String newDocid = wrapper.writeReplication(dbConn,
388
                              newxmldoc,
389
                              docinfoHash.get("public_access"),
390
                              null,  /* the dtd text */
391
                              actions,
392
                              accNumber,
393
                              docinfoHash.get("user_owner"),
394
                              null, /* null for groups[] */
395
                              docHomeServer,
396
                              remoteserver, tableName, true,// true is for time replication 
397
                              createdDate,
398
                              updatedDate);
399
      
400
      //process extra access rules 
401
      Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
402
      if (xmlAccessDAOList != null) {
403
      	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
404
      	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
405
      		if (!acfsf.accessControlExists(xmlAccessDAO)) {
406
      			acfsf.insertPermissions(xmlAccessDAO);
407
      		}
408
          }
409
      }
410
      
411
      //process guid
412
      logReplication.debug("Processing guid information from docinfoHash: " + docinfoHash.toString());
413
      String guid = docinfoHash.get("guid");
414
      System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%guid passed from docinfo hash: " + guid);
415
      IdentifierManager idman = IdentifierManager.getInstance();
416
      if(guid != null && !idman.identifierExists(guid))
417
      { //if the guid was passed in, put it in the identifiers table
418
        logReplication.debug("Creating guid/docid mapping for docid " + 
419
          docinfoHash.get("docid") + " and guid: " + guid);
420
        idman.createMapping(guid, docinfoHash.get("docid"));
421
      }
422
      else
423
      {
424
        logReplication.debug("No guid information was included with the replicated document");
425
      }
426
      
427
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Successfully replicated doc " + accNumber);
428
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
429
      {
430
        logReplication.info("ReplicationHandler.handleSingleXMLDocument - " + DOCINSERTNUMBER + " Wrote xml doc " + accNumber +
431
                                     " into "+tableName + " from " +
432
                                         remoteserver);
433
        DOCINSERTNUMBER++;
434
      }
435
      else
436
      {
437
          logReplication.info("ReplicationHandler.handleSingleXMLDocument - " +REVINSERTNUMBER + " Wrote xml doc " + accNumber +
438
                  " into "+tableName + " from " +
439
                      remoteserver);
440
          REVINSERTNUMBER++;
441
      }
442
      String ip = getIpFromURL(u);
443
      EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, accNumber, actions);
444
      
445

    
446
    }//try
447
    catch(Exception e)
448
    {
449
        
450
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
451
        {
452
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
453
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
454
                                       " into "+tableName + " from " +
455
                                           remoteserver + " because "+e.getMessage());
456
          DOCERRORNUMBER++;
457
        }
458
        else
459
        {
460
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
461
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
462
                    " into "+tableName + " from " +
463
                        remoteserver +" because "+e.getMessage());
464
            REVERRORNUMBER++;
465
        }
466
        logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
467
        logReplication.error("ReplicationHandler.handleSingleXMLDocument - Failed to write doc " + accNumber +
468
                                      " into db because " +e.getMessage());
469
      throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - generic exception " 
470
    		  + "writing Replication: " +e.getMessage());
471
    }
472
    finally
473
    {
474
       //return DBConnection
475
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
476
    }//finally
477
    logD1.info("replication.create localId:" + accNumber);
478
  }
479

    
480

    
481

    
482
  /* Handle replicate single xml document*/
483
  private void handleSingleDataFile(String remoteserver, String actions,
484
                                    String accNumber, String tableName)
485
               throws HandlerException
486
  {
487
    logReplication.info("ReplicationHandler.handleSingleDataFile - Try to replicate data file: " + accNumber);
488
    DBConnection dbConn = null;
489
    int serialNumber = -1;
490
    try
491
    {
492
      // Get DBConnection from pool
493
      dbConn=DBConnectionPool.
494
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
495
      serialNumber=dbConn.getCheckOutSerialNumber();
496
      // Try get docid info from remote server
497
      DocInfoHandler dih = new DocInfoHandler();
498
      XMLReader docinfoParser = initParser(dih);
499
      String docInfoURLString = "https://" + remoteserver +
500
                  "?server="+MetacatUtil.getLocalReplicationServerName()+
501
                  "&action=getdocumentinfo&docid="+accNumber;
502
      docInfoURLString = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLString);
503
      URL docinfoUrl = new URL(docInfoURLString);
504

    
505
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
506
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
507
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
508
      // Get docid owner
509
      String user = docinfoHash.get("user_owner");
510
      // Get docid name (such as acl or dataset)
511
      String docName = docinfoHash.get("docname");
512
      // Get doc type (eml public id)
513
      String docType = docinfoHash.get("doctype");
514
      // Get docid home sever. it might be different to remoteserver
515
      // because of hub feature
516
      String docHomeServer = docinfoHash.get("home_server");
517
      String createdDate = docinfoHash.get("date_created");
518
      String updatedDate = docinfoHash.get("date_updated");
519
      //docid should include rev number too
520
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
521
                                              (String)docinfoHash.get("rev");*/
522

    
523

    
524
      String datafilePath = PropertyService.getProperty("application.datafilepath");
525
      // Get data file content
526
      String readDataURLString = "https://" + remoteserver + "?server="+
527
                                        MetacatUtil.getLocalReplicationServerName()+
528
                                            "&action=readdata&docid="+accNumber;
529
      readDataURLString = MetacatUtil.replaceWhiteSpaceForURL(readDataURLString);
530
      URL u = new URL(readDataURLString);
531
      InputStream input = u.openStream();
532
      //register data file into xml_documents table and wite data file
533
      //into file system
534
      if ( input != null)
535
      {
536
        DocumentImpl.writeDataFileInReplication(input,
537
                                                datafilePath,
538
                                                docName,docType,
539
                                                accNumber, user,
540
                                                docHomeServer,
541
                                                remoteserver,
542
                                                tableName,
543
                                                true, //true means timed replication
544
                                                createdDate,
545
                                                updatedDate);
546
                                         
547
        //process extra access rules
548
        Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
549
        if (xmlAccessDAOList != null) {
550
        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
551
        	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
552
        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
553
        			acfsf.insertPermissions(xmlAccessDAO);
554
        		}
555
            }
556
        }
557
        
558
        logReplication.info("ReplicationHandler.handleSingleDataFile - Successfully to write datafile " + accNumber);
559
        /*MetacatReplication.replLog("wrote datafile " + accNumber + " from " +
560
                                    remote server);*/
561
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
562
        {
563
          logReplication.info("ReplicationHandler.handleSingleDataFile - " + DOCINSERTNUMBER + " Wrote data file" + accNumber +
564
                                       " into "+tableName + " from " +
565
                                           remoteserver);
566
          DOCINSERTNUMBER++;
567
        }
568
        else
569
        {
570
            logReplication.info("ReplicationHandler.handleSingleDataFile - " + REVINSERTNUMBER + " Wrote data file" + accNumber +
571
                    " into "+tableName + " from " +
572
                        remoteserver);
573
            REVINSERTNUMBER++;
574
        }
575
        String ip = getIpFromURL(u);
576
        EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, accNumber, actions);
577
        
578
      }//if
579
      else
580
      {
581
         logReplication.info("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
582
         throw new HandlerException("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
583
      }//else
584

    
585
    }//try
586
    catch(Exception e)
587
    {
588
      /*MetacatReplication.replErrorLog("Failed to try wrote data file " + accNumber +
589
                                      " because " +e.getMessage());*/
590
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
591
      {
592
    	logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
593
    	logReplication.error("ReplicationHandler.handleSingleDataFile - " + DOCERRORNUMBER + " Failed to write data file " + accNumber +
594
                                     " into " + tableName + " from " +
595
                                         remoteserver + " because " + e.getMessage());
596
        DOCERRORNUMBER++;
597
      }
598
      else
599
      {
600
    	  logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
601
    	  logReplication.error("ReplicationHandler.handleSingleDataFile - " + REVERRORNUMBER + " Failed to write data file" + accNumber +
602
                  " into " + tableName + " from " +
603
                      remoteserver +" because "+ e.getMessage());
604
          REVERRORNUMBER++;
605
      }
606
      logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
607
      logReplication.error("ReplicationHandler.handleSingleDataFile - Failed to try wrote datafile " + accNumber +
608
                                      " because " + e.getMessage());
609
      throw new HandlerException("ReplicationHandler.handleSingleDataFile - generic exception " 
610
    		  + "writing Replication: " + e.getMessage());
611
    }
612
    finally
613
    {
614
       //return DBConnection
615
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
616
    }//finally
617
    logD1.info("replication.create localId:" + accNumber);
618
  }
619

    
620

    
621

    
622
  /* Handle delete single document*/
623
  private void handleDeleteSingleDocument(String docId, String notifyServer)
624
               throws HandlerException
625
  {
626
    logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Try delete doc: "+docId);
627
    DBConnection dbConn = null;
628
    int serialNumber = -1;
629
    try
630
    {
631
      // Get DBConnection from pool
632
      dbConn=DBConnectionPool.
633
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
634
      serialNumber=dbConn.getCheckOutSerialNumber();
635
      if(!alreadyDeleted(docId))
636
      {
637

    
638
         //because delete method docid should have rev number
639
         //so we just add one for it. This rev number is no sence.
640
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
641
         //System.out.println("accnum: "+accnum);
642
         DocumentImpl.delete(accnum, null, null, notifyServer);
643
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Successfully deleted doc " + docId);
644
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Doc " + docId + " deleted");
645
         URL u = new URL("https://"+notifyServer);
646
         String ip = getIpFromURL(u);
647
         EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, docId, "delete");
648
      }
649

    
650
    }//try
651
    catch(Exception e)
652
    {
653
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
654
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
655
                                 " in db because because " + e.getMessage());
656
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
657
    		  + "when handling document: " + e.getMessage());
658
    }
659
    finally
660
    {
661
       //return DBConnection
662
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
663
    }//finally
664
    logD1.info("replication.handleDeleteSingleDocument localId:" + docId);
665
  }
666

    
667
  /* Handle updateLastCheckTimForSingleServer*/
668
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
669
                                                  throws HandlerException
670
  {
671
    String server = repServer.getServerName();
672
    DBConnection dbConn = null;
673
    int serialNumber = -1;
674
    PreparedStatement pstmt = null;
675
    try
676
    {
677
      // Get DBConnection from pool
678
      dbConn=DBConnectionPool.
679
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
680
      serialNumber=dbConn.getCheckOutSerialNumber();
681

    
682
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Try to update last_check for server: "+server);
683
      // Get time from remote server
684
      URL dateurl = new URL("https://" + server + "?server="+
685
      MetacatUtil.getLocalReplicationServerName()+"&action=gettime");
686
      String datexml = ReplicationService.getURLContent(dateurl);
687
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - datexml: "+datexml);
688
      if (datexml!=null && !datexml.equals(""))
689
      {
690
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
691
         StringBuffer sql = new StringBuffer();
692
         /*sql.append("update xml_replication set last_checked = to_date('");
693
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
694
         sql.append("server like '").append(server).append("'");*/
695
         sql.append("update xml_replication set last_checked = ");
696
         sql.append(DatabaseService.getInstance().getDBAdapter().toDate(datestr, "MM/DD/YY HH24:MI:SS"));
697
         sql.append(" where server like '").append(server).append("'");
698
         pstmt = dbConn.prepareStatement(sql.toString());
699

    
700
         pstmt.executeUpdate();
701
         dbConn.commit();
702
         pstmt.close();
703
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - last_checked updated to "+datestr+" on "
704
                                      + server);
705
      }//if
706
      else
707
      {
708

    
709
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server "  +
710
                                  server + " in db because couldn't get time "
711
                                  );
712
         throw new Exception("Couldn't get time for server "+ server);
713
      }
714

    
715
    }//try
716
    catch(Exception e)
717
    {
718
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
719
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
720
                                server + " in db because because " + e.getMessage());
721
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - " 
722
    		  + "Error updating last checked time: " + e.getMessage());
723
    }
724
    finally
725
    {
726
       //return DBConnection
727
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
728
    }//finally
729
  }
730

    
731

    
732

    
733
  /**
734
   * updates xml_catalog with entries from other servers.
735
   */
736
  private void updateCatalog()
737
  {
738
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
739
    // ReplicationServer object in server list
740
    ReplicationServer replServer = null;
741
    PreparedStatement pstmt = null;
742
    String server = null;
743

    
744

    
745
    // Go through each ReplicationServer object in sererlist
746
    for (int j=0; j<serverList.size(); j++)
747
    {
748
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
749
      Vector<String> publicId = new Vector<String>();
750
      try
751
      {
752
        // Get ReplicationServer object from server list
753
        replServer = serverList.serverAt(j);
754
        // Get server name from the ReplicationServer object
755
        server = replServer.getServerName();
756
        // Try to get catalog
757
        URL u = new URL("https://" + server + "?server="+
758
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
759
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
760
        String catxml = ReplicationService.getURLContent(u);
761

    
762
        // Make sure there are not error, no empty string
763
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
764
        {
765
          throw new Exception("Couldn't get catalog list form server " +server);
766
        }
767
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
768
        CatalogMessageHandler cmh = new CatalogMessageHandler();
769
        XMLReader catparser = initParser(cmh);
770
        catparser.parse(new InputSource(new StringReader(catxml)));
771
        //parse the returned catalog xml and put it into a vector
772
        remoteCatalog = cmh.getCatalogVect();
773

    
774
        // Make sure remoteCatalog is not empty
775
        if (remoteCatalog.isEmpty())
776
        {
777
          throw new Exception("Couldn't get catalog list form server " +server);
778
        }
779

    
780
        String localcatxml = ReplicationService.getCatalogXML();
781

    
782
        // Make sure local catalog is no empty
783
        if (localcatxml==null||localcatxml.equals(""))
784
        {
785
          throw new Exception("Couldn't get catalog list form server " +server);
786
        }
787

    
788
        cmh = new CatalogMessageHandler();
789
        catparser = initParser(cmh);
790
        catparser.parse(new InputSource(new StringReader(localcatxml)));
791
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
792

    
793
        //now we have the catalog from the remote server and this local server
794
        //we now need to compare the two and merge the differences.
795
        //the comparison is base on the public_id fields which is the 4th
796
        //entry in each row vector.
797
        publicId = new Vector<String>();
798
        for(int i=0; i<localCatalog.size(); i++)
799
        {
800
          Vector<String> v = new Vector<String>(localCatalog.elementAt(i));
801
          logReplication.info("ReplicationHandler.updateCatalog - v1: " + v.toString());
802
          publicId.add(new String((String)v.elementAt(3)));
803
          //System.out.println("adding " + (String)v.elementAt(3));
804
        }
805
      }//try
806
      catch (Exception e)
807
      {
808
        logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
809
        logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
810
                                    server + " because " +e.getMessage());
811
      }//catch
812

    
813
      for(int i=0; i<remoteCatalog.size(); i++)
814
      {
815
         // DConnection
816
        DBConnection dbConn = null;
817
        // DBConnection checkout serial number
818
        int serialNumber = -1;
819
        try
820
        {
821
            dbConn=DBConnectionPool.
822
                  getDBConnection("ReplicationHandler.updateCatalog");
823
            serialNumber=dbConn.getCheckOutSerialNumber();
824
            Vector<String> v = remoteCatalog.elementAt(i);
825
            //System.out.println("v2: " + v.toString());
826
            //System.out.println("i: " + i);
827
            //System.out.println("remoteCatalog.size(): " + remoteCatalog.size());
828
            //System.out.println("publicID: " + publicId.toString());
829
            logReplication.info
830
                              ("ReplicationHandler.updateCatalog - v.elementAt(3): " + (String)v.elementAt(3));
831
           if(!publicId.contains(v.elementAt(3)))
832
           { //so we don't have this public id in our local table so we need to
833
             //add it.
834
             //System.out.println("in if");
835
             StringBuffer sql = new StringBuffer();
836
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
837
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
838
             sql.append("?,?)");
839
             //System.out.println("sql: " + sql.toString());
840
             pstmt = dbConn.prepareStatement(sql.toString());
841
             pstmt.setString(1, (String)v.elementAt(0));
842
             pstmt.setString(2, (String)v.elementAt(1));
843
             pstmt.setString(3, (String)v.elementAt(2));
844
             pstmt.setString(4, (String)v.elementAt(3));
845
             pstmt.setString(5, (String)v.elementAt(4));
846
             pstmt.execute();
847
             pstmt.close();
848
             logReplication.info("ReplicationHandler.updateCatalog - Success fully to insert new publicid "+
849
                               (String)v.elementAt(3) + " from server"+server);
850
           }
851
        }
852
        catch(Exception e)
853
        {
854
           logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
855
           logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
856
                                    server + " because " +e.getMessage());
857
        }//catch
858
        finally
859
        {
860
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
861
        }//finally
862
      }//for remote catalog
863
    }//for server list
864
    logReplication.info("End of updateCatalog");
865
  }
866

    
867
  /**
868
   * Method that returns true if docid has already been "deleted" from metacat.
869
   * This method really implements a truth table for deleted documents
870
   * The table is (a docid in one of the tables is represented by the X):
871
   * xml_docs      xml_revs      deleted?
872
   * ------------------------------------
873
   *   X             X             FALSE
874
   *   X             _             FALSE
875
   *   _             X             TRUE
876
   *   _             _             TRUE
877
   */
878
  private static boolean alreadyDeleted(String docid) throws HandlerException
879
  {
880
    DBConnection dbConn = null;
881
    int serialNumber = -1;
882
    PreparedStatement pstmt = null;
883
    try
884
    {
885
      dbConn=DBConnectionPool.
886
                  getDBConnection("ReplicationHandler.alreadyDeleted");
887
      serialNumber=dbConn.getCheckOutSerialNumber();
888
      boolean xml_docs = false;
889
      boolean xml_revs = false;
890

    
891
      StringBuffer sb = new StringBuffer();
892
      sb.append("select docid from xml_revisions where docid like '");
893
      sb.append(docid).append("'");
894
      pstmt = dbConn.prepareStatement(sb.toString());
895
      pstmt.execute();
896
      ResultSet rs = pstmt.getResultSet();
897
      boolean tablehasrows = rs.next();
898
      if(tablehasrows)
899
      {
900
        xml_revs = true;
901
      }
902

    
903
      sb = new StringBuffer();
904
      sb.append("select docid from xml_documents where docid like '");
905
      sb.append(docid).append("'");
906
      pstmt.close();
907
      pstmt = dbConn.prepareStatement(sb.toString());
908
      //increase usage count
909
      dbConn.increaseUsageCount(1);
910
      pstmt.execute();
911
      rs = pstmt.getResultSet();
912
      tablehasrows = rs.next();
913
      pstmt.close();
914
      if(tablehasrows)
915
      {
916
        xml_docs = true;
917
      }
918

    
919
      if(xml_docs && xml_revs)
920
      {
921
        return false;
922
      }
923
      else if(xml_docs && !xml_revs)
924
      {
925
        return false;
926
      }
927
      else if(!xml_docs && xml_revs)
928
      {
929
        return true;
930
      }
931
      else if(!xml_docs && !xml_revs)
932
      {
933
        return true;
934
      }
935
    }
936
    catch(Exception e)
937
    {
938
      logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
939
      logReplication.error("ReplicationHandler.alreadyDeleted - general error in alreadyDeleted: " +
940
                          e.getMessage());
941
      throw new HandlerException("ReplicationHandler.alreadyDeleted - general error: " 
942
    		  + e.getMessage());
943
    }
944
    finally
945
    {
946
      try
947
      {
948
        pstmt.close();
949
      }//try
950
      catch (SQLException ee)
951
      {
952
    	logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
953
        logReplication.error("ReplicationHandler.alreadyDeleted - Error in replicationHandler.alreadyDeleted "+
954
                          "to close pstmt: "+ee.getMessage());
955
        throw new HandlerException("ReplicationHandler.alreadyDeleted - SQL error when closing prepared statement: " 
956
      		  + ee.getMessage());
957
      }//catch
958
      finally
959
      {
960
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
961
      }//finally
962
    }//finally
963
    return false;
964
  }
965

    
966

    
967
  /**
968
   * Method to initialize the message parser
969
   */
970
  public static XMLReader initParser(DefaultHandler dh)
971
          throws HandlerException
972
  {
973
    XMLReader parser = null;
974

    
975
    try {
976
      ContentHandler chandler = dh;
977

    
978
      // Get an instance of the parser
979
      String parserName = PropertyService.getProperty("xml.saxparser");
980
      parser = XMLReaderFactory.createXMLReader(parserName);
981

    
982
      // Turn off validation
983
      parser.setFeature("http://xml.org/sax/features/validation", false);
984

    
985
      parser.setContentHandler((ContentHandler)chandler);
986
      parser.setErrorHandler((ErrorHandler)chandler);
987

    
988
    } catch (SAXException se) {
989
      throw new HandlerException("ReplicationHandler.initParser - Sax error when " 
990
    		  + " initializing parser: " + se.getMessage());
991
    } catch (PropertyNotFoundException pnfe) {
992
        throw new HandlerException("ReplicationHandler.initParser - Property error when " 
993
      		  + " getting parser name: " + pnfe.getMessage());
994
    } 
995

    
996
    return parser;
997
  }
998

    
999
  /**
1000
	 * This method will combine given time string(in short format) to current
1001
	 * date. If the given time (e.g 10:00 AM) passed the current time (e.g 2:00
1002
	 * PM Aug 21, 2005), then the time will set to second day, 10:00 AM Aug 22,
1003
	 * 2005. If the given time (e.g 10:00 AM) haven't passed the current time
1004
	 * (e.g 8:00 AM Aug 21, 2005) The time will set to be 10:00 AM Aug 21, 2005.
1005
	 * 
1006
	 * @param givenTime
1007
	 *            the format should be "10:00 AM " or "2:00 PM"
1008
	 * @return
1009
	 * @throws Exception
1010
	 */
1011
	public static Date combinateCurrentDateAndGivenTime(String givenTime) throws HandlerException
1012
  {
1013
	  try {
1014
     Date givenDate = parseTime(givenTime);
1015
     Date newDate = null;
1016
     Date now = new Date();
1017
     String currentTimeString = getTimeString(now);
1018
     Date currentTime = parseTime(currentTimeString); 
1019
     if ( currentTime.getTime() >= givenDate.getTime())
1020
     {
1021
        logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today already pass the given time, we should set it as tomorrow");
1022
        String dateAndTime = getDateString(now) + " " + givenTime;
1023
        Date combinationDate = parseDateTime(dateAndTime);
1024
        // new date should plus 24 hours to make is the second day
1025
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
1026
     }
1027
     else
1028
     {
1029
         logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today haven't pass the given time, we should it as today");
1030
         String dateAndTime = getDateString(now) + " " + givenTime;
1031
         newDate = parseDateTime(dateAndTime);
1032
     }
1033
     logReplication.warn("ReplicationHandler.combinateCurrentDateAndGivenTime - final setting time is "+ newDate.toString());
1034
     return newDate;
1035
	  } catch (ParseException pe) {
1036
		  throw new HandlerException("ReplicationHandler.combinateCurrentDateAndGivenTime - "
1037
				  + "parsing error: "  + pe.getMessage());
1038
	  }
1039
  }
1040

    
1041
  /*
1042
	 * parse a given string to Time in short format. For example, given time is
1043
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1044
	 */
1045
  private static Date parseTime(String timeString) throws ParseException
1046
  {
1047
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1048
    Date time = format.parse(timeString); 
1049
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1050
                              +time.toString());
1051
    return time;
1052

    
1053
  }
1054
  
1055
  /*
1056
   * Parse a given string to date and time. Date format is long and time
1057
   * format is short.
1058
   */
1059
  private static Date parseDateTime(String timeString) throws ParseException
1060
  {
1061
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
1062
    Date time = format.parse(timeString);
1063
    logReplication.info("ReplicationHandler.parseDateTime - Date string is after parse a time string "+
1064
                             time.toString());
1065
    return time;
1066
  }
1067
  
1068
  /*
1069
   * Get a date string from a Date object. The date format will be long
1070
   */
1071
  private static String getDateString(Date now)
1072
  {
1073
     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
1074
     String s = df.format(now);
1075
     logReplication.info("ReplicationHandler.getDateString - Today is " + s);
1076
     return s;
1077
  }
1078
  
1079
  /*
1080
   * Get a time string from a Date object, the time format will be short
1081
   */
1082
  private static String getTimeString(Date now)
1083
  {
1084
     DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
1085
     String s = df.format(now);
1086
     logReplication.info("ReplicationHandler.getTimeString - Time is " + s);
1087
     return s;
1088
  }
1089
  
1090
  
1091
  /*
1092
	 * This method will go through the docid list both in xml_Documents table
1093
	 * and in xml_revisions table @author tao
1094
	 */
1095
	private void handleDocList(Vector<Vector<String>> docList, String tableName) {
1096
		boolean dataFile = false;
1097
		for (int j = 0; j < docList.size(); j++) {
1098
			// initial dataFile is false
1099
			dataFile = false;
1100
			// w is information for one document, information contain
1101
			// docid, rev, server or datafile.
1102
			Vector<String> w = new Vector<String>(docList.elementAt(j));
1103
			// Check if the vector w contain "datafile"
1104
			// If it has, this document is data file
1105
			try {
1106
				if (w.contains((String) PropertyService.getProperty("replication.datafileflag"))) {
1107
					dataFile = true;
1108
				}
1109
			} catch (PropertyNotFoundException pnfe) {
1110
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1111
				logReplication.error("ReplicationHandler.handleDocList - Could not retrieve data file flag property.  "
1112
						+ "Leaving as false: " + pnfe.getMessage());
1113
			}
1114
			// System.out.println("w: " + w.toString());
1115
			// Get docid
1116
			String docid = (String) w.elementAt(0);
1117
			logReplication.info("docid: " + docid);
1118
			// Get revision number
1119
			int rev = Integer.parseInt((String) w.elementAt(1));
1120
			logReplication.info("rev: " + rev);
1121
			// Get remote server name (it is may not be doc home server because
1122
			// the new hub feature
1123
			String remoteServer = (String) w.elementAt(2);
1124
			remoteServer = remoteServer.trim();
1125

    
1126
			try {
1127
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1128
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1129
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1130
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1131
				} else {
1132
					continue;
1133
				}
1134

    
1135
			} catch (Exception e) {
1136
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1137
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1138
						+ " in time replication" + e.getMessage());
1139
				continue;
1140
			}
1141
			
1142
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1143
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount + 
1144
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1145
	        }
1146
	        
1147
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1148
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount + 
1149
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1150
	        }
1151

    
1152
		}// for update docs
1153

    
1154
	}
1155
   
1156
   /*
1157
	 * This method will handle doc in xml_documents table.
1158
	 */
1159
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
1160
                                        throws HandlerException
1161
   {
1162
       // compare the update rev and local rev to see what need happen
1163
       int localrev = -1;
1164
       String action = null;
1165
       boolean flag = false;
1166
       try
1167
       {
1168
    	 long docQueryStartTime = System.currentTimeMillis();
1169
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1170
         long docQueryEndTime = System.currentTimeMillis();
1171
         _xmlDocQueryTime += (docQueryEndTime - docQueryStartTime);
1172
         _xmlDocQueryCount++;
1173
       }
1174
       catch (SQLException e)
1175
       {
1176
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1177
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1178
                                " be found because " + e.getMessage());
1179
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - " + DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1180
                 "written because error happend to find it's local revision");
1181
         DOCERRORNUMBER++;
1182
         throw new HandlerException ("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1183
                 " be found: " + e.getMessage());
1184
       }
1185
       logReplication.info("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " is "+
1186
                               localrev);
1187

    
1188
       //check the revs for an update because this document is in the
1189
       //local DB, it might be out of date.
1190
       if (localrev == -1)
1191
       {
1192
          // check if the revision is in the revision table
1193
    	   Vector<Integer> localRevVector = null;
1194
    	 try {
1195
        	 long revQueryStartTime = System.currentTimeMillis();
1196
    		 localRevVector = DBUtil.getRevListFromRevisionTable(docid);
1197
             long revQueryEndTime = System.currentTimeMillis();
1198
             _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1199
             _xmlRevQueryCount++;
1200
    	 } catch (SQLException sqle) {
1201
    		 throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - SQL error " 
1202
    				 + " when getting rev list for docid: " + docid + " : " + sqle.getMessage());
1203
    	 }
1204
         if (localRevVector != null && localRevVector.contains(new Integer(rev)))
1205
         {
1206
             // this version was deleted, so don't need replicate
1207
             flag = false;
1208
         }
1209
         else
1210
         {
1211
           //insert this document as new because it is not in the local DB
1212
           action = "INSERT";
1213
           flag = true;
1214
         }
1215
       }
1216
       else
1217
       {
1218
         if(localrev == rev)
1219
         {
1220
           // Local meatacat has the same rev to remote host, don't need
1221
           // update and flag set false
1222
           flag = false;
1223
         }
1224
         else if(localrev < rev)
1225
         {
1226
           //this document needs to be updated so send an read request
1227
           action = "UPDATE";
1228
           flag = true;
1229
         }
1230
       }
1231
       
1232
       String accNumber = null;
1233
       try {
1234
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1235
       } catch (PropertyNotFoundException pnfe) {
1236
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - error getting " 
1237
    			   + "account number separator : " + pnfe.getMessage());
1238
       }
1239
       // this is non-data file
1240
       if(flag && !dataFile)
1241
       {
1242
         try
1243
         {
1244
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1245
         }
1246
         catch(HandlerException he)
1247
         {
1248
           // skip this document
1249
           throw he;
1250
         }
1251
       }//if for non-data file
1252

    
1253
        // this is for data file
1254
       if(flag && dataFile)
1255
       {
1256
         try
1257
         {
1258
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1259
         }
1260
         catch(HandlerException he)
1261
         {
1262
           // skip this data file
1263
           throw he;
1264
         }
1265

    
1266
       }//for data file
1267
   }
1268
   
1269
   /*
1270
    * This method will handle doc in xml_documents table.
1271
    */
1272
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile) 
1273
                                        throws HandlerException
1274
   {
1275
       // compare the update rev and local rev to see what need happen
1276
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - In handle repliation revsion table");
1277
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - the docid is "+ docid);
1278
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - The rev is "+rev);
1279
       Vector<Integer> localrev = null;
1280
       String action = "INSERT";
1281
       boolean flag = false;
1282
       try
1283
       {
1284
      	 long revQueryStartTime = System.currentTimeMillis();
1285
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1286
         long revQueryEndTime = System.currentTimeMillis();
1287
         _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1288
         _xmlRevQueryCount++;
1289
       }
1290
       catch (SQLException sqle)
1291
       {
1292
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1293
         logReplication.error("ReplicationHandler.handleDocInXMLRevisions - Local rev for docid "+ docid + " could not "+
1294
                                " be found because " + sqle.getMessage());
1295
         REVERRORNUMBER++;
1296
         throw new HandlerException ("ReplicationHandler.handleDocInXMLRevisions - SQL exception getting rev list: " 
1297
        		 + sqle.getMessage());
1298
       }
1299
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - rev list in xml_revision table for docid "+ docid + " is "+
1300
                               localrev.toString());
1301
       
1302
       // if the rev is not in the xml_revision, we need insert it
1303
       if (!localrev.contains(new Integer(rev)))
1304
       {
1305
           flag = true;    
1306
       }
1307
     
1308
       String accNumber = null;
1309
       try {
1310
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1311
       } catch (PropertyNotFoundException pnfe) {
1312
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLRevisions - error getting " 
1313
    			   + "account number separator : " + pnfe.getMessage());
1314
       }
1315
       // this is non-data file
1316
       if(flag && !dataFile)
1317
       {
1318
         try
1319
         {
1320
           
1321
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1322
         }
1323
         catch(HandlerException he)
1324
         {
1325
           // skip this document
1326
           throw he;
1327
         }
1328
       }//if for non-data file
1329

    
1330
        // this is for data file
1331
       if(flag && dataFile)
1332
       {
1333
         try
1334
         {
1335
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1336
         }
1337
         catch(HandlerException he)
1338
         {
1339
           // skip this data file
1340
           throw he;
1341
         }
1342

    
1343
       }//for data file
1344
   }
1345
   
1346
   /*
1347
    * Return a ip address for given url
1348
    */
1349
   private String getIpFromURL(URL url)
1350
   {
1351
	   String ip = null;
1352
	   try
1353
	   {
1354
	      InetAddress address = InetAddress.getByName(url.getHost());
1355
	      ip = address.getHostAddress();
1356
	   }
1357
	   catch(UnknownHostException e)
1358
	   {
1359
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1360
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1361
                   +e.getMessage());
1362
	   }
1363

    
1364
	   return ip;
1365
   }
1366
  
1367
}
1368

    
(3-3/7)