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: tao $'
9
 *     '$Date: 2014-04-17 14:18:01 -0700 (Thu, 17 Apr 2014) $'
10
 * '$Revision: 8738 $'
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
import org.apache.log4j.Logger;
47
import org.dataone.service.types.v1.SystemMetadata;
48
import org.dataone.service.util.DateTimeMarshaller;
49
import org.dataone.service.util.TypeMarshaller;
50
import org.xml.sax.ContentHandler;
51
import org.xml.sax.ErrorHandler;
52
import org.xml.sax.InputSource;
53
import org.xml.sax.SAXException;
54
import org.xml.sax.XMLReader;
55
import org.xml.sax.helpers.DefaultHandler;
56
import org.xml.sax.helpers.XMLReaderFactory;
57

    
58
import edu.ucsb.nceas.metacat.CatalogMessageHandler;
59
import edu.ucsb.nceas.metacat.DBUtil;
60
import edu.ucsb.nceas.metacat.DocumentImpl;
61
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
62
import edu.ucsb.nceas.metacat.EventLog;
63
import edu.ucsb.nceas.metacat.IdentifierManager;
64
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
65
import edu.ucsb.nceas.metacat.SchemaLocationResolver;
66
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
67
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
68
import edu.ucsb.nceas.metacat.database.DBConnection;
69
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
70
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
71
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
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
   	  SystemMetadata sysMeta = null;
391
   	  // process system metadata if we have it
392
      if (systemMetadataXML != null) {
393
    	  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
      	  
405
      }
406
   	  
407
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
408
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
409
      // Get home server of the docid
410
      String docHomeServer = docinfoHash.get("home_server");
411
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doc home server in repl: "+docHomeServer);
412
     
413
      // dates
414
      String createdDateString = docinfoHash.get("date_created");
415
      String updatedDateString = docinfoHash.get("date_updated");
416
      Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
417
      Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
418
      
419
      //docid should include rev number too
420
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
421
                                              (String)docinfoHash.get("rev");*/
422
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - docid in repl: "+accNumber);
423
      String docType = docinfoHash.get("doctype");
424
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doctype in repl: "+docType);
425

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

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

    
550

    
551

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

    
575
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
576
      
577
      // strip out the system metadata portion
578
      String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
579
   	  docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);  
580
   	  
581
   	  // process system metadata
582
      if (systemMetadataXML != null) {
583
    	  SystemMetadata sysMeta = 
584
    		TypeMarshaller.unmarshalTypeFromStream(
585
    				  SystemMetadata.class, 
586
    				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
587
    	  // need the guid-to-docid mapping
588
    	  if (!IdentifierManager.getInstance().mappingExists(sysMeta.getIdentifier().getValue())) {
589
	      	  IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), accNumber);
590
    	  }
591
    	  // save the system metadata
592
    	  HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
593
    	  // submit for indexing
594
          MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
595

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

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

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

    
728

    
729

    
730
  /* Handle delete single document*/
731
  private void handleDeleteSingleDocument(String docId, String notifyServer)
732
               throws HandlerException
733
  {
734
    logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Try delete doc: "+docId);
735
    DBConnection dbConn = null;
736
    int serialNumber = -1;
737
    try
738
    {
739
      // Get DBConnection from pool
740
      dbConn=DBConnectionPool.
741
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
742
      serialNumber=dbConn.getCheckOutSerialNumber();
743
      if(!alreadyDeleted(docId))
744
      {
745

    
746
         //because delete method docid should have rev number
747
         //so we just add one for it. This rev number is no sence.
748
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
749
         DocumentImpl.delete(accnum, null, null, notifyServer, false);
750
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Successfully deleted doc " + docId);
751
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Doc " + docId + " deleted");
752
         URL u = new URL("https://"+notifyServer);
753
         String ip = getIpFromURL(u);
754
         EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, docId, "delete");
755
      }
756

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

    
798
  /* Handle updateLastCheckTimForSingleServer*/
799
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
800
                                                  throws HandlerException
801
  {
802
    String server = repServer.getServerName();
803
    DBConnection dbConn = null;
804
    int serialNumber = -1;
805
    PreparedStatement pstmt = null;
806
    try
807
    {
808
      // Get DBConnection from pool
809
      dbConn=DBConnectionPool.
810
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
811
      serialNumber=dbConn.getCheckOutSerialNumber();
812

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

    
841
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server "  +
842
                                  server + " in db because couldn't get time "
843
                                  );
844
         throw new Exception("Couldn't get time for server "+ server);
845
      }
846

    
847
    }//try
848
    catch(Exception e)
849
    {
850
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
851
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
852
                                server + " in db because because " + e.getMessage());
853
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - " 
854
    		  + "Error updating last checked time: " + e.getMessage());
855
    }
856
    finally
857
    {
858
       //return DBConnection
859
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
860
    }//finally
861
  }
862
  
863
  	/**
864
	 * Handle replicate system metadata
865
	 * 
866
	 * @param remoteserver
867
	 * @param guid
868
	 * @throws HandlerException
869
	 */
870
	private void handleSystemMetadata(String remoteserver, String guid) 
871
		throws HandlerException {
872
		try {
873

    
874
			// Try get the system metadata from remote server
875
			String sysMetaURLStr = "https://" + remoteserver + "?server="
876
					+ MetacatUtil.getLocalReplicationServerName()
877
					+ "&action=getsystemmetadata&guid=" + guid;
878
			sysMetaURLStr = MetacatUtil.replaceWhiteSpaceForURL(sysMetaURLStr);
879
			URL sysMetaUrl = new URL(sysMetaURLStr);
880
			logReplication.info("ReplicationHandler.handleSystemMetadata - Sending message: "
881
							+ sysMetaUrl.toString());
882
			String systemMetadataXML = ReplicationService.getURLContent(sysMetaUrl);
883

    
884
			logReplication.info("ReplicationHandler.handleSystemMetadata - guid in repl: " + guid);
885

    
886
			// process system metadata
887
			if (systemMetadataXML != null) {
888
				SystemMetadata sysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class,
889
								new ByteArrayInputStream(systemMetadataXML
890
										.getBytes("UTF-8")));
891
				HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
892
				// submit for indexing
893
                MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
894
			}
895

    
896
			logReplication.info("ReplicationHandler.handleSystemMetadata - Successfully replicated system metadata for guid: "
897
							+ guid);
898

    
899
			String ip = getIpFromURL(sysMetaUrl);
900
			EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, guid, "systemMetadata");
901

    
902
		} catch (Exception e) {
903
			logMetacat.error("ReplicationHandler.handleSystemMetadata - "
904
					+ ReplicationService.METACAT_REPL_ERROR_MSG);
905
			logReplication
906
					.error("ReplicationHandler.handleSystemMetadata - Failed to write system metadata "
907
							+ guid + " into db because " + e.getMessage());
908
			throw new HandlerException(
909
					"ReplicationHandler.handleSystemMetadata - generic exception "
910
							+ "writing Replication: " + e.getMessage());
911
		}
912

    
913
	}
914

    
915
  /**
916
   * updates xml_catalog with entries from other servers.
917
   */
918
  private void updateCatalog()
919
  {
920
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
921
    // ReplicationServer object in server list
922
    ReplicationServer replServer = null;
923
    PreparedStatement pstmt = null;
924
    String server = null;
925

    
926

    
927
    // Go through each ReplicationServer object in sererlist
928
    for (int j=0; j<serverList.size(); j++)
929
    {
930
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
931
      Vector<String> publicId = new Vector<String>();
932
      try
933
      {
934
        // Get ReplicationServer object from server list
935
        replServer = serverList.serverAt(j);
936
        // Get server name from the ReplicationServer object
937
        server = replServer.getServerName();
938
        // Try to get catalog
939
        URL u = new URL("https://" + server + "?server="+
940
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
941
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
942
        String catxml = ReplicationService.getURLContent(u);
943

    
944
        // Make sure there are not error, no empty string
945
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
946
        {
947
          throw new Exception("Couldn't get catalog list form server " +server);
948
        }
949
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
950
        CatalogMessageHandler cmh = new CatalogMessageHandler();
951
        XMLReader catparser = initParser(cmh);
952
        catparser.parse(new InputSource(new StringReader(catxml)));
953
        //parse the returned catalog xml and put it into a vector
954
        remoteCatalog = cmh.getCatalogVect();
955

    
956
        // Make sure remoteCatalog is not empty
957
        if (remoteCatalog.isEmpty())
958
        {
959
          throw new Exception("Couldn't get catalog list form server " +server);
960
        }
961

    
962
        String localcatxml = ReplicationService.getCatalogXML();
963

    
964
        // Make sure local catalog is no empty
965
        if (localcatxml==null||localcatxml.equals(""))
966
        {
967
          throw new Exception("Couldn't get catalog list form server " +server);
968
        }
969

    
970
        cmh = new CatalogMessageHandler();
971
        catparser = initParser(cmh);
972
        catparser.parse(new InputSource(new StringReader(localcatxml)));
973
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
974

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

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

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

    
1090
      StringBuffer sb = new StringBuffer();
1091
      sb.append("select docid from xml_revisions where docid like ? ");
1092
      pstmt = dbConn.prepareStatement(sb.toString());
1093
      pstmt.setString(1, docid);
1094
      pstmt.execute();
1095
      ResultSet rs = pstmt.getResultSet();
1096
      boolean tablehasrows = rs.next();
1097
      if(tablehasrows)
1098
      {
1099
        xml_revs = true;
1100
      }
1101

    
1102
      sb = new StringBuffer();
1103
      sb.append("select docid from xml_documents where docid like '");
1104
      sb.append(docid).append("'");
1105
      pstmt.close();
1106
      pstmt = dbConn.prepareStatement(sb.toString());
1107
      //increase usage count
1108
      dbConn.increaseUsageCount(1);
1109
      pstmt.execute();
1110
      rs = pstmt.getResultSet();
1111
      tablehasrows = rs.next();
1112
      pstmt.close();
1113
      if(tablehasrows)
1114
      {
1115
        xml_docs = true;
1116
      }
1117

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

    
1165

    
1166
  /**
1167
   * Method to initialize the message parser
1168
   */
1169
  public static XMLReader initParser(DefaultHandler dh)
1170
          throws HandlerException
1171
  {
1172
    XMLReader parser = null;
1173

    
1174
    try {
1175
      ContentHandler chandler = dh;
1176

    
1177
      // Get an instance of the parser
1178
      String parserName = PropertyService.getProperty("xml.saxparser");
1179
      parser = XMLReaderFactory.createXMLReader(parserName);
1180

    
1181
      // Turn off validation
1182
      parser.setFeature("http://xml.org/sax/features/validation", false);
1183

    
1184
      parser.setContentHandler((ContentHandler)chandler);
1185
      parser.setErrorHandler((ErrorHandler)chandler);
1186

    
1187
    } catch (SAXException se) {
1188
      throw new HandlerException("ReplicationHandler.initParser - Sax error when " 
1189
    		  + " initializing parser: " + se.getMessage());
1190
    } catch (PropertyNotFoundException pnfe) {
1191
        throw new HandlerException("ReplicationHandler.initParser - Property error when " 
1192
      		  + " getting parser name: " + pnfe.getMessage());
1193
    } 
1194

    
1195
    return parser;
1196
  }
1197

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

    
1240
  /*
1241
	 * parse a given string to Time in short format. For example, given time is
1242
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1243
	 */
1244
  private static Date parseTime(String timeString) throws ParseException
1245
  {
1246
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1247
    Date time = format.parse(timeString); 
1248
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1249
                              +time.toString());
1250
    return time;
1251

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

    
1325
			try {
1326
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1327
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1328
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1329
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1330
				} else {
1331
					continue;
1332
				}
1333

    
1334
			} catch (Exception e) {
1335
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1336
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1337
						+ " in time replication" + e.getMessage(), e);
1338
				continue;
1339
			}
1340
			
1341
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1342
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount + 
1343
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1344
	        }
1345
	        
1346
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1347
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount + 
1348
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1349
	        }
1350

    
1351
		}// for update docs
1352

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

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

    
1452
        // this is for data file
1453
       if(flag && dataFile)
1454
       {
1455
         try
1456
         {
1457
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1458
         }
1459
         catch(HandlerException he)
1460
         {
1461
           // skip this data file
1462
           throw he;
1463
         }
1464

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

    
1529
        // this is for data file
1530
       if(flag && dataFile)
1531
       {
1532
         try
1533
         {
1534
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1535
         }
1536
         catch(HandlerException he)
1537
         {
1538
           // skip this data file
1539
           throw he;
1540
         }
1541

    
1542
       }//for data file
1543
   }
1544
   
1545
   /*
1546
    * Return a ip address for given url
1547
    */
1548
   private String getIpFromURL(URL url)
1549
   {
1550
	   String ip = null;
1551
	   try
1552
	   {
1553
	      InetAddress address = InetAddress.getByName(url.getHost());
1554
	      ip = address.getHostAddress();
1555
	   }
1556
	   catch(UnknownHostException e)
1557
	   {
1558
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1559
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1560
                   +e.getMessage());
1561
	   }
1562

    
1563
	   return ip;
1564
   }
1565
  
1566
}
1567

    
(3-3/7)