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: 2013-06-20 16:49:33 -0700 (Thu, 20 Jun 2013) $'
10
 * '$Revision: 7812 $'
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.Date;
42
import java.util.Hashtable;
43
import java.util.TimerTask;
44
import java.util.Vector;
45

    
46

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

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

    
81

    
82

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

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

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

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

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

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

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

    
227

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

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

    
345
  }//update
346

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

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

    
376
      // Try get the docid info from remote server
377
      DocInfoHandler dih = new DocInfoHandler();
378
      XMLReader docinfoParser = initParser(dih);
379
      String docInfoURLStr = "https://" + remoteserver +
380
                       "?server="+MetacatUtil.getLocalReplicationServerName()+
381
                       "&action=getdocumentinfo&docid="+accNumber;
382
      docInfoURLStr = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLStr);
383
      URL docinfoUrl = new URL(docInfoURLStr);
384
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Sending message: " + docinfoUrl.toString());
385
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
386
      
387
      // strip out the system metadata portion
388
      String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
389
   	  docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);
390
      
391
   	  // process system metadata if we have it
392
      if (systemMetadataXML != null) {
393
    	  SystemMetadata sysMeta = 
394
    		  TypeMarshaller.unmarshalTypeFromStream(
395
    				  SystemMetadata.class, 
396
    				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
397
    	  // need the guid-to-docid mapping
398
    	  if (!IdentifierManager.getInstance().mappingExists(sysMeta.getIdentifier().getValue())) {
399
	      	  IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), accNumber);
400
    	  }
401
      	  // save the system metadata
402
    	  logReplication.debug("Saving SystemMetadata to shared map: " + sysMeta.getIdentifier().getValue());
403
      	  HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
404
      	  // submit for indexing
405
          HazelcastService.getInstance().getIndexQueue().add(sysMeta);
406
      }
407
   	  
408
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
409
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
410
      // Get home server of the docid
411
      String docHomeServer = docinfoHash.get("home_server");
412
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doc home server in repl: "+docHomeServer);
413
     
414
      // dates
415
      String createdDateString = docinfoHash.get("date_created");
416
      String updatedDateString = docinfoHash.get("date_updated");
417
      Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
418
      Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
419
      
420
      //docid should include rev number too
421
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
422
                                              (String)docinfoHash.get("rev");*/
423
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - docid in repl: "+accNumber);
424
      String docType = docinfoHash.get("doctype");
425
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doctype in repl: "+docType);
426

    
427
      String parserBase = null;
428
      // this for eml2 and we need user eml2 parser
429
      if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
430
      {
431
         parserBase = DocumentImpl.EML200;
432
      }
433
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
434
      {
435
        parserBase = DocumentImpl.EML200;
436
      }
437
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
438
      {
439
        parserBase = DocumentImpl.EML210;
440
      }
441
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_1NAMESPACE))
442
      {
443
        parserBase = DocumentImpl.EML210;
444
      }
445
      // Write the document into local host
446
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false, false);
447
      String newDocid = wrapper.writeReplication(dbConn,
448
                              newxmldoc,
449
                              docinfoHash.get("public_access"),
450
                              null,  /* the dtd text */
451
                              actions,
452
                              accNumber,
453
                              null, //docinfoHash.get("user_owner"),                              
454
                              null, /* null for groups[] */
455
                              docHomeServer,
456
                              remoteserver, tableName, true,// true is for time replication 
457
                              createdDate,
458
                              updatedDate);
459
      
460
      //set the user information
461
      String user = (String) docinfoHash.get("user_owner");
462
      String updated = (String) docinfoHash.get("user_updated");
463
      ReplicationService.updateUserOwner(dbConn, accNumber, user, updated);
464
      
465
      //process extra access rules 
466
      try {
467
      	// check if we had a guid -> docid mapping
468
      	String docid = DocumentUtil.getDocIdFromAccessionNumber(accNumber);
469
      	int rev = DocumentUtil.getRevisionFromAccessionNumber(accNumber);
470
      	IdentifierManager.getInstance().getGUID(docid, rev);
471
      	// no need to create the mapping if we have it
472
      } catch (McdbDocNotFoundException mcdbe) {
473
      	// create mapping if we don't
474
      	IdentifierManager.getInstance().createMapping(accNumber, accNumber);
475
      }
476
      Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
477
      if (xmlAccessDAOList != null) {
478
      	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
479
      	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
480
      		if (!acfsf.accessControlExists(xmlAccessDAO)) {
481
      			acfsf.insertPermissions(xmlAccessDAO);
482
      		}
483
          }
484
      }
485
      
486
      
487
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Successfully replicated doc " + accNumber);
488
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
489
      {
490
        logReplication.info("ReplicationHandler.handleSingleXMLDocument - " + DOCINSERTNUMBER + " Wrote xml doc " + accNumber +
491
                                     " into "+tableName + " from " +
492
                                         remoteserver);
493
        DOCINSERTNUMBER++;
494
      }
495
      else
496
      {
497
          logReplication.info("ReplicationHandler.handleSingleXMLDocument - " +REVINSERTNUMBER + " Wrote xml doc " + accNumber +
498
                  " into "+tableName + " from " +
499
                      remoteserver);
500
          REVINSERTNUMBER++;
501
      }
502
      String ip = getIpFromURL(u);
503
      EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, accNumber, actions);
504
      
505

    
506
    }//try
507
    catch(Exception e)
508
    {
509
        
510
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
511
        {
512
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
513
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
514
                                       " into "+tableName + " from " +
515
                                           remoteserver + " because "+e.getMessage());
516
          DOCERRORNUMBER++;
517
        }
518
        else
519
        {
520
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
521
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
522
                    " into "+tableName + " from " +
523
                        remoteserver +" because "+e.getMessage());
524
            REVERRORNUMBER++;
525
        }
526
        logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
527
        logReplication.error("ReplicationHandler.handleSingleXMLDocument - Failed to write doc " + accNumber +
528
                                      " into db because " + e.getMessage(), e);
529
      throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - generic exception " 
530
    		  + "writing Replication: " +e.getMessage());
531
    }
532
    finally
533
    {
534
       //return DBConnection
535
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
536
    }//finally
537
    logMetacat.info("replication.create localId:" + accNumber);
538
  }
539

    
540

    
541

    
542
  /* Handle replicate single xml document*/
543
  private void handleSingleDataFile(String remoteserver, String actions,
544
                                    String accNumber, String tableName)
545
               throws HandlerException
546
  {
547
    logReplication.info("ReplicationHandler.handleSingleDataFile - Try to replicate data file: " + accNumber);
548
    DBConnection dbConn = null;
549
    int serialNumber = -1;
550
    try
551
    {
552
      // Get DBConnection from pool
553
      dbConn=DBConnectionPool.
554
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
555
      serialNumber=dbConn.getCheckOutSerialNumber();
556
      // Try get docid info from remote server
557
      DocInfoHandler dih = new DocInfoHandler();
558
      XMLReader docinfoParser = initParser(dih);
559
      String docInfoURLString = "https://" + remoteserver +
560
                  "?server="+MetacatUtil.getLocalReplicationServerName()+
561
                  "&action=getdocumentinfo&docid="+accNumber;
562
      docInfoURLString = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLString);
563
      URL docinfoUrl = new URL(docInfoURLString);
564

    
565
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
566
      
567
      // strip out the system metadata portion
568
      String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
569
   	  docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);  
570
   	  
571
   	  // process system metadata
572
      if (systemMetadataXML != null) {
573
    	  SystemMetadata sysMeta = 
574
    		TypeMarshaller.unmarshalTypeFromStream(
575
    				  SystemMetadata.class, 
576
    				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
577
    	  // need the guid-to-docid mapping
578
    	  if (!IdentifierManager.getInstance().mappingExists(sysMeta.getIdentifier().getValue())) {
579
	      	  IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), accNumber);
580
    	  }
581
    	  // save the system metadata
582
    	  HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
583
    	  // submit for indexing
584
          HazelcastService.getInstance().getIndexQueue().add(sysMeta);
585

    
586
      }
587
   	  
588
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
589
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
590
      
591
      // Get docid name (such as acl or dataset)
592
      String docName = docinfoHash.get("docname");
593
      // Get doc type (eml public id)
594
      String docType = docinfoHash.get("doctype");
595
      // Get docid home sever. it might be different to remoteserver
596
      // because of hub feature
597
      String docHomeServer = docinfoHash.get("home_server");
598
      String createdDateString = docinfoHash.get("date_created");
599
      String updatedDateString = docinfoHash.get("date_updated");
600
      Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
601
      Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
602
      //docid should include rev number too
603
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
604
                                              (String)docinfoHash.get("rev");*/
605

    
606
      String datafilePath = PropertyService.getProperty("application.datafilepath");
607
      // Get data file content
608
      String readDataURLString = "https://" + remoteserver + "?server="+
609
                                        MetacatUtil.getLocalReplicationServerName()+
610
                                            "&action=readdata&docid="+accNumber;
611
      readDataURLString = MetacatUtil.replaceWhiteSpaceForURL(readDataURLString);
612
      URL u = new URL(readDataURLString);
613
      InputStream input = ReplicationService.getURLStream(u);
614
      //register data file into xml_documents table and wite data file
615
      //into file system
616
      if ( input != null)
617
      {
618
        DocumentImpl.writeDataFileInReplication(input,
619
                                                datafilePath,
620
                                                docName,docType,
621
                                                accNumber,
622
                                                null,
623
                                                docHomeServer,
624
                                                remoteserver,
625
                                                tableName,
626
                                                true, //true means timed replication
627
                                                createdDate,
628
                                                updatedDate);
629
                                         
630
        //set the user information
631
        String user = (String) docinfoHash.get("user_owner");
632
		String updated = (String) docinfoHash.get("user_updated");
633
        ReplicationService.updateUserOwner(dbConn, accNumber, user, updated);
634
        
635
        //process extra access rules
636
        try {
637
        	// check if we had a guid -> docid mapping
638
        	String docid = DocumentUtil.getDocIdFromAccessionNumber(accNumber);
639
        	int rev = DocumentUtil.getRevisionFromAccessionNumber(accNumber);
640
        	IdentifierManager.getInstance().getGUID(docid, rev);
641
        	// no need to create the mapping if we have it
642
        } catch (McdbDocNotFoundException mcdbe) {
643
        	// create mapping if we don't
644
        	IdentifierManager.getInstance().createMapping(accNumber, accNumber);
645
        }
646
        Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
647
        if (xmlAccessDAOList != null) {
648
        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
649
        	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
650
        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
651
        			acfsf.insertPermissions(xmlAccessDAO);
652
        		}
653
            }
654
        }
655
        
656
        logReplication.info("ReplicationHandler.handleSingleDataFile - Successfully to write datafile " + accNumber);
657
        /*MetacatReplication.replLog("wrote datafile " + accNumber + " from " +
658
                                    remote server);*/
659
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
660
        {
661
          logReplication.info("ReplicationHandler.handleSingleDataFile - " + DOCINSERTNUMBER + " Wrote data file" + accNumber +
662
                                       " into "+tableName + " from " +
663
                                           remoteserver);
664
          DOCINSERTNUMBER++;
665
        }
666
        else
667
        {
668
            logReplication.info("ReplicationHandler.handleSingleDataFile - " + REVINSERTNUMBER + " Wrote data file" + accNumber +
669
                    " into "+tableName + " from " +
670
                        remoteserver);
671
            REVINSERTNUMBER++;
672
        }
673
        String ip = getIpFromURL(u);
674
        EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, accNumber, actions);
675
        
676
      }//if
677
      else
678
      {
679
         logReplication.info("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
680
         throw new HandlerException("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
681
      }//else
682

    
683
    }//try
684
    catch(Exception e)
685
    {
686
      /*MetacatReplication.replErrorLog("Failed to try wrote data file " + accNumber +
687
                                      " because " +e.getMessage());*/
688
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
689
      {
690
    	logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
691
    	logReplication.error("ReplicationHandler.handleSingleDataFile - " + DOCERRORNUMBER + " Failed to write data file " + accNumber +
692
                                     " into " + tableName + " from " +
693
                                         remoteserver + " because " + e.getMessage());
694
        DOCERRORNUMBER++;
695
      }
696
      else
697
      {
698
    	  logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
699
    	  logReplication.error("ReplicationHandler.handleSingleDataFile - " + REVERRORNUMBER + " Failed to write data file" + accNumber +
700
                  " into " + tableName + " from " +
701
                      remoteserver +" because "+ e.getMessage());
702
          REVERRORNUMBER++;
703
      }
704
      logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
705
      logReplication.error("ReplicationHandler.handleSingleDataFile - Failed to try wrote datafile " + accNumber +
706
                                      " because " + e.getMessage());
707
      throw new HandlerException("ReplicationHandler.handleSingleDataFile - generic exception " 
708
    		  + "writing Replication: " + e.getMessage());
709
    }
710
    finally
711
    {
712
       //return DBConnection
713
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
714
    }//finally
715
    logMetacat.info("replication.create localId:" + accNumber);
716
  }
717

    
718

    
719

    
720
  /* Handle delete single document*/
721
  private void handleDeleteSingleDocument(String docId, String notifyServer)
722
               throws HandlerException
723
  {
724
    logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Try delete doc: "+docId);
725
    DBConnection dbConn = null;
726
    int serialNumber = -1;
727
    try
728
    {
729
      // Get DBConnection from pool
730
      dbConn=DBConnectionPool.
731
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
732
      serialNumber=dbConn.getCheckOutSerialNumber();
733
      if(!alreadyDeleted(docId))
734
      {
735

    
736
         //because delete method docid should have rev number
737
         //so we just add one for it. This rev number is no sence.
738
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
739
         DocumentImpl.delete(accnum, null, null, notifyServer, false);
740
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Successfully deleted doc " + docId);
741
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Doc " + docId + " deleted");
742
         URL u = new URL("https://"+notifyServer);
743
         String ip = getIpFromURL(u);
744
         EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, docId, "delete");
745
      }
746

    
747
    }//try
748
    catch(McdbDocNotFoundException e)
749
    {
750
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
751
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
752
                                 " in db because because " + e.getMessage());
753
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
754
    		  + "when handling document: " + e.getMessage());
755
    }
756
    catch(InsufficientKarmaException e)
757
    {
758
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
759
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
760
                                 " in db because because " + e.getMessage());
761
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
762
    		  + "when handling document: " + e.getMessage());
763
    }
764
    catch(SQLException e)
765
    {
766
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
767
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
768
                                 " in db because because " + e.getMessage());
769
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
770
    		  + "when handling document: " + e.getMessage());
771
    }
772
    catch(Exception e)
773
    {
774
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
775
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
776
                                 " in db because because " + e.getMessage());
777
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
778
    		  + "when handling document: " + e.getMessage());
779
    }
780
    finally
781
    {
782
       //return DBConnection
783
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
784
    }//finally
785
    logMetacat.info("replication.handleDeleteSingleDocument localId:" + docId);
786
  }
787

    
788
  /* Handle updateLastCheckTimForSingleServer*/
789
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
790
                                                  throws HandlerException
791
  {
792
    String server = repServer.getServerName();
793
    DBConnection dbConn = null;
794
    int serialNumber = -1;
795
    PreparedStatement pstmt = null;
796
    try
797
    {
798
      // Get DBConnection from pool
799
      dbConn=DBConnectionPool.
800
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
801
      serialNumber=dbConn.getCheckOutSerialNumber();
802

    
803
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Try to update last_check for server: "+server);
804
      // Get time from remote server
805
      URL dateurl = new URL("https://" + server + "?server="+
806
      MetacatUtil.getLocalReplicationServerName()+"&action=gettime");
807
      String datexml = ReplicationService.getURLContent(dateurl);
808
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - datexml: "+datexml);
809
      if (datexml != null && !datexml.equals("")) {
810
    	  
811
    	  // parse the ISO datetime
812
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
813
         Date updated = DateTimeMarshaller.deserializeDateToUTC(datestr);
814
         
815
         StringBuffer sql = new StringBuffer();
816
         sql.append("update xml_replication set last_checked = ? ");
817
         sql.append(" where server like ? ");
818
         pstmt = dbConn.prepareStatement(sql.toString());
819
         pstmt.setTimestamp(1, new Timestamp(updated.getTime()));
820
         pstmt.setString(2, server);
821
         
822
         pstmt.executeUpdate();
823
         dbConn.commit();
824
         pstmt.close();
825
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - last_checked updated to "+datestr+" on "
826
                                      + server);
827
      }//if
828
      else
829
      {
830

    
831
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server "  +
832
                                  server + " in db because couldn't get time "
833
                                  );
834
         throw new Exception("Couldn't get time for server "+ server);
835
      }
836

    
837
    }//try
838
    catch(Exception e)
839
    {
840
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
841
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
842
                                server + " in db because because " + e.getMessage());
843
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - " 
844
    		  + "Error updating last checked time: " + e.getMessage());
845
    }
846
    finally
847
    {
848
       //return DBConnection
849
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
850
    }//finally
851
  }
852
  
853
  	/**
854
	 * Handle replicate system metadata
855
	 * 
856
	 * @param remoteserver
857
	 * @param guid
858
	 * @throws HandlerException
859
	 */
860
	private void handleSystemMetadata(String remoteserver, String guid) 
861
		throws HandlerException {
862
		try {
863

    
864
			// Try get the system metadata from remote server
865
			String sysMetaURLStr = "https://" + remoteserver + "?server="
866
					+ MetacatUtil.getLocalReplicationServerName()
867
					+ "&action=getsystemmetadata&guid=" + guid;
868
			sysMetaURLStr = MetacatUtil.replaceWhiteSpaceForURL(sysMetaURLStr);
869
			URL sysMetaUrl = new URL(sysMetaURLStr);
870
			logReplication.info("ReplicationHandler.handleSystemMetadata - Sending message: "
871
							+ sysMetaUrl.toString());
872
			String systemMetadataXML = ReplicationService.getURLContent(sysMetaUrl);
873

    
874
			logReplication.info("ReplicationHandler.handleSystemMetadata - guid in repl: " + guid);
875

    
876
			// process system metadata
877
			if (systemMetadataXML != null) {
878
				SystemMetadata sysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class,
879
								new ByteArrayInputStream(systemMetadataXML
880
										.getBytes("UTF-8")));
881
				HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
882
				// submit for indexing
883
                HazelcastService.getInstance().getIndexQueue().add(sysMeta);
884
			}
885

    
886
			logReplication.info("ReplicationHandler.handleSystemMetadata - Successfully replicated system metadata for guid: "
887
							+ guid);
888

    
889
			String ip = getIpFromURL(sysMetaUrl);
890
			EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, guid, "systemMetadata");
891

    
892
		} catch (Exception e) {
893
			logMetacat.error("ReplicationHandler.handleSystemMetadata - "
894
					+ ReplicationService.METACAT_REPL_ERROR_MSG);
895
			logReplication
896
					.error("ReplicationHandler.handleSystemMetadata - Failed to write system metadata "
897
							+ guid + " into db because " + e.getMessage());
898
			throw new HandlerException(
899
					"ReplicationHandler.handleSystemMetadata - generic exception "
900
							+ "writing Replication: " + e.getMessage());
901
		}
902

    
903
	}
904

    
905
  /**
906
   * updates xml_catalog with entries from other servers.
907
   */
908
  private void updateCatalog()
909
  {
910
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
911
    // ReplicationServer object in server list
912
    ReplicationServer replServer = null;
913
    PreparedStatement pstmt = null;
914
    String server = null;
915

    
916

    
917
    // Go through each ReplicationServer object in sererlist
918
    for (int j=0; j<serverList.size(); j++)
919
    {
920
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
921
      Vector<String> publicId = new Vector<String>();
922
      try
923
      {
924
        // Get ReplicationServer object from server list
925
        replServer = serverList.serverAt(j);
926
        // Get server name from the ReplicationServer object
927
        server = replServer.getServerName();
928
        // Try to get catalog
929
        URL u = new URL("https://" + server + "?server="+
930
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
931
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
932
        String catxml = ReplicationService.getURLContent(u);
933

    
934
        // Make sure there are not error, no empty string
935
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
936
        {
937
          throw new Exception("Couldn't get catalog list form server " +server);
938
        }
939
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
940
        CatalogMessageHandler cmh = new CatalogMessageHandler();
941
        XMLReader catparser = initParser(cmh);
942
        catparser.parse(new InputSource(new StringReader(catxml)));
943
        //parse the returned catalog xml and put it into a vector
944
        remoteCatalog = cmh.getCatalogVect();
945

    
946
        // Make sure remoteCatalog is not empty
947
        if (remoteCatalog.isEmpty())
948
        {
949
          throw new Exception("Couldn't get catalog list form server " +server);
950
        }
951

    
952
        String localcatxml = ReplicationService.getCatalogXML();
953

    
954
        // Make sure local catalog is no empty
955
        if (localcatxml==null||localcatxml.equals(""))
956
        {
957
          throw new Exception("Couldn't get catalog list form server " +server);
958
        }
959

    
960
        cmh = new CatalogMessageHandler();
961
        catparser = initParser(cmh);
962
        catparser.parse(new InputSource(new StringReader(localcatxml)));
963
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
964

    
965
        //now we have the catalog from the remote server and this local server
966
        //we now need to compare the two and merge the differences.
967
        //the comparison is base on the public_id fields which is the 4th
968
        //entry in each row vector.
969
        publicId = new Vector<String>();
970
        for(int i=0; i<localCatalog.size(); i++)
971
        {
972
          Vector<String> v = new Vector<String>(localCatalog.elementAt(i));
973
          logReplication.info("ReplicationHandler.updateCatalog - v1: " + v.toString());
974
          publicId.add(new String((String)v.elementAt(3)));
975
        }
976
      }//try
977
      catch (Exception e)
978
      {
979
        logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
980
        logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
981
                                    server + " because " +e.getMessage());
982
      }//catch
983

    
984
      for(int i=0; i<remoteCatalog.size(); i++)
985
      {
986
         // DConnection
987
        DBConnection dbConn = null;
988
        // DBConnection checkout serial number
989
        int serialNumber = -1;
990
        try
991
        {
992
            dbConn=DBConnectionPool.
993
                  getDBConnection("ReplicationHandler.updateCatalog");
994
            serialNumber=dbConn.getCheckOutSerialNumber();
995
            Vector<String> v = remoteCatalog.elementAt(i);
996
            //logMetacat.debug("v2: " + v.toString());
997
            //logMetacat.debug("i: " + i);
998
            //logMetacat.debug("remoteCatalog.size(): " + remoteCatalog.size());
999
            //logMetacat.debug("publicID: " + publicId.toString());
1000
            logReplication.info
1001
                              ("ReplicationHandler.updateCatalog - v.elementAt(3): " + (String)v.elementAt(3));
1002
           if(!publicId.contains(v.elementAt(3)))
1003
           { //so we don't have this public id in our local table so we need to
1004
             //add it.
1005
        	   
1006
        	   // check where it is pointing first, before adding
1007
        	   String entryType = (String)v.elementAt(0);
1008
        	   if (entryType.equals(DocumentImpl.SCHEMA)) {
1009
	        	   String nameSpace = (String)v.elementAt(3);
1010
	        	   String schemaLocation = (String)v.elementAt(4);
1011
	        	   SchemaLocationResolver slr = new SchemaLocationResolver(nameSpace, schemaLocation);
1012
	        	   try {
1013
	        		   slr.resolveNameSpace();
1014
	        	   } catch (Exception e) {
1015
	        		   String msg = "Could not save remote schema to xml catalog. " + "nameSpace: " + nameSpace + " location: " + schemaLocation;
1016
	        		   logMetacat.error(msg, e);
1017
	        		   logReplication.error(msg, e);
1018
	        	   }
1019
	        	   // skip whatever else we were going to do
1020
	        	   continue;
1021
        	   }
1022
        	   
1023
             //logMetacat.debug("in if");
1024
             StringBuffer sql = new StringBuffer();
1025
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
1026
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
1027
             sql.append("?,?)");
1028
             //logMetacat.debug("sql: " + sql.toString());
1029
             pstmt = dbConn.prepareStatement(sql.toString());
1030
             pstmt.setString(1, (String)v.elementAt(0));
1031
             pstmt.setString(2, (String)v.elementAt(1));
1032
             pstmt.setString(3, (String)v.elementAt(2));
1033
             pstmt.setString(4, (String)v.elementAt(3));
1034
             pstmt.setString(5, (String)v.elementAt(4));
1035
             pstmt.execute();
1036
             pstmt.close();
1037
             logReplication.info("ReplicationHandler.updateCatalog - Success fully to insert new publicid "+
1038
                               (String)v.elementAt(3) + " from server"+server);
1039
           }
1040
        }
1041
        catch(Exception e)
1042
        {
1043
           logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1044
           logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
1045
                                    server + " because " +e.getMessage());
1046
        }//catch
1047
        finally
1048
        {
1049
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1050
        }//finally
1051
      }//for remote catalog
1052
    }//for server list
1053
    logReplication.info("End of updateCatalog");
1054
  }
1055

    
1056
  /**
1057
   * Method that returns true if docid has already been "deleted" from metacat.
1058
   * This method really implements a truth table for deleted documents
1059
   * The table is (a docid in one of the tables is represented by the X):
1060
   * xml_docs      xml_revs      deleted?
1061
   * ------------------------------------
1062
   *   X             X             FALSE
1063
   *   X             _             FALSE
1064
   *   _             X             TRUE
1065
   *   _             _             TRUE
1066
   */
1067
  private static boolean alreadyDeleted(String docid) throws HandlerException
1068
  {
1069
    DBConnection dbConn = null;
1070
    int serialNumber = -1;
1071
    PreparedStatement pstmt = null;
1072
    try
1073
    {
1074
      dbConn=DBConnectionPool.
1075
                  getDBConnection("ReplicationHandler.alreadyDeleted");
1076
      serialNumber=dbConn.getCheckOutSerialNumber();
1077
      boolean xml_docs = false;
1078
      boolean xml_revs = false;
1079

    
1080
      StringBuffer sb = new StringBuffer();
1081
      sb.append("select docid from xml_revisions where docid like ? ");
1082
      pstmt = dbConn.prepareStatement(sb.toString());
1083
      pstmt.setString(1, docid);
1084
      pstmt.execute();
1085
      ResultSet rs = pstmt.getResultSet();
1086
      boolean tablehasrows = rs.next();
1087
      if(tablehasrows)
1088
      {
1089
        xml_revs = true;
1090
      }
1091

    
1092
      sb = new StringBuffer();
1093
      sb.append("select docid from xml_documents where docid like '");
1094
      sb.append(docid).append("'");
1095
      pstmt.close();
1096
      pstmt = dbConn.prepareStatement(sb.toString());
1097
      //increase usage count
1098
      dbConn.increaseUsageCount(1);
1099
      pstmt.execute();
1100
      rs = pstmt.getResultSet();
1101
      tablehasrows = rs.next();
1102
      pstmt.close();
1103
      if(tablehasrows)
1104
      {
1105
        xml_docs = true;
1106
      }
1107

    
1108
      if(xml_docs && xml_revs)
1109
      {
1110
        return false;
1111
      }
1112
      else if(xml_docs && !xml_revs)
1113
      {
1114
        return false;
1115
      }
1116
      else if(!xml_docs && xml_revs)
1117
      {
1118
        return true;
1119
      }
1120
      else if(!xml_docs && !xml_revs)
1121
      {
1122
        return true;
1123
      }
1124
    }
1125
    catch(Exception e)
1126
    {
1127
      logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1128
      logReplication.error("ReplicationHandler.alreadyDeleted - general error in alreadyDeleted: " +
1129
                          e.getMessage());
1130
      throw new HandlerException("ReplicationHandler.alreadyDeleted - general error: " 
1131
    		  + e.getMessage());
1132
    }
1133
    finally
1134
    {
1135
      try
1136
      {
1137
        pstmt.close();
1138
      }//try
1139
      catch (SQLException ee)
1140
      {
1141
    	logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1142
        logReplication.error("ReplicationHandler.alreadyDeleted - Error in replicationHandler.alreadyDeleted "+
1143
                          "to close pstmt: "+ee.getMessage());
1144
        throw new HandlerException("ReplicationHandler.alreadyDeleted - SQL error when closing prepared statement: " 
1145
      		  + ee.getMessage());
1146
      }//catch
1147
      finally
1148
      {
1149
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1150
      }//finally
1151
    }//finally
1152
    return false;
1153
  }
1154

    
1155

    
1156
  /**
1157
   * Method to initialize the message parser
1158
   */
1159
  public static XMLReader initParser(DefaultHandler dh)
1160
          throws HandlerException
1161
  {
1162
    XMLReader parser = null;
1163

    
1164
    try {
1165
      ContentHandler chandler = dh;
1166

    
1167
      // Get an instance of the parser
1168
      String parserName = PropertyService.getProperty("xml.saxparser");
1169
      parser = XMLReaderFactory.createXMLReader(parserName);
1170

    
1171
      // Turn off validation
1172
      parser.setFeature("http://xml.org/sax/features/validation", false);
1173

    
1174
      parser.setContentHandler((ContentHandler)chandler);
1175
      parser.setErrorHandler((ErrorHandler)chandler);
1176

    
1177
    } catch (SAXException se) {
1178
      throw new HandlerException("ReplicationHandler.initParser - Sax error when " 
1179
    		  + " initializing parser: " + se.getMessage());
1180
    } catch (PropertyNotFoundException pnfe) {
1181
        throw new HandlerException("ReplicationHandler.initParser - Property error when " 
1182
      		  + " getting parser name: " + pnfe.getMessage());
1183
    } 
1184

    
1185
    return parser;
1186
  }
1187

    
1188
  /**
1189
	 * This method will combine given time string(in short format) to current
1190
	 * date. If the given time (e.g 10:00 AM) passed the current time (e.g 2:00
1191
	 * PM Aug 21, 2005), then the time will set to second day, 10:00 AM Aug 22,
1192
	 * 2005. If the given time (e.g 10:00 AM) haven't passed the current time
1193
	 * (e.g 8:00 AM Aug 21, 2005) The time will set to be 10:00 AM Aug 21, 2005.
1194
	 * 
1195
	 * @param givenTime
1196
	 *            the format should be "10:00 AM " or "2:00 PM"
1197
	 * @return
1198
	 * @throws Exception
1199
	 */
1200
	public static Date combinateCurrentDateAndGivenTime(String givenTime) throws HandlerException
1201
  {
1202
	  try {
1203
     Date givenDate = parseTime(givenTime);
1204
     Date newDate = null;
1205
     Date now = new Date();
1206
     String currentTimeString = getTimeString(now);
1207
     Date currentTime = parseTime(currentTimeString); 
1208
     if ( currentTime.getTime() >= givenDate.getTime())
1209
     {
1210
        logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today already pass the given time, we should set it as tomorrow");
1211
        String dateAndTime = getDateString(now) + " " + givenTime;
1212
        Date combinationDate = parseDateTime(dateAndTime);
1213
        // new date should plus 24 hours to make is the second day
1214
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
1215
     }
1216
     else
1217
     {
1218
         logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today haven't pass the given time, we should it as today");
1219
         String dateAndTime = getDateString(now) + " " + givenTime;
1220
         newDate = parseDateTime(dateAndTime);
1221
     }
1222
     logReplication.warn("ReplicationHandler.combinateCurrentDateAndGivenTime - final setting time is "+ newDate.toString());
1223
     return newDate;
1224
	  } catch (ParseException pe) {
1225
		  throw new HandlerException("ReplicationHandler.combinateCurrentDateAndGivenTime - "
1226
				  + "parsing error: "  + pe.getMessage());
1227
	  }
1228
  }
1229

    
1230
  /*
1231
	 * parse a given string to Time in short format. For example, given time is
1232
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1233
	 */
1234
  private static Date parseTime(String timeString) throws ParseException
1235
  {
1236
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1237
    Date time = format.parse(timeString); 
1238
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1239
                              +time.toString());
1240
    return time;
1241

    
1242
  }
1243
  
1244
  /*
1245
   * Parse a given string to date and time. Date format is long and time
1246
   * format is short.
1247
   */
1248
  private static Date parseDateTime(String timeString) throws ParseException
1249
  {
1250
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
1251
    Date time = format.parse(timeString);
1252
    logReplication.info("ReplicationHandler.parseDateTime - Date string is after parse a time string "+
1253
                             time.toString());
1254
    return time;
1255
  }
1256
  
1257
  /*
1258
   * Get a date string from a Date object. The date format will be long
1259
   */
1260
  private static String getDateString(Date now)
1261
  {
1262
     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
1263
     String s = df.format(now);
1264
     logReplication.info("ReplicationHandler.getDateString - Today is " + s);
1265
     return s;
1266
  }
1267
  
1268
  /*
1269
   * Get a time string from a Date object, the time format will be short
1270
   */
1271
  private static String getTimeString(Date now)
1272
  {
1273
     DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
1274
     String s = df.format(now);
1275
     logReplication.info("ReplicationHandler.getTimeString - Time is " + s);
1276
     return s;
1277
  }
1278
  
1279
  
1280
  /*
1281
	 * This method will go through the docid list both in xml_Documents table
1282
	 * and in xml_revisions table @author tao
1283
	 */
1284
	private void handleDocList(Vector<Vector<String>> docList, String tableName) {
1285
		boolean dataFile = false;
1286
		for (int j = 0; j < docList.size(); j++) {
1287
			// initial dataFile is false
1288
			dataFile = false;
1289
			// w is information for one document, information contain
1290
			// docid, rev, server or datafile.
1291
			Vector<String> w = new Vector<String>(docList.elementAt(j));
1292
			// Check if the vector w contain "datafile"
1293
			// If it has, this document is data file
1294
			try {
1295
				if (w.contains((String) PropertyService.getProperty("replication.datafileflag"))) {
1296
					dataFile = true;
1297
				}
1298
			} catch (PropertyNotFoundException pnfe) {
1299
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1300
				logReplication.error("ReplicationHandler.handleDocList - Could not retrieve data file flag property.  "
1301
						+ "Leaving as false: " + pnfe.getMessage());
1302
			}
1303
			// logMetacat.debug("w: " + w.toString());
1304
			// Get docid
1305
			String docid = (String) w.elementAt(0);
1306
			logReplication.info("docid: " + docid);
1307
			// Get revision number
1308
			int rev = Integer.parseInt((String) w.elementAt(1));
1309
			logReplication.info("rev: " + rev);
1310
			// Get remote server name (it is may not be doc home server because
1311
			// the new hub feature
1312
			String remoteServer = (String) w.elementAt(2);
1313
			remoteServer = remoteServer.trim();
1314

    
1315
			try {
1316
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1317
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1318
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1319
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1320
				} else {
1321
					continue;
1322
				}
1323

    
1324
			} catch (Exception e) {
1325
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1326
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1327
						+ " in time replication" + e.getMessage(), e);
1328
				continue;
1329
			}
1330
			
1331
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1332
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount + 
1333
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1334
	        }
1335
	        
1336
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1337
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount + 
1338
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1339
	        }
1340

    
1341
		}// for update docs
1342

    
1343
	}
1344
   
1345
   /*
1346
	 * This method will handle doc in xml_documents table.
1347
	 */
1348
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
1349
                                        throws HandlerException
1350
   {
1351
       // compare the update rev and local rev to see what need happen
1352
       int localrev = -1;
1353
       String action = null;
1354
       boolean flag = false;
1355
       try
1356
       {
1357
    	 long docQueryStartTime = System.currentTimeMillis();
1358
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1359
         long docQueryEndTime = System.currentTimeMillis();
1360
         _xmlDocQueryTime += (docQueryEndTime - docQueryStartTime);
1361
         _xmlDocQueryCount++;
1362
       }
1363
       catch (SQLException e)
1364
       {
1365
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1366
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1367
                                " be found because " + e.getMessage());
1368
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - " + DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1369
                 "written because error happend to find it's local revision");
1370
         DOCERRORNUMBER++;
1371
         throw new HandlerException ("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1372
                 " be found: " + e.getMessage());
1373
       }
1374
       logReplication.info("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " is "+
1375
                               localrev);
1376

    
1377
       //check the revs for an update because this document is in the
1378
       //local DB, it might be out of date.
1379
       if (localrev == -1)
1380
       {
1381
          // check if the revision is in the revision table
1382
    	   Vector<Integer> localRevVector = null;
1383
    	 try {
1384
        	 long revQueryStartTime = System.currentTimeMillis();
1385
    		 localRevVector = DBUtil.getRevListFromRevisionTable(docid);
1386
             long revQueryEndTime = System.currentTimeMillis();
1387
             _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1388
             _xmlRevQueryCount++;
1389
    	 } catch (SQLException sqle) {
1390
    		 throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - SQL error " 
1391
    				 + " when getting rev list for docid: " + docid + " : " + sqle.getMessage());
1392
    	 }
1393
         if (localRevVector != null && localRevVector.contains(new Integer(rev)))
1394
         {
1395
             // this version was deleted, so don't need replicate
1396
             flag = false;
1397
         }
1398
         else
1399
         {
1400
           //insert this document as new because it is not in the local DB
1401
           action = "INSERT";
1402
           flag = true;
1403
         }
1404
       }
1405
       else
1406
       {
1407
         if(localrev == rev)
1408
         {
1409
           // Local meatacat has the same rev to remote host, don't need
1410
           // update and flag set false
1411
           flag = false;
1412
         }
1413
         else if(localrev < rev)
1414
         {
1415
           //this document needs to be updated so send an read request
1416
           action = "UPDATE";
1417
           flag = true;
1418
         }
1419
       }
1420
       
1421
       String accNumber = null;
1422
       try {
1423
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1424
       } catch (PropertyNotFoundException pnfe) {
1425
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - error getting " 
1426
    			   + "account number separator : " + pnfe.getMessage());
1427
       }
1428
       // this is non-data file
1429
       if(flag && !dataFile)
1430
       {
1431
         try
1432
         {
1433
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1434
         }
1435
         catch(HandlerException he)
1436
         {
1437
           // skip this document
1438
           throw he;
1439
         }
1440
       }//if for non-data file
1441

    
1442
        // this is for data file
1443
       if(flag && dataFile)
1444
       {
1445
         try
1446
         {
1447
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1448
         }
1449
         catch(HandlerException he)
1450
         {
1451
           // skip this data file
1452
           throw he;
1453
         }
1454

    
1455
       }//for data file
1456
   }
1457
   
1458
   /*
1459
    * This method will handle doc in xml_documents table.
1460
    */
1461
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile) 
1462
                                        throws HandlerException
1463
   {
1464
       // compare the update rev and local rev to see what need happen
1465
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - In handle repliation revsion table");
1466
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - the docid is "+ docid);
1467
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - The rev is "+rev);
1468
       Vector<Integer> localrev = null;
1469
       String action = "INSERT";
1470
       boolean flag = false;
1471
       try
1472
       {
1473
      	 long revQueryStartTime = System.currentTimeMillis();
1474
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1475
         long revQueryEndTime = System.currentTimeMillis();
1476
         _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1477
         _xmlRevQueryCount++;
1478
       }
1479
       catch (SQLException sqle)
1480
       {
1481
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1482
         logReplication.error("ReplicationHandler.handleDocInXMLRevisions - Local rev for docid "+ docid + " could not "+
1483
                                " be found because " + sqle.getMessage());
1484
         REVERRORNUMBER++;
1485
         throw new HandlerException ("ReplicationHandler.handleDocInXMLRevisions - SQL exception getting rev list: " 
1486
        		 + sqle.getMessage());
1487
       }
1488
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - rev list in xml_revision table for docid "+ docid + " is "+
1489
                               localrev.toString());
1490
       
1491
       // if the rev is not in the xml_revision, we need insert it
1492
       if (!localrev.contains(new Integer(rev)))
1493
       {
1494
           flag = true;    
1495
       }
1496
     
1497
       String accNumber = null;
1498
       try {
1499
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1500
       } catch (PropertyNotFoundException pnfe) {
1501
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLRevisions - error getting " 
1502
    			   + "account number separator : " + pnfe.getMessage());
1503
       }
1504
       // this is non-data file
1505
       if(flag && !dataFile)
1506
       {
1507
         try
1508
         {
1509
           
1510
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1511
         }
1512
         catch(HandlerException he)
1513
         {
1514
           // skip this document
1515
           throw he;
1516
         }
1517
       }//if for non-data file
1518

    
1519
        // this is for data file
1520
       if(flag && dataFile)
1521
       {
1522
         try
1523
         {
1524
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1525
         }
1526
         catch(HandlerException he)
1527
         {
1528
           // skip this data file
1529
           throw he;
1530
         }
1531

    
1532
       }//for data file
1533
   }
1534
   
1535
   /*
1536
    * Return a ip address for given url
1537
    */
1538
   private String getIpFromURL(URL url)
1539
   {
1540
	   String ip = null;
1541
	   try
1542
	   {
1543
	      InetAddress address = InetAddress.getByName(url.getHost());
1544
	      ip = address.getHostAddress();
1545
	   }
1546
	   catch(UnknownHostException e)
1547
	   {
1548
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1549
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1550
                   +e.getMessage());
1551
	   }
1552

    
1553
	   return ip;
1554
   }
1555
  
1556
}
1557

    
(3-3/7)