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-26 14:05:09 -0700 (Mon, 26 Jul 2010) $'
10
 * '$Revision: 5451 $'
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
      String docName = docinfoHash.get("docName");
415
      System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%guid passed from docinfo hash: " + guid);
416
      IdentifierManager idman = IdentifierManager.getInstance();
417
      if(guid != null && !idman.identifierExists(guid))
418
      { //if the guid was passed in, put it in the identifiers table
419
        logReplication.debug("Creating guid/docid mapping for docid " + 
420
          docinfoHash.get("docid") + " and guid: " + guid);
421
        System.out.println("docname: " + docName);
422
        if(docName.trim().equals("systemMetadata"))
423
        {
424
            System.out.println("creating mapping for systemMetadata: guid: " + guid + " localId: " + docinfoHash.get("docid"));
425
            idman.createSystemMetadataMapping(guid, docinfoHash.get("docid"));
426
        }
427
        else
428
        {
429
            System.out.println("creating mapping: guid: " + guid + " localId: " + docinfoHash.get("docid"));
430
            idman.createMapping(guid, docinfoHash.get("docid"));
431
        }
432
      }
433
      else
434
      {
435
        logReplication.debug("No guid information was included with the replicated document");
436
      }
437
      
438
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Successfully replicated doc " + accNumber);
439
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
440
      {
441
        logReplication.info("ReplicationHandler.handleSingleXMLDocument - " + DOCINSERTNUMBER + " Wrote xml doc " + accNumber +
442
                                     " into "+tableName + " from " +
443
                                         remoteserver);
444
        DOCINSERTNUMBER++;
445
      }
446
      else
447
      {
448
          logReplication.info("ReplicationHandler.handleSingleXMLDocument - " +REVINSERTNUMBER + " Wrote xml doc " + accNumber +
449
                  " into "+tableName + " from " +
450
                      remoteserver);
451
          REVINSERTNUMBER++;
452
      }
453
      String ip = getIpFromURL(u);
454
      EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, accNumber, actions);
455
      
456

    
457
    }//try
458
    catch(Exception e)
459
    {
460
        
461
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
462
        {
463
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
464
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
465
                                       " into "+tableName + " from " +
466
                                           remoteserver + " because "+e.getMessage());
467
          DOCERRORNUMBER++;
468
        }
469
        else
470
        {
471
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
472
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
473
                    " into "+tableName + " from " +
474
                        remoteserver +" because "+e.getMessage());
475
            REVERRORNUMBER++;
476
        }
477
        logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
478
        logReplication.error("ReplicationHandler.handleSingleXMLDocument - Failed to write doc " + accNumber +
479
                                      " into db because " +e.getMessage());
480
      throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - generic exception " 
481
    		  + "writing Replication: " +e.getMessage());
482
    }
483
    finally
484
    {
485
       //return DBConnection
486
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
487
    }//finally
488
    logD1.info("replication.create localId:" + accNumber);
489
  }
490

    
491

    
492

    
493
  /* Handle replicate single xml document*/
494
  private void handleSingleDataFile(String remoteserver, String actions,
495
                                    String accNumber, String tableName)
496
               throws HandlerException
497
  {
498
    logReplication.info("ReplicationHandler.handleSingleDataFile - Try to replicate data file: " + accNumber);
499
    DBConnection dbConn = null;
500
    int serialNumber = -1;
501
    try
502
    {
503
      // Get DBConnection from pool
504
      dbConn=DBConnectionPool.
505
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
506
      serialNumber=dbConn.getCheckOutSerialNumber();
507
      // Try get docid info from remote server
508
      DocInfoHandler dih = new DocInfoHandler();
509
      XMLReader docinfoParser = initParser(dih);
510
      String docInfoURLString = "https://" + remoteserver +
511
                  "?server="+MetacatUtil.getLocalReplicationServerName()+
512
                  "&action=getdocumentinfo&docid="+accNumber;
513
      docInfoURLString = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLString);
514
      URL docinfoUrl = new URL(docInfoURLString);
515

    
516
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
517
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
518
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
519
      // Get docid owner
520
      String user = docinfoHash.get("user_owner");
521
      // Get docid name (such as acl or dataset)
522
      String docName = docinfoHash.get("docname");
523
      // Get doc type (eml public id)
524
      String docType = docinfoHash.get("doctype");
525
      // Get docid home sever. it might be different to remoteserver
526
      // because of hub feature
527
      String docHomeServer = docinfoHash.get("home_server");
528
      String createdDate = docinfoHash.get("date_created");
529
      String updatedDate = docinfoHash.get("date_updated");
530
      //docid should include rev number too
531
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
532
                                              (String)docinfoHash.get("rev");*/
533

    
534

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

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

    
631

    
632

    
633
  /* Handle delete single document*/
634
  private void handleDeleteSingleDocument(String docId, String notifyServer)
635
               throws HandlerException
636
  {
637
    logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Try delete doc: "+docId);
638
    DBConnection dbConn = null;
639
    int serialNumber = -1;
640
    try
641
    {
642
      // Get DBConnection from pool
643
      dbConn=DBConnectionPool.
644
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
645
      serialNumber=dbConn.getCheckOutSerialNumber();
646
      if(!alreadyDeleted(docId))
647
      {
648

    
649
         //because delete method docid should have rev number
650
         //so we just add one for it. This rev number is no sence.
651
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
652
         //System.out.println("accnum: "+accnum);
653
         DocumentImpl.delete(accnum, null, null, notifyServer);
654
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Successfully deleted doc " + docId);
655
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Doc " + docId + " deleted");
656
         URL u = new URL("https://"+notifyServer);
657
         String ip = getIpFromURL(u);
658
         EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, docId, "delete");
659
      }
660

    
661
    }//try
662
    catch(Exception e)
663
    {
664
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
665
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
666
                                 " in db because because " + e.getMessage());
667
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
668
    		  + "when handling document: " + e.getMessage());
669
    }
670
    finally
671
    {
672
       //return DBConnection
673
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
674
    }//finally
675
    logD1.info("replication.handleDeleteSingleDocument localId:" + docId);
676
  }
677

    
678
  /* Handle updateLastCheckTimForSingleServer*/
679
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
680
                                                  throws HandlerException
681
  {
682
    String server = repServer.getServerName();
683
    DBConnection dbConn = null;
684
    int serialNumber = -1;
685
    PreparedStatement pstmt = null;
686
    try
687
    {
688
      // Get DBConnection from pool
689
      dbConn=DBConnectionPool.
690
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
691
      serialNumber=dbConn.getCheckOutSerialNumber();
692

    
693
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Try to update last_check for server: "+server);
694
      // Get time from remote server
695
      URL dateurl = new URL("https://" + server + "?server="+
696
      MetacatUtil.getLocalReplicationServerName()+"&action=gettime");
697
      String datexml = ReplicationService.getURLContent(dateurl);
698
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - datexml: "+datexml);
699
      if (datexml!=null && !datexml.equals(""))
700
      {
701
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
702
         StringBuffer sql = new StringBuffer();
703
         /*sql.append("update xml_replication set last_checked = to_date('");
704
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
705
         sql.append("server like '").append(server).append("'");*/
706
         sql.append("update xml_replication set last_checked = ");
707
         sql.append(DatabaseService.getInstance().getDBAdapter().toDate(datestr, "MM/DD/YY HH24:MI:SS"));
708
         sql.append(" where server like '").append(server).append("'");
709
         pstmt = dbConn.prepareStatement(sql.toString());
710

    
711
         pstmt.executeUpdate();
712
         dbConn.commit();
713
         pstmt.close();
714
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - last_checked updated to "+datestr+" on "
715
                                      + server);
716
      }//if
717
      else
718
      {
719

    
720
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server "  +
721
                                  server + " in db because couldn't get time "
722
                                  );
723
         throw new Exception("Couldn't get time for server "+ server);
724
      }
725

    
726
    }//try
727
    catch(Exception e)
728
    {
729
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
730
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
731
                                server + " in db because because " + e.getMessage());
732
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - " 
733
    		  + "Error updating last checked time: " + e.getMessage());
734
    }
735
    finally
736
    {
737
       //return DBConnection
738
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
739
    }//finally
740
  }
741

    
742

    
743

    
744
  /**
745
   * updates xml_catalog with entries from other servers.
746
   */
747
  private void updateCatalog()
748
  {
749
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
750
    // ReplicationServer object in server list
751
    ReplicationServer replServer = null;
752
    PreparedStatement pstmt = null;
753
    String server = null;
754

    
755

    
756
    // Go through each ReplicationServer object in sererlist
757
    for (int j=0; j<serverList.size(); j++)
758
    {
759
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
760
      Vector<String> publicId = new Vector<String>();
761
      try
762
      {
763
        // Get ReplicationServer object from server list
764
        replServer = serverList.serverAt(j);
765
        // Get server name from the ReplicationServer object
766
        server = replServer.getServerName();
767
        // Try to get catalog
768
        URL u = new URL("https://" + server + "?server="+
769
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
770
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
771
        String catxml = ReplicationService.getURLContent(u);
772

    
773
        // Make sure there are not error, no empty string
774
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
775
        {
776
          throw new Exception("Couldn't get catalog list form server " +server);
777
        }
778
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
779
        CatalogMessageHandler cmh = new CatalogMessageHandler();
780
        XMLReader catparser = initParser(cmh);
781
        catparser.parse(new InputSource(new StringReader(catxml)));
782
        //parse the returned catalog xml and put it into a vector
783
        remoteCatalog = cmh.getCatalogVect();
784

    
785
        // Make sure remoteCatalog is not empty
786
        if (remoteCatalog.isEmpty())
787
        {
788
          throw new Exception("Couldn't get catalog list form server " +server);
789
        }
790

    
791
        String localcatxml = ReplicationService.getCatalogXML();
792

    
793
        // Make sure local catalog is no empty
794
        if (localcatxml==null||localcatxml.equals(""))
795
        {
796
          throw new Exception("Couldn't get catalog list form server " +server);
797
        }
798

    
799
        cmh = new CatalogMessageHandler();
800
        catparser = initParser(cmh);
801
        catparser.parse(new InputSource(new StringReader(localcatxml)));
802
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
803

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

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

    
878
  /**
879
   * Method that returns true if docid has already been "deleted" from metacat.
880
   * This method really implements a truth table for deleted documents
881
   * The table is (a docid in one of the tables is represented by the X):
882
   * xml_docs      xml_revs      deleted?
883
   * ------------------------------------
884
   *   X             X             FALSE
885
   *   X             _             FALSE
886
   *   _             X             TRUE
887
   *   _             _             TRUE
888
   */
889
  private static boolean alreadyDeleted(String docid) throws HandlerException
890
  {
891
    DBConnection dbConn = null;
892
    int serialNumber = -1;
893
    PreparedStatement pstmt = null;
894
    try
895
    {
896
      dbConn=DBConnectionPool.
897
                  getDBConnection("ReplicationHandler.alreadyDeleted");
898
      serialNumber=dbConn.getCheckOutSerialNumber();
899
      boolean xml_docs = false;
900
      boolean xml_revs = false;
901

    
902
      StringBuffer sb = new StringBuffer();
903
      sb.append("select docid from xml_revisions where docid like '");
904
      sb.append(docid).append("'");
905
      pstmt = dbConn.prepareStatement(sb.toString());
906
      pstmt.execute();
907
      ResultSet rs = pstmt.getResultSet();
908
      boolean tablehasrows = rs.next();
909
      if(tablehasrows)
910
      {
911
        xml_revs = true;
912
      }
913

    
914
      sb = new StringBuffer();
915
      sb.append("select docid from xml_documents where docid like '");
916
      sb.append(docid).append("'");
917
      pstmt.close();
918
      pstmt = dbConn.prepareStatement(sb.toString());
919
      //increase usage count
920
      dbConn.increaseUsageCount(1);
921
      pstmt.execute();
922
      rs = pstmt.getResultSet();
923
      tablehasrows = rs.next();
924
      pstmt.close();
925
      if(tablehasrows)
926
      {
927
        xml_docs = true;
928
      }
929

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

    
977

    
978
  /**
979
   * Method to initialize the message parser
980
   */
981
  public static XMLReader initParser(DefaultHandler dh)
982
          throws HandlerException
983
  {
984
    XMLReader parser = null;
985

    
986
    try {
987
      ContentHandler chandler = dh;
988

    
989
      // Get an instance of the parser
990
      String parserName = PropertyService.getProperty("xml.saxparser");
991
      parser = XMLReaderFactory.createXMLReader(parserName);
992

    
993
      // Turn off validation
994
      parser.setFeature("http://xml.org/sax/features/validation", false);
995

    
996
      parser.setContentHandler((ContentHandler)chandler);
997
      parser.setErrorHandler((ErrorHandler)chandler);
998

    
999
    } catch (SAXException se) {
1000
      throw new HandlerException("ReplicationHandler.initParser - Sax error when " 
1001
    		  + " initializing parser: " + se.getMessage());
1002
    } catch (PropertyNotFoundException pnfe) {
1003
        throw new HandlerException("ReplicationHandler.initParser - Property error when " 
1004
      		  + " getting parser name: " + pnfe.getMessage());
1005
    } 
1006

    
1007
    return parser;
1008
  }
1009

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

    
1052
  /*
1053
	 * parse a given string to Time in short format. For example, given time is
1054
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1055
	 */
1056
  private static Date parseTime(String timeString) throws ParseException
1057
  {
1058
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1059
    Date time = format.parse(timeString); 
1060
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1061
                              +time.toString());
1062
    return time;
1063

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

    
1137
			try {
1138
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1139
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1140
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1141
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1142
				} else {
1143
					continue;
1144
				}
1145

    
1146
			} catch (Exception e) {
1147
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1148
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1149
						+ " in time replication" + e.getMessage());
1150
				continue;
1151
			}
1152
			
1153
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1154
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount + 
1155
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1156
	        }
1157
	        
1158
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1159
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount + 
1160
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1161
	        }
1162

    
1163
		}// for update docs
1164

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

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

    
1264
        // this is for data file
1265
       if(flag && dataFile)
1266
       {
1267
         try
1268
         {
1269
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1270
         }
1271
         catch(HandlerException he)
1272
         {
1273
           // skip this data file
1274
           throw he;
1275
         }
1276

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

    
1341
        // this is for data file
1342
       if(flag && dataFile)
1343
       {
1344
         try
1345
         {
1346
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1347
         }
1348
         catch(HandlerException he)
1349
         {
1350
           // skip this data file
1351
           throw he;
1352
         }
1353

    
1354
       }//for data file
1355
   }
1356
   
1357
   /*
1358
    * Return a ip address for given url
1359
    */
1360
   private String getIpFromURL(URL url)
1361
   {
1362
	   String ip = null;
1363
	   try
1364
	   {
1365
	      InetAddress address = InetAddress.getByName(url.getHost());
1366
	      ip = address.getHostAddress();
1367
	   }
1368
	   catch(UnknownHostException e)
1369
	   {
1370
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1371
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1372
                   +e.getMessage());
1373
	   }
1374

    
1375
	   return ip;
1376
   }
1377
  
1378
}
1379

    
(3-3/7)