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: 2011-11-07 14:31:44 -0800 (Mon, 07 Nov 2011) $'
10
 * '$Revision: 6614 $'
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 java.io.ByteArrayInputStream;
30
import java.io.InputStream;
31
import java.io.StringReader;
32
import java.net.InetAddress;
33
import java.net.URL;
34
import java.net.UnknownHostException;
35
import java.sql.PreparedStatement;
36
import java.sql.ResultSet;
37
import java.sql.SQLException;
38
import java.sql.Timestamp;
39
import java.text.DateFormat;
40
import java.text.ParseException;
41
import java.util.Calendar;
42
import java.util.Date;
43
import java.util.Hashtable;
44
import java.util.TimerTask;
45
import java.util.Vector;
46

    
47
import javax.xml.bind.DatatypeConverter;
48

    
49
import org.apache.log4j.Logger;
50
import org.dataone.service.types.v1.SystemMetadata;
51
import org.dataone.service.util.DateTimeMarshaller;
52
import org.dataone.service.util.TypeMarshaller;
53
import org.xml.sax.ContentHandler;
54
import org.xml.sax.ErrorHandler;
55
import org.xml.sax.InputSource;
56
import org.xml.sax.SAXException;
57
import org.xml.sax.XMLReader;
58
import org.xml.sax.helpers.DefaultHandler;
59
import org.xml.sax.helpers.XMLReaderFactory;
60

    
61
import edu.ucsb.nceas.metacat.CatalogMessageHandler;
62
import edu.ucsb.nceas.metacat.DBUtil;
63
import edu.ucsb.nceas.metacat.DocInfoHandler;
64
import edu.ucsb.nceas.metacat.DocumentImpl;
65
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
66
import edu.ucsb.nceas.metacat.EventLog;
67
import edu.ucsb.nceas.metacat.IdentifierManager;
68
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
69
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
70
import edu.ucsb.nceas.metacat.accesscontrol.XMLAccessDAO;
71
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
72
import edu.ucsb.nceas.metacat.database.DBConnection;
73
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
74
import edu.ucsb.nceas.metacat.database.DatabaseService;
75
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
76
import edu.ucsb.nceas.metacat.properties.PropertyService;
77
import edu.ucsb.nceas.metacat.shared.HandlerException;
78
import edu.ucsb.nceas.metacat.util.MetacatUtil;
79
import edu.ucsb.nceas.metacat.util.ReplicationUtil;
80
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
81

    
82

    
83

    
84
/**
85
 * This class handles deltaT replication checking.  Whenever this TimerTask
86
 * is fired it checks each server in xml_replication for updates and updates
87
 * the local db as needed.
88
 */
89
public class ReplicationHandler extends TimerTask
90
{
91
  int serverCheckCode = 1;
92
  ReplicationServerList serverList = null;
93
  //PrintWriter out;
94
//  private static final AbstractDatabase dbAdapter = MetacatUtil.dbAdapter;
95
  private static Logger logReplication = Logger.getLogger("ReplicationLogging");
96
  private static Logger logMetacat = Logger.getLogger(ReplicationHandler.class);
97
  private static Logger logD1 = Logger.getLogger("DataOneLogger");
98
  
99
  private static int DOCINSERTNUMBER = 1;
100
  private static int DOCERRORNUMBER  = 1;
101
  private static int REVINSERTNUMBER = 1;
102
  private static int REVERRORNUMBER  = 1;
103
  
104
  private static int _xmlDocQueryCount = 0;
105
  private static int _xmlRevQueryCount = 0;
106
  private static long _xmlDocQueryTime = 0;
107
  private static long _xmlRevQueryTime = 0;
108
  
109
  
110
  public ReplicationHandler()
111
  {
112
    //this.out = o;
113
    serverList = new ReplicationServerList();
114
  }
115

    
116
  public ReplicationHandler(int serverCheckCode)
117
  {
118
    //this.out = o;
119
    this.serverCheckCode = serverCheckCode;
120
    serverList = new ReplicationServerList();
121
  }
122

    
123
  /**
124
   * Method that implements TimerTask.run().  It runs whenever the timer is
125
   * fired.
126
   */
127
  public void run()
128
  {
129
    //find out the last_checked time of each server in the server list and
130
    //send a query to each server to see if there are any documents in
131
    //xml_documents with an update_date > last_checked
132
	  
133
      //if serverList is null, metacat don't need to replication
134
      if (serverList==null||serverList.isEmpty())
135
      {
136
        return;
137
      }
138
      updateCatalog();
139
      update();
140
      //conn.close();
141
  }
142

    
143
  /**
144
   * Method that uses revision tagging for replication instead of update_date.
145
   */
146
  private void update()
147
  {
148
	  
149
	  _xmlDocQueryCount = 0;
150
	  _xmlRevQueryCount = 0;
151
	  _xmlDocQueryTime = 0;
152
	  _xmlRevQueryTime = 0;
153
    /*
154
     Pseudo-algorithm
155
     - request a doc list from each server in xml_replication
156
     - check the rev number of each of those documents agains the
157
       documents in the local database
158
     - pull any documents that have a lesser rev number on the local server
159
       from the remote server
160
     - delete any documents that still exist in the local xml_documents but
161
       are in the deletedDocuments tag of the remote host response.
162
     - update last_checked to keep track of the last time it was checked.
163
       (this info is theoretically not needed using this system but probably
164
       should be kept anyway)
165
    */
166

    
167
    ReplicationServer replServer = null; // Variable to store the
168
                                        // ReplicationServer got from
169
                                        // Server list
170
    String server = null; // Variable to store server name
171
//    String update;
172
    Vector<String> responses = new Vector<String>();
173
    URL u;
174
    long replicationStartTime = System.currentTimeMillis();
175
    long timeToGetServerList = 0;
176
    
177
    //Check for every server in server list to get updated list and put
178
    // them in to response
179
    long startTimeToGetServers = System.currentTimeMillis();
180
    for (int i=0; i<serverList.size(); i++)
181
    {
182
        // Get ReplicationServer object from server list
183
        replServer = serverList.serverAt(i);
184
        // Get server name from ReplicationServer object
185
        server = replServer.getServerName().trim();
186
        String result = null;
187
        logReplication.info("ReplicationHandler.update - full update started to: " + server);
188
        // Send command to that server to get updated docid information
189
        try
190
        {
191
          u = new URL("https://" + server + "?server="
192
          +MetacatUtil.getLocalReplicationServerName()+"&action=update");
193
          logReplication.info("ReplicationHandler.update - Sending infomation " +u.toString());
194
          result = ReplicationService.getURLContent(u);
195
        }
196
        catch (Exception e)
197
        {
198
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
199
          logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
200
                       "for server " + server + " because "+e.getMessage());
201
          continue;
202
        }
203

    
204
        //logReplication.info("ReplicationHandler.update - docid: "+server+" "+result);
205
        //check if result have error or not, if has skip it.
206
        if (result.indexOf("<error>")!=-1 && result.indexOf("</error>")!=-1)
207
        {
208
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
209
          logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
210
                       "for server " + server + " because "+result);
211
          continue;
212
        }
213
        //Add result to vector
214
        responses.add(result);
215
    }
216
    timeToGetServerList = System.currentTimeMillis() - startTimeToGetServers;
217

    
218
    //make sure that there is updated file list
219
    //If response is null, metacat don't need do anything
220
    if (responses==null || responses.isEmpty())
221
    {
222
    	logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
223
        logReplication.info( "ReplicationHandler.update - No updated doc list for "+
224
                           "every server and failed to replicate");
225
        return;
226
    }
227

    
228

    
229
    //logReplication.info("ReplicationHandler.update - Responses from remote metacat about updated "+
230
    //               "document information: "+ responses.toString());
231
    
232
    long totalServerListParseTime = 0;
233
    // go through response vector(it contains updated vector and delete vector
234
    for(int i=0; i<responses.size(); i++)
235
    {
236
    	long startServerListParseTime = System.currentTimeMillis();
237
    	XMLReader parser;
238
    	ReplMessageHandler message = new ReplMessageHandler();
239
    	try
240
        {
241
          parser = initParser(message);
242
        }
243
        catch (Exception e)
244
        {
245
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
246
          logReplication.error("ReplicationHandler.update - Failed to replicate becaue couldn't " +
247
                                " initParser for message and " +e.getMessage());
248
           // stop replication
249
           return;
250
        }
251
    	
252
        try
253
        {
254
          parser.parse(new InputSource(
255
                     new StringReader(
256
                     (String)(responses.elementAt(i)))));
257
        }
258
        catch(Exception e)
259
        {
260
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
261
          logReplication.error("ReplicationHandler.update - Couldn't parse one responses "+
262
                                   "because "+ e.getMessage());
263
          continue;
264
        }
265
        //v is the list of updated documents
266
        Vector<Vector<String>> updateList = new Vector<Vector<String>>(message.getUpdatesVect());
267
        logReplication.info("ReplicationHandler.update - The document list size is "+updateList.size()+ " from "+message.getServerName());
268
        //d is the list of deleted documents
269
        Vector<Vector<String>> deleteList = new Vector<Vector<String>>(message.getDeletesVect());
270
        logReplication.info("ReplicationHandler.update - Update vector size: "+ updateList.size()+" from "+message.getServerName());
271
        logReplication.info("ReplicationHandler.update - Delete vector size: "+ deleteList.size()+" from "+message.getServerName());
272
        logReplication.info("ReplicationHandler.update - The delete document list size is "+deleteList.size()+" from "+message.getServerName());
273
        // go though every element in updated document vector
274
        handleDocList(updateList, DocumentImpl.DOCUMENTTABLE);
275
        //handle deleted docs
276
        for(int k=0; k<deleteList.size(); k++)
277
        { //delete the deleted documents;
278
          Vector<String> w = new Vector<String>(deleteList.elementAt(k));
279
          String docId = (String)w.elementAt(0);
280
          try
281
          {
282
            handleDeleteSingleDocument(docId, server);
283
          }
284
          catch (Exception ee)
285
          {
286
            continue;
287
          }
288
        }//for delete docs
289
        
290
        // handle replicate doc in xml_revision
291
        Vector<Vector<String>> revisionList = new Vector<Vector<String>>(message.getRevisionsVect());
292
        logReplication.info("ReplicationHandler.update - The revision document list size is "+revisionList.size()+ " from "+message.getServerName());
293
        handleDocList(revisionList, DocumentImpl.REVISIONTABLE);
294
        DOCINSERTNUMBER = 1;
295
        DOCERRORNUMBER  = 1;
296
        REVINSERTNUMBER = 1;
297
        REVERRORNUMBER  = 1;
298
        
299
        // handle system metadata
300
        Vector<Vector<String>> systemMetadataList = message.getSystemMetadataVect();
301
        for(int k = 0; k < systemMetadataList.size(); k++) { 
302
        	Vector<String> w = systemMetadataList.elementAt(k);
303
        	String guid = (String) w.elementAt(0);
304
        	String remoteserver = (String) w.elementAt(1);
305
        	try {
306
        		handleSystemMetadata(remoteserver, guid);
307
        	}
308
        	catch (Exception ee) {
309
        		logMetacat.error("Error replicating system metedata for guid: " + guid, ee);
310
        		continue;
311
        	}
312
        }
313
        
314
        totalServerListParseTime += (System.currentTimeMillis() - startServerListParseTime);
315
    }//for response
316

    
317
    //updated last_checked
318
    for (int i=0;i<serverList.size(); i++)
319
    {
320
       // Get ReplicationServer object from server list
321
       replServer = serverList.serverAt(i);
322
       try
323
       {
324
         updateLastCheckTimeForSingleServer(replServer);
325
       }
326
       catch(Exception e)
327
       {
328
         continue;
329
       }
330
    }//for
331
    
332
    long replicationEndTime = System.currentTimeMillis();
333
    logMetacat.debug("ReplicationHandler.update - Total replication time: " + 
334
    		(replicationEndTime - replicationStartTime));
335
    logMetacat.debug("ReplicationHandler.update - time to get server list: " + 
336
    		timeToGetServerList);
337
    logMetacat.debug("ReplicationHandler.update - server list parse time: " + 
338
    		totalServerListParseTime);
339
    logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query count: " + 
340
    		_xmlDocQueryCount);
341
    logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query time: " + 
342
    		_xmlDocQueryTime + " ms");
343
    logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query count: " + 
344
    		_xmlRevQueryCount);
345
    logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query time: " + 
346
    		_xmlRevQueryTime + " ms");;
347

    
348
  }//update
349

    
350
  /* Handle replicate single xml document*/
351
  private void handleSingleXMLDocument(String remoteserver, String actions,
352
                                       String accNumber, String tableName)
353
               throws HandlerException
354
  {
355
    DBConnection dbConn = null;
356
    int serialNumber = -1;
357
    try
358
    {
359
      // Get DBConnection from pool
360
      dbConn=DBConnectionPool.
361
                  getDBConnection("ReplicationHandler.handleSingleXMLDocument");
362
      serialNumber=dbConn.getCheckOutSerialNumber();
363
      //if the document needs to be updated or inserted, this is executed
364
      String readDocURLString = "https://" + remoteserver + "?server="+
365
              MetacatUtil.getLocalReplicationServerName()+"&action=read&docid="+accNumber;
366
      readDocURLString = MetacatUtil.replaceWhiteSpaceForURL(readDocURLString);
367
      URL u = new URL(readDocURLString);
368

    
369
      // Get docid content
370
      String newxmldoc = ReplicationService.getURLContent(u);
371
      // If couldn't get skip it
372
      if ( newxmldoc.indexOf("<error>")!= -1 && newxmldoc.indexOf("</error>")!=-1)
373
      {
374
         throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - " + newxmldoc);
375
      }
376
      //logReplication.info("xml documnet:");
377
      //logReplication.info(newxmldoc);
378

    
379
      // Try get the docid info from remote server
380
      DocInfoHandler dih = new DocInfoHandler();
381
      XMLReader docinfoParser = initParser(dih);
382
      String docInfoURLStr = "https://" + remoteserver +
383
                       "?server="+MetacatUtil.getLocalReplicationServerName()+
384
                       "&action=getdocumentinfo&docid="+accNumber;
385
      docInfoURLStr = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLStr);
386
      URL docinfoUrl = new URL(docInfoURLStr);
387
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Sending message: " + docinfoUrl.toString());
388
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
389
      
390
      // strip out the system metadata portion
391
      String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
392
   	  docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);
393
      
394
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
395
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
396
      // Get home server of the docid
397
      String docHomeServer = docinfoHash.get("home_server");
398
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doc home server in repl: "+docHomeServer);
399
     
400
      // dates
401
      String createdDateString = docinfoHash.get("date_created");
402
      String updatedDateString = docinfoHash.get("date_updated");
403
      Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
404
      Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
405
      
406
      //docid should include rev number too
407
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
408
                                              (String)docinfoHash.get("rev");*/
409
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - docid in repl: "+accNumber);
410
      String docType = docinfoHash.get("doctype");
411
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doctype in repl: "+docType);
412

    
413
      String parserBase = null;
414
      // this for eml2 and we need user eml2 parser
415
      if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
416
      {
417
         parserBase = DocumentImpl.EML200;
418
      }
419
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
420
      {
421
        parserBase = DocumentImpl.EML200;
422
      }
423
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
424
      {
425
        parserBase = DocumentImpl.EML210;
426
      }
427
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_1NAMESPACE))
428
      {
429
        parserBase = DocumentImpl.EML210;
430
      }
431
      // Write the document into local host
432
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
433
      String newDocid = wrapper.writeReplication(dbConn,
434
                              newxmldoc,
435
                              docinfoHash.get("public_access"),
436
                              null,  /* the dtd text */
437
                              actions,
438
                              accNumber,
439
                              null, //docinfoHash.get("user_owner"),                              
440
                              null, /* null for groups[] */
441
                              docHomeServer,
442
                              remoteserver, tableName, true,// true is for time replication 
443
                              createdDate,
444
                              updatedDate);
445
      
446
      //set the user information
447
      String user = (String) docinfoHash.get("user_owner");
448
      String updated = (String) docinfoHash.get("user_updated");
449
      ReplicationService.updateUserOwner(dbConn, accNumber, user, updated);
450
      
451
      //process extra access rules 
452
      Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
453
      if (xmlAccessDAOList != null) {
454
      	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
455
      	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
456
      		if (!acfsf.accessControlExists(xmlAccessDAO)) {
457
      			acfsf.insertPermissions(xmlAccessDAO);
458
      		}
459
          }
460
      }
461
      
462
      // process system metadata
463
      if (systemMetadataXML != null) {
464
    	  SystemMetadata sysMeta = 
465
    		  TypeMarshaller.unmarshalTypeFromStream(
466
    				  SystemMetadata.class, 
467
    				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
468
    	  // need the guid-to-docid mapping
469
      	  IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), accNumber);
470
      }
471
      
472
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Successfully replicated doc " + accNumber);
473
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
474
      {
475
        logReplication.info("ReplicationHandler.handleSingleXMLDocument - " + DOCINSERTNUMBER + " Wrote xml doc " + accNumber +
476
                                     " into "+tableName + " from " +
477
                                         remoteserver);
478
        DOCINSERTNUMBER++;
479
      }
480
      else
481
      {
482
          logReplication.info("ReplicationHandler.handleSingleXMLDocument - " +REVINSERTNUMBER + " Wrote xml doc " + accNumber +
483
                  " into "+tableName + " from " +
484
                      remoteserver);
485
          REVINSERTNUMBER++;
486
      }
487
      String ip = getIpFromURL(u);
488
      EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, accNumber, actions);
489
      
490

    
491
    }//try
492
    catch(Exception e)
493
    {
494
        
495
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
496
        {
497
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
498
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
499
                                       " into "+tableName + " from " +
500
                                           remoteserver + " because "+e.getMessage());
501
          DOCERRORNUMBER++;
502
        }
503
        else
504
        {
505
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
506
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
507
                    " into "+tableName + " from " +
508
                        remoteserver +" because "+e.getMessage());
509
            REVERRORNUMBER++;
510
        }
511
        logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
512
        logReplication.error("ReplicationHandler.handleSingleXMLDocument - Failed to write doc " + accNumber +
513
                                      " into db because " +e.getMessage());
514
      throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - generic exception " 
515
    		  + "writing Replication: " +e.getMessage());
516
    }
517
    finally
518
    {
519
       //return DBConnection
520
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
521
    }//finally
522
    logD1.info("replication.create localId:" + accNumber);
523
  }
524

    
525

    
526

    
527
  /* Handle replicate single xml document*/
528
  private void handleSingleDataFile(String remoteserver, String actions,
529
                                    String accNumber, String tableName)
530
               throws HandlerException
531
  {
532
    logReplication.info("ReplicationHandler.handleSingleDataFile - Try to replicate data file: " + accNumber);
533
    DBConnection dbConn = null;
534
    int serialNumber = -1;
535
    try
536
    {
537
      // Get DBConnection from pool
538
      dbConn=DBConnectionPool.
539
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
540
      serialNumber=dbConn.getCheckOutSerialNumber();
541
      // Try get docid info from remote server
542
      DocInfoHandler dih = new DocInfoHandler();
543
      XMLReader docinfoParser = initParser(dih);
544
      String docInfoURLString = "https://" + remoteserver +
545
                  "?server="+MetacatUtil.getLocalReplicationServerName()+
546
                  "&action=getdocumentinfo&docid="+accNumber;
547
      docInfoURLString = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLString);
548
      URL docinfoUrl = new URL(docInfoURLString);
549

    
550
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
551
      
552
      // strip out the system metadata portion
553
      String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
554
   	  docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);  
555
   	  
556
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
557
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
558
      
559
      // Get docid name (such as acl or dataset)
560
      String docName = docinfoHash.get("docname");
561
      // Get doc type (eml public id)
562
      String docType = docinfoHash.get("doctype");
563
      // Get docid home sever. it might be different to remoteserver
564
      // because of hub feature
565
      String docHomeServer = docinfoHash.get("home_server");
566
      String createdDateString = docinfoHash.get("date_created");
567
      String updatedDateString = docinfoHash.get("date_updated");
568
      Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
569
      Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
570
      //docid should include rev number too
571
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
572
                                              (String)docinfoHash.get("rev");*/
573

    
574
      String datafilePath = PropertyService.getProperty("application.datafilepath");
575
      // Get data file content
576
      String readDataURLString = "https://" + remoteserver + "?server="+
577
                                        MetacatUtil.getLocalReplicationServerName()+
578
                                            "&action=readdata&docid="+accNumber;
579
      readDataURLString = MetacatUtil.replaceWhiteSpaceForURL(readDataURLString);
580
      URL u = new URL(readDataURLString);
581
      InputStream input = ReplicationService.getURLStream(u);
582
      //register data file into xml_documents table and wite data file
583
      //into file system
584
      if ( input != null)
585
      {
586
        DocumentImpl.writeDataFileInReplication(input,
587
                                                datafilePath,
588
                                                docName,docType,
589
                                                accNumber,
590
                                                null,
591
                                                docHomeServer,
592
                                                remoteserver,
593
                                                tableName,
594
                                                true, //true means timed replication
595
                                                createdDate,
596
                                                updatedDate);
597
                                         
598
        //set the user information
599
        String user = (String) docinfoHash.get("user_owner");
600
		String updated = (String) docinfoHash.get("user_updated");
601
        ReplicationService.updateUserOwner(dbConn, accNumber, user, updated);
602
        
603
        //process extra access rules
604
        Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
605
        if (xmlAccessDAOList != null) {
606
        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
607
        	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
608
        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
609
        			acfsf.insertPermissions(xmlAccessDAO);
610
        		}
611
            }
612
        }
613
        
614
        // process system metadata
615
        if (systemMetadataXML != null) {
616
      	  SystemMetadata sysMeta = 
617
      		TypeMarshaller.unmarshalTypeFromStream(
618
      				  SystemMetadata.class, 
619
      				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
620
      	  // need the guid-to-docid mapping
621
      	  IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), accNumber);
622
        }
623
        
624
        logReplication.info("ReplicationHandler.handleSingleDataFile - Successfully to write datafile " + accNumber);
625
        /*MetacatReplication.replLog("wrote datafile " + accNumber + " from " +
626
                                    remote server);*/
627
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
628
        {
629
          logReplication.info("ReplicationHandler.handleSingleDataFile - " + DOCINSERTNUMBER + " Wrote data file" + accNumber +
630
                                       " into "+tableName + " from " +
631
                                           remoteserver);
632
          DOCINSERTNUMBER++;
633
        }
634
        else
635
        {
636
            logReplication.info("ReplicationHandler.handleSingleDataFile - " + REVINSERTNUMBER + " Wrote data file" + accNumber +
637
                    " into "+tableName + " from " +
638
                        remoteserver);
639
            REVINSERTNUMBER++;
640
        }
641
        String ip = getIpFromURL(u);
642
        EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, accNumber, actions);
643
        
644
      }//if
645
      else
646
      {
647
         logReplication.info("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
648
         throw new HandlerException("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
649
      }//else
650

    
651
    }//try
652
    catch(Exception e)
653
    {
654
      /*MetacatReplication.replErrorLog("Failed to try wrote data file " + accNumber +
655
                                      " because " +e.getMessage());*/
656
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
657
      {
658
    	logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
659
    	logReplication.error("ReplicationHandler.handleSingleDataFile - " + DOCERRORNUMBER + " Failed to write data file " + accNumber +
660
                                     " into " + tableName + " from " +
661
                                         remoteserver + " because " + e.getMessage());
662
        DOCERRORNUMBER++;
663
      }
664
      else
665
      {
666
    	  logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
667
    	  logReplication.error("ReplicationHandler.handleSingleDataFile - " + REVERRORNUMBER + " Failed to write data file" + accNumber +
668
                  " into " + tableName + " from " +
669
                      remoteserver +" because "+ e.getMessage());
670
          REVERRORNUMBER++;
671
      }
672
      logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
673
      logReplication.error("ReplicationHandler.handleSingleDataFile - Failed to try wrote datafile " + accNumber +
674
                                      " because " + e.getMessage());
675
      throw new HandlerException("ReplicationHandler.handleSingleDataFile - generic exception " 
676
    		  + "writing Replication: " + e.getMessage());
677
    }
678
    finally
679
    {
680
       //return DBConnection
681
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
682
    }//finally
683
    logD1.info("replication.create localId:" + accNumber);
684
  }
685

    
686

    
687

    
688
  /* Handle delete single document*/
689
  private void handleDeleteSingleDocument(String docId, String notifyServer)
690
               throws HandlerException
691
  {
692
    logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Try delete doc: "+docId);
693
    DBConnection dbConn = null;
694
    int serialNumber = -1;
695
    try
696
    {
697
      // Get DBConnection from pool
698
      dbConn=DBConnectionPool.
699
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
700
      serialNumber=dbConn.getCheckOutSerialNumber();
701
      if(!alreadyDeleted(docId))
702
      {
703

    
704
         //because delete method docid should have rev number
705
         //so we just add one for it. This rev number is no sence.
706
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
707
         DocumentImpl.delete(accnum, null, null, notifyServer);
708
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Successfully deleted doc " + docId);
709
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Doc " + docId + " deleted");
710
         URL u = new URL("https://"+notifyServer);
711
         String ip = getIpFromURL(u);
712
         EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, docId, "delete");
713
      }
714

    
715
    }//try
716
    catch(McdbDocNotFoundException e)
717
    {
718
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
719
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
720
                                 " in db because because " + e.getMessage());
721
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
722
    		  + "when handling document: " + e.getMessage());
723
    }
724
    catch(InsufficientKarmaException e)
725
    {
726
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
727
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
728
                                 " in db because because " + e.getMessage());
729
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
730
    		  + "when handling document: " + e.getMessage());
731
    }
732
    catch(SQLException e)
733
    {
734
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
735
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
736
                                 " in db because because " + e.getMessage());
737
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
738
    		  + "when handling document: " + e.getMessage());
739
    }
740
    catch(Exception e)
741
    {
742
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
743
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
744
                                 " in db because because " + e.getMessage());
745
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
746
    		  + "when handling document: " + e.getMessage());
747
    }
748
    finally
749
    {
750
       //return DBConnection
751
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
752
    }//finally
753
    logD1.info("replication.handleDeleteSingleDocument localId:" + docId);
754
  }
755

    
756
  /* Handle updateLastCheckTimForSingleServer*/
757
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
758
                                                  throws HandlerException
759
  {
760
    String server = repServer.getServerName();
761
    DBConnection dbConn = null;
762
    int serialNumber = -1;
763
    PreparedStatement pstmt = null;
764
    try
765
    {
766
      // Get DBConnection from pool
767
      dbConn=DBConnectionPool.
768
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
769
      serialNumber=dbConn.getCheckOutSerialNumber();
770

    
771
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Try to update last_check for server: "+server);
772
      // Get time from remote server
773
      URL dateurl = new URL("https://" + server + "?server="+
774
      MetacatUtil.getLocalReplicationServerName()+"&action=gettime");
775
      String datexml = ReplicationService.getURLContent(dateurl);
776
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - datexml: "+datexml);
777
      if (datexml != null && !datexml.equals("")) {
778
    	  
779
    	  // parse the ISO datetime
780
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
781
         Date updated = DateTimeMarshaller.deserializeDateToUTC(datestr);
782
         
783
         StringBuffer sql = new StringBuffer();
784
         sql.append("update xml_replication set last_checked = ? ");
785
         sql.append(" where server like ? ");
786
         pstmt = dbConn.prepareStatement(sql.toString());
787
         pstmt.setTimestamp(1, new Timestamp(updated.getTime()));
788
         pstmt.setString(2, server);
789
         
790
         pstmt.executeUpdate();
791
         dbConn.commit();
792
         pstmt.close();
793
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - last_checked updated to "+datestr+" on "
794
                                      + server);
795
      }//if
796
      else
797
      {
798

    
799
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server "  +
800
                                  server + " in db because couldn't get time "
801
                                  );
802
         throw new Exception("Couldn't get time for server "+ server);
803
      }
804

    
805
    }//try
806
    catch(Exception e)
807
    {
808
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
809
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
810
                                server + " in db because because " + e.getMessage());
811
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - " 
812
    		  + "Error updating last checked time: " + e.getMessage());
813
    }
814
    finally
815
    {
816
       //return DBConnection
817
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
818
    }//finally
819
  }
820
  
821
  	/**
822
	 * Handle replicate system metadata
823
	 * 
824
	 * @param remoteserver
825
	 * @param guid
826
	 * @throws HandlerException
827
	 */
828
	private void handleSystemMetadata(String remoteserver, String guid) 
829
		throws HandlerException {
830
		try {
831

    
832
			// Try get the system metadata from remote server
833
			String sysMetaURLStr = "https://" + remoteserver + "?server="
834
					+ MetacatUtil.getLocalReplicationServerName()
835
					+ "&action=getsystemmetadata&guid=" + guid;
836
			sysMetaURLStr = MetacatUtil.replaceWhiteSpaceForURL(sysMetaURLStr);
837
			URL sysMetaUrl = new URL(sysMetaURLStr);
838
			logReplication.info("ReplicationHandler.handleSystemMetadata - Sending message: "
839
							+ sysMetaUrl.toString());
840
			String systemMetadataXML = ReplicationService.getURLContent(sysMetaUrl);
841

    
842
			logReplication.info("ReplicationHandler.handleSystemMetadata - guid in repl: " + guid);
843

    
844
			// process system metadata
845
			if (systemMetadataXML != null) {
846
				SystemMetadata sysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class,
847
								new ByteArrayInputStream(systemMetadataXML
848
										.getBytes("UTF-8")));
849
				HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
850
			}
851

    
852
			logReplication.info("ReplicationHandler.handleSystemMetadata - Successfully replicated system metadata for guid: "
853
							+ guid);
854

    
855
			String ip = getIpFromURL(sysMetaUrl);
856
			EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, guid, "systemMetadata");
857

    
858
		} catch (Exception e) {
859
			logMetacat.error("ReplicationHandler.handleSystemMetadata - "
860
					+ ReplicationService.METACAT_REPL_ERROR_MSG);
861
			logReplication
862
					.error("ReplicationHandler.handleSystemMetadata - Failed to write system metadata "
863
							+ guid + " into db because " + e.getMessage());
864
			throw new HandlerException(
865
					"ReplicationHandler.handleSystemMetadata - generic exception "
866
							+ "writing Replication: " + e.getMessage());
867
		}
868

    
869
	}
870

    
871
  /**
872
   * updates xml_catalog with entries from other servers.
873
   */
874
  private void updateCatalog()
875
  {
876
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
877
    // ReplicationServer object in server list
878
    ReplicationServer replServer = null;
879
    PreparedStatement pstmt = null;
880
    String server = null;
881

    
882

    
883
    // Go through each ReplicationServer object in sererlist
884
    for (int j=0; j<serverList.size(); j++)
885
    {
886
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
887
      Vector<String> publicId = new Vector<String>();
888
      try
889
      {
890
        // Get ReplicationServer object from server list
891
        replServer = serverList.serverAt(j);
892
        // Get server name from the ReplicationServer object
893
        server = replServer.getServerName();
894
        // Try to get catalog
895
        URL u = new URL("https://" + server + "?server="+
896
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
897
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
898
        String catxml = ReplicationService.getURLContent(u);
899

    
900
        // Make sure there are not error, no empty string
901
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
902
        {
903
          throw new Exception("Couldn't get catalog list form server " +server);
904
        }
905
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
906
        CatalogMessageHandler cmh = new CatalogMessageHandler();
907
        XMLReader catparser = initParser(cmh);
908
        catparser.parse(new InputSource(new StringReader(catxml)));
909
        //parse the returned catalog xml and put it into a vector
910
        remoteCatalog = cmh.getCatalogVect();
911

    
912
        // Make sure remoteCatalog is not empty
913
        if (remoteCatalog.isEmpty())
914
        {
915
          throw new Exception("Couldn't get catalog list form server " +server);
916
        }
917

    
918
        String localcatxml = ReplicationService.getCatalogXML();
919

    
920
        // Make sure local catalog is no empty
921
        if (localcatxml==null||localcatxml.equals(""))
922
        {
923
          throw new Exception("Couldn't get catalog list form server " +server);
924
        }
925

    
926
        cmh = new CatalogMessageHandler();
927
        catparser = initParser(cmh);
928
        catparser.parse(new InputSource(new StringReader(localcatxml)));
929
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
930

    
931
        //now we have the catalog from the remote server and this local server
932
        //we now need to compare the two and merge the differences.
933
        //the comparison is base on the public_id fields which is the 4th
934
        //entry in each row vector.
935
        publicId = new Vector<String>();
936
        for(int i=0; i<localCatalog.size(); i++)
937
        {
938
          Vector<String> v = new Vector<String>(localCatalog.elementAt(i));
939
          logReplication.info("ReplicationHandler.updateCatalog - v1: " + v.toString());
940
          publicId.add(new String((String)v.elementAt(3)));
941
        }
942
      }//try
943
      catch (Exception e)
944
      {
945
        logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
946
        logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
947
                                    server + " because " +e.getMessage());
948
      }//catch
949

    
950
      for(int i=0; i<remoteCatalog.size(); i++)
951
      {
952
         // DConnection
953
        DBConnection dbConn = null;
954
        // DBConnection checkout serial number
955
        int serialNumber = -1;
956
        try
957
        {
958
            dbConn=DBConnectionPool.
959
                  getDBConnection("ReplicationHandler.updateCatalog");
960
            serialNumber=dbConn.getCheckOutSerialNumber();
961
            Vector<String> v = remoteCatalog.elementAt(i);
962
            //logMetacat.debug("v2: " + v.toString());
963
            //logMetacat.debug("i: " + i);
964
            //logMetacat.debug("remoteCatalog.size(): " + remoteCatalog.size());
965
            //logMetacat.debug("publicID: " + publicId.toString());
966
            logReplication.info
967
                              ("ReplicationHandler.updateCatalog - v.elementAt(3): " + (String)v.elementAt(3));
968
           if(!publicId.contains(v.elementAt(3)))
969
           { //so we don't have this public id in our local table so we need to
970
             //add it.
971
             //logMetacat.debug("in if");
972
             StringBuffer sql = new StringBuffer();
973
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
974
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
975
             sql.append("?,?)");
976
             //logMetacat.debug("sql: " + sql.toString());
977
             pstmt = dbConn.prepareStatement(sql.toString());
978
             pstmt.setString(1, (String)v.elementAt(0));
979
             pstmt.setString(2, (String)v.elementAt(1));
980
             pstmt.setString(3, (String)v.elementAt(2));
981
             pstmt.setString(4, (String)v.elementAt(3));
982
             pstmt.setString(5, (String)v.elementAt(4));
983
             pstmt.execute();
984
             pstmt.close();
985
             logReplication.info("ReplicationHandler.updateCatalog - Success fully to insert new publicid "+
986
                               (String)v.elementAt(3) + " from server"+server);
987
           }
988
        }
989
        catch(Exception e)
990
        {
991
           logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
992
           logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
993
                                    server + " because " +e.getMessage());
994
        }//catch
995
        finally
996
        {
997
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
998
        }//finally
999
      }//for remote catalog
1000
    }//for server list
1001
    logReplication.info("End of updateCatalog");
1002
  }
1003

    
1004
  /**
1005
   * Method that returns true if docid has already been "deleted" from metacat.
1006
   * This method really implements a truth table for deleted documents
1007
   * The table is (a docid in one of the tables is represented by the X):
1008
   * xml_docs      xml_revs      deleted?
1009
   * ------------------------------------
1010
   *   X             X             FALSE
1011
   *   X             _             FALSE
1012
   *   _             X             TRUE
1013
   *   _             _             TRUE
1014
   */
1015
  private static boolean alreadyDeleted(String docid) throws HandlerException
1016
  {
1017
    DBConnection dbConn = null;
1018
    int serialNumber = -1;
1019
    PreparedStatement pstmt = null;
1020
    try
1021
    {
1022
      dbConn=DBConnectionPool.
1023
                  getDBConnection("ReplicationHandler.alreadyDeleted");
1024
      serialNumber=dbConn.getCheckOutSerialNumber();
1025
      boolean xml_docs = false;
1026
      boolean xml_revs = false;
1027

    
1028
      StringBuffer sb = new StringBuffer();
1029
      sb.append("select docid from xml_revisions where docid like ? ");
1030
      pstmt = dbConn.prepareStatement(sb.toString());
1031
      pstmt.setString(1, docid);
1032
      pstmt.execute();
1033
      ResultSet rs = pstmt.getResultSet();
1034
      boolean tablehasrows = rs.next();
1035
      if(tablehasrows)
1036
      {
1037
        xml_revs = true;
1038
      }
1039

    
1040
      sb = new StringBuffer();
1041
      sb.append("select docid from xml_documents where docid like '");
1042
      sb.append(docid).append("'");
1043
      pstmt.close();
1044
      pstmt = dbConn.prepareStatement(sb.toString());
1045
      //increase usage count
1046
      dbConn.increaseUsageCount(1);
1047
      pstmt.execute();
1048
      rs = pstmt.getResultSet();
1049
      tablehasrows = rs.next();
1050
      pstmt.close();
1051
      if(tablehasrows)
1052
      {
1053
        xml_docs = true;
1054
      }
1055

    
1056
      if(xml_docs && xml_revs)
1057
      {
1058
        return false;
1059
      }
1060
      else if(xml_docs && !xml_revs)
1061
      {
1062
        return false;
1063
      }
1064
      else if(!xml_docs && xml_revs)
1065
      {
1066
        return true;
1067
      }
1068
      else if(!xml_docs && !xml_revs)
1069
      {
1070
        return true;
1071
      }
1072
    }
1073
    catch(Exception e)
1074
    {
1075
      logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1076
      logReplication.error("ReplicationHandler.alreadyDeleted - general error in alreadyDeleted: " +
1077
                          e.getMessage());
1078
      throw new HandlerException("ReplicationHandler.alreadyDeleted - general error: " 
1079
    		  + e.getMessage());
1080
    }
1081
    finally
1082
    {
1083
      try
1084
      {
1085
        pstmt.close();
1086
      }//try
1087
      catch (SQLException ee)
1088
      {
1089
    	logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1090
        logReplication.error("ReplicationHandler.alreadyDeleted - Error in replicationHandler.alreadyDeleted "+
1091
                          "to close pstmt: "+ee.getMessage());
1092
        throw new HandlerException("ReplicationHandler.alreadyDeleted - SQL error when closing prepared statement: " 
1093
      		  + ee.getMessage());
1094
      }//catch
1095
      finally
1096
      {
1097
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1098
      }//finally
1099
    }//finally
1100
    return false;
1101
  }
1102

    
1103

    
1104
  /**
1105
   * Method to initialize the message parser
1106
   */
1107
  public static XMLReader initParser(DefaultHandler dh)
1108
          throws HandlerException
1109
  {
1110
    XMLReader parser = null;
1111

    
1112
    try {
1113
      ContentHandler chandler = dh;
1114

    
1115
      // Get an instance of the parser
1116
      String parserName = PropertyService.getProperty("xml.saxparser");
1117
      parser = XMLReaderFactory.createXMLReader(parserName);
1118

    
1119
      // Turn off validation
1120
      parser.setFeature("http://xml.org/sax/features/validation", false);
1121

    
1122
      parser.setContentHandler((ContentHandler)chandler);
1123
      parser.setErrorHandler((ErrorHandler)chandler);
1124

    
1125
    } catch (SAXException se) {
1126
      throw new HandlerException("ReplicationHandler.initParser - Sax error when " 
1127
    		  + " initializing parser: " + se.getMessage());
1128
    } catch (PropertyNotFoundException pnfe) {
1129
        throw new HandlerException("ReplicationHandler.initParser - Property error when " 
1130
      		  + " getting parser name: " + pnfe.getMessage());
1131
    } 
1132

    
1133
    return parser;
1134
  }
1135

    
1136
  /**
1137
	 * This method will combine given time string(in short format) to current
1138
	 * date. If the given time (e.g 10:00 AM) passed the current time (e.g 2:00
1139
	 * PM Aug 21, 2005), then the time will set to second day, 10:00 AM Aug 22,
1140
	 * 2005. If the given time (e.g 10:00 AM) haven't passed the current time
1141
	 * (e.g 8:00 AM Aug 21, 2005) The time will set to be 10:00 AM Aug 21, 2005.
1142
	 * 
1143
	 * @param givenTime
1144
	 *            the format should be "10:00 AM " or "2:00 PM"
1145
	 * @return
1146
	 * @throws Exception
1147
	 */
1148
	public static Date combinateCurrentDateAndGivenTime(String givenTime) throws HandlerException
1149
  {
1150
	  try {
1151
     Date givenDate = parseTime(givenTime);
1152
     Date newDate = null;
1153
     Date now = new Date();
1154
     String currentTimeString = getTimeString(now);
1155
     Date currentTime = parseTime(currentTimeString); 
1156
     if ( currentTime.getTime() >= givenDate.getTime())
1157
     {
1158
        logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today already pass the given time, we should set it as tomorrow");
1159
        String dateAndTime = getDateString(now) + " " + givenTime;
1160
        Date combinationDate = parseDateTime(dateAndTime);
1161
        // new date should plus 24 hours to make is the second day
1162
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
1163
     }
1164
     else
1165
     {
1166
         logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today haven't pass the given time, we should it as today");
1167
         String dateAndTime = getDateString(now) + " " + givenTime;
1168
         newDate = parseDateTime(dateAndTime);
1169
     }
1170
     logReplication.warn("ReplicationHandler.combinateCurrentDateAndGivenTime - final setting time is "+ newDate.toString());
1171
     return newDate;
1172
	  } catch (ParseException pe) {
1173
		  throw new HandlerException("ReplicationHandler.combinateCurrentDateAndGivenTime - "
1174
				  + "parsing error: "  + pe.getMessage());
1175
	  }
1176
  }
1177

    
1178
  /*
1179
	 * parse a given string to Time in short format. For example, given time is
1180
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1181
	 */
1182
  private static Date parseTime(String timeString) throws ParseException
1183
  {
1184
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1185
    Date time = format.parse(timeString); 
1186
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1187
                              +time.toString());
1188
    return time;
1189

    
1190
  }
1191
  
1192
  /*
1193
   * Parse a given string to date and time. Date format is long and time
1194
   * format is short.
1195
   */
1196
  private static Date parseDateTime(String timeString) throws ParseException
1197
  {
1198
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
1199
    Date time = format.parse(timeString);
1200
    logReplication.info("ReplicationHandler.parseDateTime - Date string is after parse a time string "+
1201
                             time.toString());
1202
    return time;
1203
  }
1204
  
1205
  /*
1206
   * Get a date string from a Date object. The date format will be long
1207
   */
1208
  private static String getDateString(Date now)
1209
  {
1210
     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
1211
     String s = df.format(now);
1212
     logReplication.info("ReplicationHandler.getDateString - Today is " + s);
1213
     return s;
1214
  }
1215
  
1216
  /*
1217
   * Get a time string from a Date object, the time format will be short
1218
   */
1219
  private static String getTimeString(Date now)
1220
  {
1221
     DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
1222
     String s = df.format(now);
1223
     logReplication.info("ReplicationHandler.getTimeString - Time is " + s);
1224
     return s;
1225
  }
1226
  
1227
  
1228
  /*
1229
	 * This method will go through the docid list both in xml_Documents table
1230
	 * and in xml_revisions table @author tao
1231
	 */
1232
	private void handleDocList(Vector<Vector<String>> docList, String tableName) {
1233
		boolean dataFile = false;
1234
		for (int j = 0; j < docList.size(); j++) {
1235
			// initial dataFile is false
1236
			dataFile = false;
1237
			// w is information for one document, information contain
1238
			// docid, rev, server or datafile.
1239
			Vector<String> w = new Vector<String>(docList.elementAt(j));
1240
			// Check if the vector w contain "datafile"
1241
			// If it has, this document is data file
1242
			try {
1243
				if (w.contains((String) PropertyService.getProperty("replication.datafileflag"))) {
1244
					dataFile = true;
1245
				}
1246
			} catch (PropertyNotFoundException pnfe) {
1247
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1248
				logReplication.error("ReplicationHandler.handleDocList - Could not retrieve data file flag property.  "
1249
						+ "Leaving as false: " + pnfe.getMessage());
1250
			}
1251
			// logMetacat.debug("w: " + w.toString());
1252
			// Get docid
1253
			String docid = (String) w.elementAt(0);
1254
			logReplication.info("docid: " + docid);
1255
			// Get revision number
1256
			int rev = Integer.parseInt((String) w.elementAt(1));
1257
			logReplication.info("rev: " + rev);
1258
			// Get remote server name (it is may not be doc home server because
1259
			// the new hub feature
1260
			String remoteServer = (String) w.elementAt(2);
1261
			remoteServer = remoteServer.trim();
1262

    
1263
			try {
1264
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1265
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1266
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1267
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1268
				} else {
1269
					continue;
1270
				}
1271

    
1272
			} catch (Exception e) {
1273
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1274
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1275
						+ " in time replication" + e.getMessage());
1276
				continue;
1277
			}
1278
			
1279
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1280
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount + 
1281
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1282
	        }
1283
	        
1284
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1285
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount + 
1286
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1287
	        }
1288

    
1289
		}// for update docs
1290

    
1291
	}
1292
   
1293
   /*
1294
	 * This method will handle doc in xml_documents table.
1295
	 */
1296
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
1297
                                        throws HandlerException
1298
   {
1299
       // compare the update rev and local rev to see what need happen
1300
       int localrev = -1;
1301
       String action = null;
1302
       boolean flag = false;
1303
       try
1304
       {
1305
    	 long docQueryStartTime = System.currentTimeMillis();
1306
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1307
         long docQueryEndTime = System.currentTimeMillis();
1308
         _xmlDocQueryTime += (docQueryEndTime - docQueryStartTime);
1309
         _xmlDocQueryCount++;
1310
       }
1311
       catch (SQLException e)
1312
       {
1313
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1314
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1315
                                " be found because " + e.getMessage());
1316
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - " + DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1317
                 "written because error happend to find it's local revision");
1318
         DOCERRORNUMBER++;
1319
         throw new HandlerException ("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1320
                 " be found: " + e.getMessage());
1321
       }
1322
       logReplication.info("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " is "+
1323
                               localrev);
1324

    
1325
       //check the revs for an update because this document is in the
1326
       //local DB, it might be out of date.
1327
       if (localrev == -1)
1328
       {
1329
          // check if the revision is in the revision table
1330
    	   Vector<Integer> localRevVector = null;
1331
    	 try {
1332
        	 long revQueryStartTime = System.currentTimeMillis();
1333
    		 localRevVector = DBUtil.getRevListFromRevisionTable(docid);
1334
             long revQueryEndTime = System.currentTimeMillis();
1335
             _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1336
             _xmlRevQueryCount++;
1337
    	 } catch (SQLException sqle) {
1338
    		 throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - SQL error " 
1339
    				 + " when getting rev list for docid: " + docid + " : " + sqle.getMessage());
1340
    	 }
1341
         if (localRevVector != null && localRevVector.contains(new Integer(rev)))
1342
         {
1343
             // this version was deleted, so don't need replicate
1344
             flag = false;
1345
         }
1346
         else
1347
         {
1348
           //insert this document as new because it is not in the local DB
1349
           action = "INSERT";
1350
           flag = true;
1351
         }
1352
       }
1353
       else
1354
       {
1355
         if(localrev == rev)
1356
         {
1357
           // Local meatacat has the same rev to remote host, don't need
1358
           // update and flag set false
1359
           flag = false;
1360
         }
1361
         else if(localrev < rev)
1362
         {
1363
           //this document needs to be updated so send an read request
1364
           action = "UPDATE";
1365
           flag = true;
1366
         }
1367
       }
1368
       
1369
       String accNumber = null;
1370
       try {
1371
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1372
       } catch (PropertyNotFoundException pnfe) {
1373
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - error getting " 
1374
    			   + "account number separator : " + pnfe.getMessage());
1375
       }
1376
       // this is non-data file
1377
       if(flag && !dataFile)
1378
       {
1379
         try
1380
         {
1381
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1382
         }
1383
         catch(HandlerException he)
1384
         {
1385
           // skip this document
1386
           throw he;
1387
         }
1388
       }//if for non-data file
1389

    
1390
        // this is for data file
1391
       if(flag && dataFile)
1392
       {
1393
         try
1394
         {
1395
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1396
         }
1397
         catch(HandlerException he)
1398
         {
1399
           // skip this data file
1400
           throw he;
1401
         }
1402

    
1403
       }//for data file
1404
   }
1405
   
1406
   /*
1407
    * This method will handle doc in xml_documents table.
1408
    */
1409
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile) 
1410
                                        throws HandlerException
1411
   {
1412
       // compare the update rev and local rev to see what need happen
1413
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - In handle repliation revsion table");
1414
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - the docid is "+ docid);
1415
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - The rev is "+rev);
1416
       Vector<Integer> localrev = null;
1417
       String action = "INSERT";
1418
       boolean flag = false;
1419
       try
1420
       {
1421
      	 long revQueryStartTime = System.currentTimeMillis();
1422
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1423
         long revQueryEndTime = System.currentTimeMillis();
1424
         _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1425
         _xmlRevQueryCount++;
1426
       }
1427
       catch (SQLException sqle)
1428
       {
1429
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1430
         logReplication.error("ReplicationHandler.handleDocInXMLRevisions - Local rev for docid "+ docid + " could not "+
1431
                                " be found because " + sqle.getMessage());
1432
         REVERRORNUMBER++;
1433
         throw new HandlerException ("ReplicationHandler.handleDocInXMLRevisions - SQL exception getting rev list: " 
1434
        		 + sqle.getMessage());
1435
       }
1436
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - rev list in xml_revision table for docid "+ docid + " is "+
1437
                               localrev.toString());
1438
       
1439
       // if the rev is not in the xml_revision, we need insert it
1440
       if (!localrev.contains(new Integer(rev)))
1441
       {
1442
           flag = true;    
1443
       }
1444
     
1445
       String accNumber = null;
1446
       try {
1447
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1448
       } catch (PropertyNotFoundException pnfe) {
1449
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLRevisions - error getting " 
1450
    			   + "account number separator : " + pnfe.getMessage());
1451
       }
1452
       // this is non-data file
1453
       if(flag && !dataFile)
1454
       {
1455
         try
1456
         {
1457
           
1458
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1459
         }
1460
         catch(HandlerException he)
1461
         {
1462
           // skip this document
1463
           throw he;
1464
         }
1465
       }//if for non-data file
1466

    
1467
        // this is for data file
1468
       if(flag && dataFile)
1469
       {
1470
         try
1471
         {
1472
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1473
         }
1474
         catch(HandlerException he)
1475
         {
1476
           // skip this data file
1477
           throw he;
1478
         }
1479

    
1480
       }//for data file
1481
   }
1482
   
1483
   /*
1484
    * Return a ip address for given url
1485
    */
1486
   private String getIpFromURL(URL url)
1487
   {
1488
	   String ip = null;
1489
	   try
1490
	   {
1491
	      InetAddress address = InetAddress.getByName(url.getHost());
1492
	      ip = address.getHostAddress();
1493
	   }
1494
	   catch(UnknownHostException e)
1495
	   {
1496
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1497
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1498
                   +e.getMessage());
1499
	   }
1500

    
1501
	   return ip;
1502
   }
1503
  
1504
}
1505

    
(4-4/8)