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: 2010-12-08 16:59:35 -0800 (Wed, 08 Dec 2010) $'
10
 * '$Revision: 5709 $'
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
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_1NAMESPACE))
386
      {
387
        parserBase = DocumentImpl.EML210;
388
      }
389
      // Write the document into local host
390
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
391
      String newDocid = wrapper.writeReplication(dbConn,
392
                              newxmldoc,
393
                              docinfoHash.get("public_access"),
394
                              null,  /* the dtd text */
395
                              actions,
396
                              accNumber,
397
                              docinfoHash.get("user_owner"),
398
                              null, /* null for groups[] */
399
                              docHomeServer,
400
                              remoteserver, tableName, true,// true is for time replication 
401
                              createdDate,
402
                              updatedDate);
403
      
404
      //process extra access rules 
405
      Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
406
      if (xmlAccessDAOList != null) {
407
      	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
408
      	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
409
      		if (!acfsf.accessControlExists(xmlAccessDAO)) {
410
      			acfsf.insertPermissions(xmlAccessDAO);
411
      		}
412
          }
413
      }
414
      
415
      //process guid
416
      logReplication.debug("Processing guid information from docinfoHash: " + docinfoHash.toString());
417
      String guid = docinfoHash.get("guid");
418
      String docName = docinfoHash.get("docName");
419
      System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%guid passed from docinfo hash: " + guid);
420
      IdentifierManager idman = IdentifierManager.getInstance();
421
      if(guid != null && !idman.identifierExists(guid))
422
      { //if the guid was passed in, put it in the identifiers table
423
        logReplication.debug("Creating guid/docid mapping for docid " + 
424
          docinfoHash.get("docid") + " and guid: " + guid);
425
        System.out.println("docname: " + docName);
426
        if(docName.trim().equals("systemMetadata"))
427
        {
428
            System.out.println("creating mapping for systemMetadata: guid: " + guid + " localId: " + docinfoHash.get("docid"));
429
            idman.createSystemMetadataMapping(guid, docinfoHash.get("docid"));
430
        }
431
        else
432
        {
433
            System.out.println("creating mapping: guid: " + guid + " localId: " + docinfoHash.get("docid"));
434
            idman.createMapping(guid, docinfoHash.get("docid"));
435
        }
436
      }
437
      else
438
      {
439
        logReplication.debug("No guid information was included with the replicated document");
440
      }
441
      
442
      if(guid != null)
443
      {
444
          if(!docName.trim().equals("systemMetadata"))
445
          {
446
              logReplication.info("replicate D1GUID:" + guid + ":D1SCIMETADATA:" + 
447
                      accNumber + ":");
448
          }
449
          else
450
          {
451
              logReplication.info("replicate D1GUID:" + guid + ":D1SYSMETADATA:" + 
452
                      accNumber + ":");
453
          }
454
      }
455
      
456
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Successfully replicated doc " + accNumber);
457
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
458
      {
459
        logReplication.info("ReplicationHandler.handleSingleXMLDocument - " + DOCINSERTNUMBER + " Wrote xml doc " + accNumber +
460
                                     " into "+tableName + " from " +
461
                                         remoteserver);
462
        DOCINSERTNUMBER++;
463
      }
464
      else
465
      {
466
          logReplication.info("ReplicationHandler.handleSingleXMLDocument - " +REVINSERTNUMBER + " Wrote xml doc " + accNumber +
467
                  " into "+tableName + " from " +
468
                      remoteserver);
469
          REVINSERTNUMBER++;
470
      }
471
      String ip = getIpFromURL(u);
472
      EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, accNumber, actions);
473
      
474

    
475
    }//try
476
    catch(Exception e)
477
    {
478
        
479
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
480
        {
481
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
482
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
483
                                       " into "+tableName + " from " +
484
                                           remoteserver + " because "+e.getMessage());
485
          DOCERRORNUMBER++;
486
        }
487
        else
488
        {
489
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
490
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
491
                    " into "+tableName + " from " +
492
                        remoteserver +" because "+e.getMessage());
493
            REVERRORNUMBER++;
494
        }
495
        logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
496
        logReplication.error("ReplicationHandler.handleSingleXMLDocument - Failed to write doc " + accNumber +
497
                                      " into db because " +e.getMessage());
498
      throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - generic exception " 
499
    		  + "writing Replication: " +e.getMessage());
500
    }
501
    finally
502
    {
503
       //return DBConnection
504
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
505
    }//finally
506
    logD1.info("replication.create localId:" + accNumber);
507
  }
508

    
509

    
510

    
511
  /* Handle replicate single xml document*/
512
  private void handleSingleDataFile(String remoteserver, String actions,
513
                                    String accNumber, String tableName)
514
               throws HandlerException
515
  {
516
    logReplication.info("ReplicationHandler.handleSingleDataFile - Try to replicate data file: " + accNumber);
517
    DBConnection dbConn = null;
518
    int serialNumber = -1;
519
    try
520
    {
521
      // Get DBConnection from pool
522
      dbConn=DBConnectionPool.
523
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
524
      serialNumber=dbConn.getCheckOutSerialNumber();
525
      // Try get docid info from remote server
526
      DocInfoHandler dih = new DocInfoHandler();
527
      XMLReader docinfoParser = initParser(dih);
528
      String docInfoURLString = "https://" + remoteserver +
529
                  "?server="+MetacatUtil.getLocalReplicationServerName()+
530
                  "&action=getdocumentinfo&docid="+accNumber;
531
      docInfoURLString = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLString);
532
      URL docinfoUrl = new URL(docInfoURLString);
533

    
534
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
535
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
536
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
537
      // Get docid owner
538
      String user = docinfoHash.get("user_owner");
539
      // Get docid name (such as acl or dataset)
540
      String docName = docinfoHash.get("docname");
541
      // Get doc type (eml public id)
542
      String docType = docinfoHash.get("doctype");
543
      // Get docid home sever. it might be different to remoteserver
544
      // because of hub feature
545
      String docHomeServer = docinfoHash.get("home_server");
546
      String createdDate = docinfoHash.get("date_created");
547
      String updatedDate = docinfoHash.get("date_updated");
548
      //docid should include rev number too
549
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
550
                                              (String)docinfoHash.get("rev");*/
551

    
552

    
553
      String datafilePath = PropertyService.getProperty("application.datafilepath");
554
      // Get data file content
555
      String readDataURLString = "https://" + remoteserver + "?server="+
556
                                        MetacatUtil.getLocalReplicationServerName()+
557
                                            "&action=readdata&docid="+accNumber;
558
      readDataURLString = MetacatUtil.replaceWhiteSpaceForURL(readDataURLString);
559
      URL u = new URL(readDataURLString);
560
      InputStream input = u.openStream();
561
      //register data file into xml_documents table and wite data file
562
      //into file system
563
      if ( input != null)
564
      {
565
        DocumentImpl.writeDataFileInReplication(input,
566
                                                datafilePath,
567
                                                docName,docType,
568
                                                accNumber, user,
569
                                                docHomeServer,
570
                                                remoteserver,
571
                                                tableName,
572
                                                true, //true means timed replication
573
                                                createdDate,
574
                                                updatedDate);
575
                                         
576
        //process extra access rules
577
        Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
578
        if (xmlAccessDAOList != null) {
579
        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
580
        	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
581
        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
582
        			acfsf.insertPermissions(xmlAccessDAO);
583
        		}
584
            }
585
        }
586
        
587
        logReplication.info("ReplicationHandler.handleSingleDataFile - Successfully to write datafile " + accNumber);
588
        /*MetacatReplication.replLog("wrote datafile " + accNumber + " from " +
589
                                    remote server);*/
590
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
591
        {
592
          logReplication.info("ReplicationHandler.handleSingleDataFile - " + DOCINSERTNUMBER + " Wrote data file" + accNumber +
593
                                       " into "+tableName + " from " +
594
                                           remoteserver);
595
          DOCINSERTNUMBER++;
596
        }
597
        else
598
        {
599
            logReplication.info("ReplicationHandler.handleSingleDataFile - " + REVINSERTNUMBER + " Wrote data file" + accNumber +
600
                    " into "+tableName + " from " +
601
                        remoteserver);
602
            REVINSERTNUMBER++;
603
        }
604
        String ip = getIpFromURL(u);
605
        EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, accNumber, actions);
606
        
607
      }//if
608
      else
609
      {
610
         logReplication.info("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
611
         throw new HandlerException("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
612
      }//else
613

    
614
    }//try
615
    catch(Exception e)
616
    {
617
      /*MetacatReplication.replErrorLog("Failed to try wrote data file " + accNumber +
618
                                      " because " +e.getMessage());*/
619
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
620
      {
621
    	logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
622
    	logReplication.error("ReplicationHandler.handleSingleDataFile - " + DOCERRORNUMBER + " Failed to write data file " + accNumber +
623
                                     " into " + tableName + " from " +
624
                                         remoteserver + " because " + e.getMessage());
625
        DOCERRORNUMBER++;
626
      }
627
      else
628
      {
629
    	  logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
630
    	  logReplication.error("ReplicationHandler.handleSingleDataFile - " + REVERRORNUMBER + " Failed to write data file" + accNumber +
631
                  " into " + tableName + " from " +
632
                      remoteserver +" because "+ e.getMessage());
633
          REVERRORNUMBER++;
634
      }
635
      logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
636
      logReplication.error("ReplicationHandler.handleSingleDataFile - Failed to try wrote datafile " + accNumber +
637
                                      " because " + e.getMessage());
638
      throw new HandlerException("ReplicationHandler.handleSingleDataFile - generic exception " 
639
    		  + "writing Replication: " + e.getMessage());
640
    }
641
    finally
642
    {
643
       //return DBConnection
644
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
645
    }//finally
646
    logD1.info("replication.create localId:" + accNumber);
647
  }
648

    
649

    
650

    
651
  /* Handle delete single document*/
652
  private void handleDeleteSingleDocument(String docId, String notifyServer)
653
               throws HandlerException
654
  {
655
    logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Try delete doc: "+docId);
656
    DBConnection dbConn = null;
657
    int serialNumber = -1;
658
    try
659
    {
660
      // Get DBConnection from pool
661
      dbConn=DBConnectionPool.
662
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
663
      serialNumber=dbConn.getCheckOutSerialNumber();
664
      if(!alreadyDeleted(docId))
665
      {
666

    
667
         //because delete method docid should have rev number
668
         //so we just add one for it. This rev number is no sence.
669
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
670
         //System.out.println("accnum: "+accnum);
671
         DocumentImpl.delete(accnum, null, null, notifyServer);
672
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Successfully deleted doc " + docId);
673
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Doc " + docId + " deleted");
674
         URL u = new URL("https://"+notifyServer);
675
         String ip = getIpFromURL(u);
676
         EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, docId, "delete");
677
      }
678

    
679
    }//try
680
    catch(Exception e)
681
    {
682
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
683
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
684
                                 " in db because because " + e.getMessage());
685
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
686
    		  + "when handling document: " + e.getMessage());
687
    }
688
    finally
689
    {
690
       //return DBConnection
691
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
692
    }//finally
693
    logD1.info("replication.handleDeleteSingleDocument localId:" + docId);
694
  }
695

    
696
  /* Handle updateLastCheckTimForSingleServer*/
697
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
698
                                                  throws HandlerException
699
  {
700
    String server = repServer.getServerName();
701
    DBConnection dbConn = null;
702
    int serialNumber = -1;
703
    PreparedStatement pstmt = null;
704
    try
705
    {
706
      // Get DBConnection from pool
707
      dbConn=DBConnectionPool.
708
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
709
      serialNumber=dbConn.getCheckOutSerialNumber();
710

    
711
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Try to update last_check for server: "+server);
712
      // Get time from remote server
713
      URL dateurl = new URL("https://" + server + "?server="+
714
      MetacatUtil.getLocalReplicationServerName()+"&action=gettime");
715
      String datexml = ReplicationService.getURLContent(dateurl);
716
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - datexml: "+datexml);
717
      if (datexml!=null && !datexml.equals(""))
718
      {
719
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
720
         StringBuffer sql = new StringBuffer();
721
         /*sql.append("update xml_replication set last_checked = to_date('");
722
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
723
         sql.append("server like '").append(server).append("'");*/
724
         sql.append("update xml_replication set last_checked = ");
725
         sql.append(DatabaseService.getInstance().getDBAdapter().toDate(datestr, "MM/DD/YY HH24:MI:SS"));
726
         sql.append(" where server like '").append(server).append("'");
727
         pstmt = dbConn.prepareStatement(sql.toString());
728

    
729
         pstmt.executeUpdate();
730
         dbConn.commit();
731
         pstmt.close();
732
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - last_checked updated to "+datestr+" on "
733
                                      + server);
734
      }//if
735
      else
736
      {
737

    
738
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server "  +
739
                                  server + " in db because couldn't get time "
740
                                  );
741
         throw new Exception("Couldn't get time for server "+ server);
742
      }
743

    
744
    }//try
745
    catch(Exception e)
746
    {
747
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
748
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
749
                                server + " in db because because " + e.getMessage());
750
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - " 
751
    		  + "Error updating last checked time: " + e.getMessage());
752
    }
753
    finally
754
    {
755
       //return DBConnection
756
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
757
    }//finally
758
  }
759

    
760

    
761

    
762
  /**
763
   * updates xml_catalog with entries from other servers.
764
   */
765
  private void updateCatalog()
766
  {
767
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
768
    // ReplicationServer object in server list
769
    ReplicationServer replServer = null;
770
    PreparedStatement pstmt = null;
771
    String server = null;
772

    
773

    
774
    // Go through each ReplicationServer object in sererlist
775
    for (int j=0; j<serverList.size(); j++)
776
    {
777
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
778
      Vector<String> publicId = new Vector<String>();
779
      try
780
      {
781
        // Get ReplicationServer object from server list
782
        replServer = serverList.serverAt(j);
783
        // Get server name from the ReplicationServer object
784
        server = replServer.getServerName();
785
        // Try to get catalog
786
        URL u = new URL("https://" + server + "?server="+
787
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
788
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
789
        String catxml = ReplicationService.getURLContent(u);
790

    
791
        // Make sure there are not error, no empty string
792
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
793
        {
794
          throw new Exception("Couldn't get catalog list form server " +server);
795
        }
796
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
797
        CatalogMessageHandler cmh = new CatalogMessageHandler();
798
        XMLReader catparser = initParser(cmh);
799
        catparser.parse(new InputSource(new StringReader(catxml)));
800
        //parse the returned catalog xml and put it into a vector
801
        remoteCatalog = cmh.getCatalogVect();
802

    
803
        // Make sure remoteCatalog is not empty
804
        if (remoteCatalog.isEmpty())
805
        {
806
          throw new Exception("Couldn't get catalog list form server " +server);
807
        }
808

    
809
        String localcatxml = ReplicationService.getCatalogXML();
810

    
811
        // Make sure local catalog is no empty
812
        if (localcatxml==null||localcatxml.equals(""))
813
        {
814
          throw new Exception("Couldn't get catalog list form server " +server);
815
        }
816

    
817
        cmh = new CatalogMessageHandler();
818
        catparser = initParser(cmh);
819
        catparser.parse(new InputSource(new StringReader(localcatxml)));
820
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
821

    
822
        //now we have the catalog from the remote server and this local server
823
        //we now need to compare the two and merge the differences.
824
        //the comparison is base on the public_id fields which is the 4th
825
        //entry in each row vector.
826
        publicId = new Vector<String>();
827
        for(int i=0; i<localCatalog.size(); i++)
828
        {
829
          Vector<String> v = new Vector<String>(localCatalog.elementAt(i));
830
          logReplication.info("ReplicationHandler.updateCatalog - v1: " + v.toString());
831
          publicId.add(new String((String)v.elementAt(3)));
832
          //System.out.println("adding " + (String)v.elementAt(3));
833
        }
834
      }//try
835
      catch (Exception e)
836
      {
837
        logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
838
        logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
839
                                    server + " because " +e.getMessage());
840
      }//catch
841

    
842
      for(int i=0; i<remoteCatalog.size(); i++)
843
      {
844
         // DConnection
845
        DBConnection dbConn = null;
846
        // DBConnection checkout serial number
847
        int serialNumber = -1;
848
        try
849
        {
850
            dbConn=DBConnectionPool.
851
                  getDBConnection("ReplicationHandler.updateCatalog");
852
            serialNumber=dbConn.getCheckOutSerialNumber();
853
            Vector<String> v = remoteCatalog.elementAt(i);
854
            //System.out.println("v2: " + v.toString());
855
            //System.out.println("i: " + i);
856
            //System.out.println("remoteCatalog.size(): " + remoteCatalog.size());
857
            //System.out.println("publicID: " + publicId.toString());
858
            logReplication.info
859
                              ("ReplicationHandler.updateCatalog - v.elementAt(3): " + (String)v.elementAt(3));
860
           if(!publicId.contains(v.elementAt(3)))
861
           { //so we don't have this public id in our local table so we need to
862
             //add it.
863
             //System.out.println("in if");
864
             StringBuffer sql = new StringBuffer();
865
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
866
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
867
             sql.append("?,?)");
868
             //System.out.println("sql: " + sql.toString());
869
             pstmt = dbConn.prepareStatement(sql.toString());
870
             pstmt.setString(1, (String)v.elementAt(0));
871
             pstmt.setString(2, (String)v.elementAt(1));
872
             pstmt.setString(3, (String)v.elementAt(2));
873
             pstmt.setString(4, (String)v.elementAt(3));
874
             pstmt.setString(5, (String)v.elementAt(4));
875
             pstmt.execute();
876
             pstmt.close();
877
             logReplication.info("ReplicationHandler.updateCatalog - Success fully to insert new publicid "+
878
                               (String)v.elementAt(3) + " from server"+server);
879
           }
880
        }
881
        catch(Exception e)
882
        {
883
           logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
884
           logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
885
                                    server + " because " +e.getMessage());
886
        }//catch
887
        finally
888
        {
889
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
890
        }//finally
891
      }//for remote catalog
892
    }//for server list
893
    logReplication.info("End of updateCatalog");
894
  }
895

    
896
  /**
897
   * Method that returns true if docid has already been "deleted" from metacat.
898
   * This method really implements a truth table for deleted documents
899
   * The table is (a docid in one of the tables is represented by the X):
900
   * xml_docs      xml_revs      deleted?
901
   * ------------------------------------
902
   *   X             X             FALSE
903
   *   X             _             FALSE
904
   *   _             X             TRUE
905
   *   _             _             TRUE
906
   */
907
  private static boolean alreadyDeleted(String docid) throws HandlerException
908
  {
909
    DBConnection dbConn = null;
910
    int serialNumber = -1;
911
    PreparedStatement pstmt = null;
912
    try
913
    {
914
      dbConn=DBConnectionPool.
915
                  getDBConnection("ReplicationHandler.alreadyDeleted");
916
      serialNumber=dbConn.getCheckOutSerialNumber();
917
      boolean xml_docs = false;
918
      boolean xml_revs = false;
919

    
920
      StringBuffer sb = new StringBuffer();
921
      sb.append("select docid from xml_revisions where docid like '");
922
      sb.append(docid).append("'");
923
      pstmt = dbConn.prepareStatement(sb.toString());
924
      pstmt.execute();
925
      ResultSet rs = pstmt.getResultSet();
926
      boolean tablehasrows = rs.next();
927
      if(tablehasrows)
928
      {
929
        xml_revs = true;
930
      }
931

    
932
      sb = new StringBuffer();
933
      sb.append("select docid from xml_documents where docid like '");
934
      sb.append(docid).append("'");
935
      pstmt.close();
936
      pstmt = dbConn.prepareStatement(sb.toString());
937
      //increase usage count
938
      dbConn.increaseUsageCount(1);
939
      pstmt.execute();
940
      rs = pstmt.getResultSet();
941
      tablehasrows = rs.next();
942
      pstmt.close();
943
      if(tablehasrows)
944
      {
945
        xml_docs = true;
946
      }
947

    
948
      if(xml_docs && xml_revs)
949
      {
950
        return false;
951
      }
952
      else if(xml_docs && !xml_revs)
953
      {
954
        return false;
955
      }
956
      else if(!xml_docs && xml_revs)
957
      {
958
        return true;
959
      }
960
      else if(!xml_docs && !xml_revs)
961
      {
962
        return true;
963
      }
964
    }
965
    catch(Exception e)
966
    {
967
      logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
968
      logReplication.error("ReplicationHandler.alreadyDeleted - general error in alreadyDeleted: " +
969
                          e.getMessage());
970
      throw new HandlerException("ReplicationHandler.alreadyDeleted - general error: " 
971
    		  + e.getMessage());
972
    }
973
    finally
974
    {
975
      try
976
      {
977
        pstmt.close();
978
      }//try
979
      catch (SQLException ee)
980
      {
981
    	logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
982
        logReplication.error("ReplicationHandler.alreadyDeleted - Error in replicationHandler.alreadyDeleted "+
983
                          "to close pstmt: "+ee.getMessage());
984
        throw new HandlerException("ReplicationHandler.alreadyDeleted - SQL error when closing prepared statement: " 
985
      		  + ee.getMessage());
986
      }//catch
987
      finally
988
      {
989
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
990
      }//finally
991
    }//finally
992
    return false;
993
  }
994

    
995

    
996
  /**
997
   * Method to initialize the message parser
998
   */
999
  public static XMLReader initParser(DefaultHandler dh)
1000
          throws HandlerException
1001
  {
1002
    XMLReader parser = null;
1003

    
1004
    try {
1005
      ContentHandler chandler = dh;
1006

    
1007
      // Get an instance of the parser
1008
      String parserName = PropertyService.getProperty("xml.saxparser");
1009
      parser = XMLReaderFactory.createXMLReader(parserName);
1010

    
1011
      // Turn off validation
1012
      parser.setFeature("http://xml.org/sax/features/validation", false);
1013

    
1014
      parser.setContentHandler((ContentHandler)chandler);
1015
      parser.setErrorHandler((ErrorHandler)chandler);
1016

    
1017
    } catch (SAXException se) {
1018
      throw new HandlerException("ReplicationHandler.initParser - Sax error when " 
1019
    		  + " initializing parser: " + se.getMessage());
1020
    } catch (PropertyNotFoundException pnfe) {
1021
        throw new HandlerException("ReplicationHandler.initParser - Property error when " 
1022
      		  + " getting parser name: " + pnfe.getMessage());
1023
    } 
1024

    
1025
    return parser;
1026
  }
1027

    
1028
  /**
1029
	 * This method will combine given time string(in short format) to current
1030
	 * date. If the given time (e.g 10:00 AM) passed the current time (e.g 2:00
1031
	 * PM Aug 21, 2005), then the time will set to second day, 10:00 AM Aug 22,
1032
	 * 2005. If the given time (e.g 10:00 AM) haven't passed the current time
1033
	 * (e.g 8:00 AM Aug 21, 2005) The time will set to be 10:00 AM Aug 21, 2005.
1034
	 * 
1035
	 * @param givenTime
1036
	 *            the format should be "10:00 AM " or "2:00 PM"
1037
	 * @return
1038
	 * @throws Exception
1039
	 */
1040
	public static Date combinateCurrentDateAndGivenTime(String givenTime) throws HandlerException
1041
  {
1042
	  try {
1043
     Date givenDate = parseTime(givenTime);
1044
     Date newDate = null;
1045
     Date now = new Date();
1046
     String currentTimeString = getTimeString(now);
1047
     Date currentTime = parseTime(currentTimeString); 
1048
     if ( currentTime.getTime() >= givenDate.getTime())
1049
     {
1050
        logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today already pass the given time, we should set it as tomorrow");
1051
        String dateAndTime = getDateString(now) + " " + givenTime;
1052
        Date combinationDate = parseDateTime(dateAndTime);
1053
        // new date should plus 24 hours to make is the second day
1054
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
1055
     }
1056
     else
1057
     {
1058
         logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today haven't pass the given time, we should it as today");
1059
         String dateAndTime = getDateString(now) + " " + givenTime;
1060
         newDate = parseDateTime(dateAndTime);
1061
     }
1062
     logReplication.warn("ReplicationHandler.combinateCurrentDateAndGivenTime - final setting time is "+ newDate.toString());
1063
     return newDate;
1064
	  } catch (ParseException pe) {
1065
		  throw new HandlerException("ReplicationHandler.combinateCurrentDateAndGivenTime - "
1066
				  + "parsing error: "  + pe.getMessage());
1067
	  }
1068
  }
1069

    
1070
  /*
1071
	 * parse a given string to Time in short format. For example, given time is
1072
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1073
	 */
1074
  private static Date parseTime(String timeString) throws ParseException
1075
  {
1076
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1077
    Date time = format.parse(timeString); 
1078
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1079
                              +time.toString());
1080
    return time;
1081

    
1082
  }
1083
  
1084
  /*
1085
   * Parse a given string to date and time. Date format is long and time
1086
   * format is short.
1087
   */
1088
  private static Date parseDateTime(String timeString) throws ParseException
1089
  {
1090
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
1091
    Date time = format.parse(timeString);
1092
    logReplication.info("ReplicationHandler.parseDateTime - Date string is after parse a time string "+
1093
                             time.toString());
1094
    return time;
1095
  }
1096
  
1097
  /*
1098
   * Get a date string from a Date object. The date format will be long
1099
   */
1100
  private static String getDateString(Date now)
1101
  {
1102
     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
1103
     String s = df.format(now);
1104
     logReplication.info("ReplicationHandler.getDateString - Today is " + s);
1105
     return s;
1106
  }
1107
  
1108
  /*
1109
   * Get a time string from a Date object, the time format will be short
1110
   */
1111
  private static String getTimeString(Date now)
1112
  {
1113
     DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
1114
     String s = df.format(now);
1115
     logReplication.info("ReplicationHandler.getTimeString - Time is " + s);
1116
     return s;
1117
  }
1118
  
1119
  
1120
  /*
1121
	 * This method will go through the docid list both in xml_Documents table
1122
	 * and in xml_revisions table @author tao
1123
	 */
1124
	private void handleDocList(Vector<Vector<String>> docList, String tableName) {
1125
		boolean dataFile = false;
1126
		for (int j = 0; j < docList.size(); j++) {
1127
			// initial dataFile is false
1128
			dataFile = false;
1129
			// w is information for one document, information contain
1130
			// docid, rev, server or datafile.
1131
			Vector<String> w = new Vector<String>(docList.elementAt(j));
1132
			// Check if the vector w contain "datafile"
1133
			// If it has, this document is data file
1134
			try {
1135
				if (w.contains((String) PropertyService.getProperty("replication.datafileflag"))) {
1136
					dataFile = true;
1137
				}
1138
			} catch (PropertyNotFoundException pnfe) {
1139
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1140
				logReplication.error("ReplicationHandler.handleDocList - Could not retrieve data file flag property.  "
1141
						+ "Leaving as false: " + pnfe.getMessage());
1142
			}
1143
			// System.out.println("w: " + w.toString());
1144
			// Get docid
1145
			String docid = (String) w.elementAt(0);
1146
			logReplication.info("docid: " + docid);
1147
			// Get revision number
1148
			int rev = Integer.parseInt((String) w.elementAt(1));
1149
			logReplication.info("rev: " + rev);
1150
			// Get remote server name (it is may not be doc home server because
1151
			// the new hub feature
1152
			String remoteServer = (String) w.elementAt(2);
1153
			remoteServer = remoteServer.trim();
1154

    
1155
			try {
1156
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1157
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1158
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1159
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1160
				} else {
1161
					continue;
1162
				}
1163

    
1164
			} catch (Exception e) {
1165
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1166
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1167
						+ " in time replication" + e.getMessage());
1168
				continue;
1169
			}
1170
			
1171
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1172
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount + 
1173
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1174
	        }
1175
	        
1176
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1177
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount + 
1178
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1179
	        }
1180

    
1181
		}// for update docs
1182

    
1183
	}
1184
   
1185
   /*
1186
	 * This method will handle doc in xml_documents table.
1187
	 */
1188
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
1189
                                        throws HandlerException
1190
   {
1191
       // compare the update rev and local rev to see what need happen
1192
       int localrev = -1;
1193
       String action = null;
1194
       boolean flag = false;
1195
       try
1196
       {
1197
    	 long docQueryStartTime = System.currentTimeMillis();
1198
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1199
         long docQueryEndTime = System.currentTimeMillis();
1200
         _xmlDocQueryTime += (docQueryEndTime - docQueryStartTime);
1201
         _xmlDocQueryCount++;
1202
       }
1203
       catch (SQLException e)
1204
       {
1205
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1206
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1207
                                " be found because " + e.getMessage());
1208
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - " + DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1209
                 "written because error happend to find it's local revision");
1210
         DOCERRORNUMBER++;
1211
         throw new HandlerException ("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1212
                 " be found: " + e.getMessage());
1213
       }
1214
       logReplication.info("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " is "+
1215
                               localrev);
1216

    
1217
       //check the revs for an update because this document is in the
1218
       //local DB, it might be out of date.
1219
       if (localrev == -1)
1220
       {
1221
          // check if the revision is in the revision table
1222
    	   Vector<Integer> localRevVector = null;
1223
    	 try {
1224
        	 long revQueryStartTime = System.currentTimeMillis();
1225
    		 localRevVector = DBUtil.getRevListFromRevisionTable(docid);
1226
             long revQueryEndTime = System.currentTimeMillis();
1227
             _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1228
             _xmlRevQueryCount++;
1229
    	 } catch (SQLException sqle) {
1230
    		 throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - SQL error " 
1231
    				 + " when getting rev list for docid: " + docid + " : " + sqle.getMessage());
1232
    	 }
1233
         if (localRevVector != null && localRevVector.contains(new Integer(rev)))
1234
         {
1235
             // this version was deleted, so don't need replicate
1236
             flag = false;
1237
         }
1238
         else
1239
         {
1240
           //insert this document as new because it is not in the local DB
1241
           action = "INSERT";
1242
           flag = true;
1243
         }
1244
       }
1245
       else
1246
       {
1247
         if(localrev == rev)
1248
         {
1249
           // Local meatacat has the same rev to remote host, don't need
1250
           // update and flag set false
1251
           flag = false;
1252
         }
1253
         else if(localrev < rev)
1254
         {
1255
           //this document needs to be updated so send an read request
1256
           action = "UPDATE";
1257
           flag = true;
1258
         }
1259
       }
1260
       
1261
       String accNumber = null;
1262
       try {
1263
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1264
       } catch (PropertyNotFoundException pnfe) {
1265
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - error getting " 
1266
    			   + "account number separator : " + pnfe.getMessage());
1267
       }
1268
       // this is non-data file
1269
       if(flag && !dataFile)
1270
       {
1271
         try
1272
         {
1273
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1274
         }
1275
         catch(HandlerException he)
1276
         {
1277
           // skip this document
1278
           throw he;
1279
         }
1280
       }//if for non-data file
1281

    
1282
        // this is for data file
1283
       if(flag && dataFile)
1284
       {
1285
         try
1286
         {
1287
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1288
         }
1289
         catch(HandlerException he)
1290
         {
1291
           // skip this data file
1292
           throw he;
1293
         }
1294

    
1295
       }//for data file
1296
   }
1297
   
1298
   /*
1299
    * This method will handle doc in xml_documents table.
1300
    */
1301
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile) 
1302
                                        throws HandlerException
1303
   {
1304
       // compare the update rev and local rev to see what need happen
1305
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - In handle repliation revsion table");
1306
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - the docid is "+ docid);
1307
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - The rev is "+rev);
1308
       Vector<Integer> localrev = null;
1309
       String action = "INSERT";
1310
       boolean flag = false;
1311
       try
1312
       {
1313
      	 long revQueryStartTime = System.currentTimeMillis();
1314
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1315
         long revQueryEndTime = System.currentTimeMillis();
1316
         _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1317
         _xmlRevQueryCount++;
1318
       }
1319
       catch (SQLException sqle)
1320
       {
1321
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1322
         logReplication.error("ReplicationHandler.handleDocInXMLRevisions - Local rev for docid "+ docid + " could not "+
1323
                                " be found because " + sqle.getMessage());
1324
         REVERRORNUMBER++;
1325
         throw new HandlerException ("ReplicationHandler.handleDocInXMLRevisions - SQL exception getting rev list: " 
1326
        		 + sqle.getMessage());
1327
       }
1328
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - rev list in xml_revision table for docid "+ docid + " is "+
1329
                               localrev.toString());
1330
       
1331
       // if the rev is not in the xml_revision, we need insert it
1332
       if (!localrev.contains(new Integer(rev)))
1333
       {
1334
           flag = true;    
1335
       }
1336
     
1337
       String accNumber = null;
1338
       try {
1339
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1340
       } catch (PropertyNotFoundException pnfe) {
1341
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLRevisions - error getting " 
1342
    			   + "account number separator : " + pnfe.getMessage());
1343
       }
1344
       // this is non-data file
1345
       if(flag && !dataFile)
1346
       {
1347
         try
1348
         {
1349
           
1350
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1351
         }
1352
         catch(HandlerException he)
1353
         {
1354
           // skip this document
1355
           throw he;
1356
         }
1357
       }//if for non-data file
1358

    
1359
        // this is for data file
1360
       if(flag && dataFile)
1361
       {
1362
         try
1363
         {
1364
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1365
         }
1366
         catch(HandlerException he)
1367
         {
1368
           // skip this data file
1369
           throw he;
1370
         }
1371

    
1372
       }//for data file
1373
   }
1374
   
1375
   /*
1376
    * Return a ip address for given url
1377
    */
1378
   private String getIpFromURL(URL url)
1379
   {
1380
	   String ip = null;
1381
	   try
1382
	   {
1383
	      InetAddress address = InetAddress.getByName(url.getHost());
1384
	      ip = address.getHostAddress();
1385
	   }
1386
	   catch(UnknownHostException e)
1387
	   {
1388
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1389
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1390
                   +e.getMessage());
1391
	   }
1392

    
1393
	   return ip;
1394
   }
1395
  
1396
}
1397

    
(3-3/7)