Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A class to asyncronously do delta-T replication checking
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Chad Berkley
7
 *
8
 *   '$Author: leinfelder $'
9
 *     '$Date: 2011-05-05 15:14:07 -0700 (Thu, 05 May 2011) $'
10
 * '$Revision: 6079 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacat.replication;
28

    
29
import edu.ucsb.nceas.metacat.CatalogMessageHandler;
30
import edu.ucsb.nceas.metacat.DBUtil;
31
import edu.ucsb.nceas.metacat.DocInfoHandler;
32
import edu.ucsb.nceas.metacat.DocumentImpl;
33
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
34
import edu.ucsb.nceas.metacat.EventLog;
35
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
36
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
37
import edu.ucsb.nceas.metacat.accesscontrol.XMLAccessDAO;
38
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
39
import edu.ucsb.nceas.metacat.database.DBConnection;
40
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
41
import edu.ucsb.nceas.metacat.database.DatabaseService;
42
import edu.ucsb.nceas.metacat.properties.PropertyService;
43
import edu.ucsb.nceas.metacat.shared.HandlerException;
44
import edu.ucsb.nceas.metacat.util.MetacatUtil;
45
import edu.ucsb.nceas.metacat.IdentifierManager;
46
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
47

    
48
import java.sql.*;
49
import java.util.*;
50
import java.util.Date;
51
import java.io.*;
52
import java.net.*;
53
import java.text.*;
54

    
55
import org.apache.log4j.Logger;
56
import org.xml.sax.ContentHandler;
57
import org.xml.sax.ErrorHandler;
58
import org.xml.sax.InputSource;
59
import org.xml.sax.SAXException;
60
import org.xml.sax.XMLReader;
61
import org.xml.sax.helpers.XMLReaderFactory;
62
import org.xml.sax.helpers.DefaultHandler;
63

    
64

    
65

    
66
/**
67
 * This class handles deltaT replication checking.  Whenever this TimerTask
68
 * is fired it checks each server in xml_replication for updates and updates
69
 * the local db as needed.
70
 */
71
public class ReplicationHandler extends TimerTask
72
{
73
  int serverCheckCode = 1;
74
  ReplicationServerList serverList = null;
75
  //PrintWriter out;
76
//  private static final AbstractDatabase dbAdapter = MetacatUtil.dbAdapter;
77
  private static Logger logReplication = Logger.getLogger("ReplicationLogging");
78
  private static Logger logMetacat = Logger.getLogger(ReplicationHandler.class);
79
  private static Logger logD1 = Logger.getLogger("DataOneLogger");
80
  
81
  private static int DOCINSERTNUMBER = 1;
82
  private static int DOCERRORNUMBER  = 1;
83
  private static int REVINSERTNUMBER = 1;
84
  private static int REVERRORNUMBER  = 1;
85
  
86
  private static int _xmlDocQueryCount = 0;
87
  private static int _xmlRevQueryCount = 0;
88
  private static long _xmlDocQueryTime = 0;
89
  private static long _xmlRevQueryTime = 0;
90
  
91
  
92
  public ReplicationHandler()
93
  {
94
    //this.out = o;
95
    serverList = new ReplicationServerList();
96
  }
97

    
98
  public ReplicationHandler(int serverCheckCode)
99
  {
100
    //this.out = o;
101
    this.serverCheckCode = serverCheckCode;
102
    serverList = new ReplicationServerList();
103
  }
104

    
105
  /**
106
   * Method that implements TimerTask.run().  It runs whenever the timer is
107
   * fired.
108
   */
109
  public void run()
110
  {
111
    //find out the last_checked time of each server in the server list and
112
    //send a query to each server to see if there are any documents in
113
    //xml_documents with an update_date > last_checked
114
	  
115
      //if serverList is null, metacat don't need to replication
116
      if (serverList==null||serverList.isEmpty())
117
      {
118
        return;
119
      }
120
      updateCatalog();
121
      update();
122
      //conn.close();
123
  }
124

    
125
  /**
126
   * Method that uses revision tagging for replication instead of update_date.
127
   */
128
  private void update()
129
  {
130
	  
131
	  _xmlDocQueryCount = 0;
132
	  _xmlRevQueryCount = 0;
133
	  _xmlDocQueryTime = 0;
134
	  _xmlRevQueryTime = 0;
135
    /*
136
     Pseudo-algorithm
137
     - request a doc list from each server in xml_replication
138
     - check the rev number of each of those documents agains the
139
       documents in the local database
140
     - pull any documents that have a lesser rev number on the local server
141
       from the remote server
142
     - delete any documents that still exist in the local xml_documents but
143
       are in the deletedDocuments tag of the remote host response.
144
     - update last_checked to keep track of the last time it was checked.
145
       (this info is theoretically not needed using this system but probably
146
       should be kept anyway)
147
    */
148

    
149
    ReplicationServer replServer = null; // Variable to store the
150
                                        // ReplicationServer got from
151
                                        // Server list
152
    String server = null; // Variable to store server name
153
//    String update;
154
    Vector<String> responses = new Vector<String>();
155
    URL u;
156
    long replicationStartTime = System.currentTimeMillis();
157
    long timeToGetServerList = 0;
158
    
159
    //Check for every server in server list to get updated list and put
160
    // them in to response
161
    long startTimeToGetServers = System.currentTimeMillis();
162
    for (int i=0; i<serverList.size(); i++)
163
    {
164
        // Get ReplicationServer object from server list
165
        replServer = serverList.serverAt(i);
166
        // Get server name from ReplicationServer object
167
        server = replServer.getServerName().trim();
168
        String result = null;
169
        logReplication.info("ReplicationHandler.update - full update started to: " + server);
170
        // Send command to that server to get updated docid information
171
        try
172
        {
173
          u = new URL("https://" + server + "?server="
174
          +MetacatUtil.getLocalReplicationServerName()+"&action=update");
175
          logReplication.info("ReplicationHandler.update - Sending infomation " +u.toString());
176
          result = ReplicationService.getURLContent(u);
177
        }
178
        catch (Exception e)
179
        {
180
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
181
          logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
182
                       "for server " + server + " because "+e.getMessage());
183
          continue;
184
        }
185

    
186
        //logReplication.info("ReplicationHandler.update - docid: "+server+" "+result);
187
        //check if result have error or not, if has skip it.
188
        if (result.indexOf("<error>")!=-1 && result.indexOf("</error>")!=-1)
189
        {
190
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
191
          logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
192
                       "for server " + server + " because "+result);
193
          continue;
194
        }
195
        //Add result to vector
196
        responses.add(result);
197
    }
198
    timeToGetServerList = System.currentTimeMillis() - startTimeToGetServers;
199

    
200
    //make sure that there is updated file list
201
    //If response is null, metacat don't need do anything
202
    if (responses==null || responses.isEmpty())
203
    {
204
    	logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
205
        logReplication.info( "ReplicationHandler.update - No updated doc list for "+
206
                           "every server and failed to replicate");
207
        return;
208
    }
209

    
210

    
211
    //logReplication.info("ReplicationHandler.update - Responses from remote metacat about updated "+
212
    //               "document information: "+ responses.toString());
213
    
214
    long totalServerListParseTime = 0;
215
    // go through response vector(it contains updated vector and delete vector
216
    for(int i=0; i<responses.size(); i++)
217
    {
218
    	long startServerListParseTime = System.currentTimeMillis();
219
    	XMLReader parser;
220
    	ReplMessageHandler message = new ReplMessageHandler();
221
    	try
222
        {
223
          parser = initParser(message);
224
        }
225
        catch (Exception e)
226
        {
227
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
228
          logReplication.error("ReplicationHandler.update - Failed to replicate becaue couldn't " +
229
                                " initParser for message and " +e.getMessage());
230
           // stop replication
231
           return;
232
        }
233
    	
234
        try
235
        {
236
          parser.parse(new InputSource(
237
                     new StringReader(
238
                     (String)(responses.elementAt(i)))));
239
        }
240
        catch(Exception e)
241
        {
242
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
243
          logReplication.error("ReplicationHandler.update - Couldn't parse one responses "+
244
                                   "because "+ e.getMessage());
245
          continue;
246
        }
247
        //v is the list of updated documents
248
        Vector<Vector<String>> updateList = new Vector<Vector<String>>(message.getUpdatesVect());
249
        logReplication.info("ReplicationHandler.update - The document list size is "+updateList.size()+ " from "+message.getServerName());
250
        //System.out.println("v: " + v.toString());
251
        //d is the list of deleted documents
252
        Vector<Vector<String>> deleteList = new Vector<Vector<String>>(message.getDeletesVect());
253
        //System.out.println("d: " + d.toString());
254
        logReplication.info("ReplicationHandler.update - Update vector size: "+ updateList.size()+" from "+message.getServerName());
255
        logReplication.info("ReplicationHandler.update - Delete vector size: "+ deleteList.size()+" from "+message.getServerName());
256
        logReplication.info("ReplicationHandler.update - The delete document list size is "+deleteList.size()+" from "+message.getServerName());
257
        // go though every element in updated document vector
258
        handleDocList(updateList, DocumentImpl.DOCUMENTTABLE);
259
        //handle deleted docs
260
        for(int k=0; k<deleteList.size(); k++)
261
        { //delete the deleted documents;
262
          Vector<String> w = new Vector<String>(deleteList.elementAt(k));
263
          String docId = (String)w.elementAt(0);
264
          try
265
          {
266
            handleDeleteSingleDocument(docId, server);
267
          }
268
          catch (Exception ee)
269
          {
270
            continue;
271
          }
272
        }//for delete docs
273
        
274
        // handle replicate doc in xml_revision
275
        Vector<Vector<String>> revisionList = new Vector<Vector<String>>(message.getRevisionsVect());
276
        logReplication.info("ReplicationHandler.update - The revision document list size is "+revisionList.size()+ " from "+message.getServerName());
277
        handleDocList(revisionList, DocumentImpl.REVISIONTABLE);
278
        DOCINSERTNUMBER = 1;
279
        DOCERRORNUMBER  = 1;
280
        REVINSERTNUMBER = 1;
281
        REVERRORNUMBER  = 1;
282
        
283
        totalServerListParseTime += (System.currentTimeMillis() - startServerListParseTime);
284
    }//for response
285

    
286
    //updated last_checked
287
    for (int i=0;i<serverList.size(); i++)
288
    {
289
       // Get ReplicationServer object from server list
290
       replServer = serverList.serverAt(i);
291
       try
292
       {
293
         updateLastCheckTimeForSingleServer(replServer);
294
       }
295
       catch(Exception e)
296
       {
297
         continue;
298
       }
299
    }//for
300
    
301
    long replicationEndTime = System.currentTimeMillis();
302
    logMetacat.debug("ReplicationHandler.update - Total replication time: " + 
303
    		(replicationEndTime - replicationStartTime));
304
    logMetacat.debug("ReplicationHandler.update - time to get server list: " + 
305
    		timeToGetServerList);
306
    logMetacat.debug("ReplicationHandler.update - server list parse time: " + 
307
    		totalServerListParseTime);
308
    logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query count: " + 
309
    		_xmlDocQueryCount);
310
    logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query time: " + 
311
    		_xmlDocQueryTime + " ms");
312
    logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query count: " + 
313
    		_xmlRevQueryCount);
314
    logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query time: " + 
315
    		_xmlRevQueryTime + " ms");;
316

    
317
  }//update
318

    
319
  /* Handle replicate single xml document*/
320
  private void handleSingleXMLDocument(String remoteserver, String actions,
321
                                       String accNumber, String tableName)
322
               throws HandlerException
323
  {
324
    DBConnection dbConn = null;
325
    int serialNumber = -1;
326
    try
327
    {
328
      // Get DBConnection from pool
329
      dbConn=DBConnectionPool.
330
                  getDBConnection("ReplicationHandler.handleSingleXMLDocument");
331
      serialNumber=dbConn.getCheckOutSerialNumber();
332
      //if the document needs to be updated or inserted, this is executed
333
      String readDocURLString = "https://" + remoteserver + "?server="+
334
              MetacatUtil.getLocalReplicationServerName()+"&action=read&docid="+accNumber;
335
      readDocURLString = MetacatUtil.replaceWhiteSpaceForURL(readDocURLString);
336
      URL u = new URL(readDocURLString);
337

    
338
      // Get docid content
339
      String newxmldoc = ReplicationService.getURLContent(u);
340
      // If couldn't get skip it
341
      if ( newxmldoc.indexOf("<error>")!= -1 && newxmldoc.indexOf("</error>")!=-1)
342
      {
343
         throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - " + newxmldoc);
344
      }
345
      //logReplication.info("xml documnet:");
346
      //logReplication.info(newxmldoc);
347

    
348
      // Try get the docid info from remote server
349
      DocInfoHandler dih = new DocInfoHandler();
350
      XMLReader docinfoParser = initParser(dih);
351
      String docInfoURLStr = "https://" + remoteserver +
352
                       "?server="+MetacatUtil.getLocalReplicationServerName()+
353
                       "&action=getdocumentinfo&docid="+accNumber;
354
      docInfoURLStr = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLStr);
355
      URL docinfoUrl = new URL(docInfoURLStr);
356
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Sending message: " +
357
                                                  docinfoUrl.toString());
358
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
359
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
360
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
361
      // Get home server of the docid
362
      String docHomeServer = docinfoHash.get("home_server");
363
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doc home server in repl: "+docHomeServer);
364
      String createdDate = docinfoHash.get("date_created");
365
      String updatedDate = docinfoHash.get("date_updated");
366
      //docid should include rev number too
367
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
368
                                              (String)docinfoHash.get("rev");*/
369
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - docid in repl: "+accNumber);
370
      String docType = docinfoHash.get("doctype");
371
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doctype in repl: "+docType);
372

    
373
      String parserBase = null;
374
      // this for eml2 and we need user eml2 parser
375
      if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
376
      {
377
         parserBase = DocumentImpl.EML200;
378
      }
379
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
380
      {
381
        parserBase = DocumentImpl.EML200;
382
      }
383
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
384
      {
385
        parserBase = DocumentImpl.EML210;
386
      }
387
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_1NAMESPACE))
388
      {
389
        parserBase = DocumentImpl.EML210;
390
      }
391
      // Write the document into local host
392
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
393
      String newDocid = wrapper.writeReplication(dbConn,
394
                              newxmldoc,
395
                              docinfoHash.get("public_access"),
396
                              null,  /* the dtd text */
397
                              actions,
398
                              accNumber,
399
                              null, //docinfoHash.get("user_owner"),                              
400
                              null, /* null for groups[] */
401
                              docHomeServer,
402
                              remoteserver, tableName, true,// true is for time replication 
403
                              createdDate,
404
                              updatedDate);
405
      
406
      //set the user information
407
      String user = (String) docinfoHash.get("user_owner");
408
      String updated = (String) docinfoHash.get("user_updated");
409
      ReplicationService.updateUserOwner(dbConn, accNumber, user, updated);
410
      
411
      //process extra access rules 
412
      Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
413
      if (xmlAccessDAOList != null) {
414
      	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
415
      	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
416
      		if (!acfsf.accessControlExists(xmlAccessDAO)) {
417
      			acfsf.insertPermissions(xmlAccessDAO);
418
      		}
419
          }
420
      }
421
      
422
      //process guid
423
      logReplication.debug("Processing guid information from docinfoHash: " + docinfoHash.toString());
424
      String guid = docinfoHash.get("guid");
425
      String docName = docinfoHash.get("docname");
426
      System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%guid passed from docinfo hash: " + guid);
427
      IdentifierManager idman = IdentifierManager.getInstance();
428
      
429
      System.out.println("docname: " + docName);
430
      
431
      if(guid != null && !idman.identifierExists(guid))
432
      { //if the guid was passed in, put it in the identifiers table
433
        logReplication.debug("Creating guid/docid mapping for docid " + 
434
          docinfoHash.get("docid") + " and guid: " + guid);
435
        
436
        
437
        System.out.println("creating mapping: guid: " + guid + " localId: " + docinfoHash.get("docid"));
438
        idman.createMapping(guid, docinfoHash.get("docid"));
439
      }
440
      else
441
      {
442
        logReplication.debug("No guid information was included with the replicated document");
443
      }
444
      
445
      //handle systemMetadata
446
      if(docName.trim().equals("systemMetadata"))
447
      {
448
          if (actions.equalsIgnoreCase("UPDATE")) {
449
        	  System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!update mapping for systemMetadata: guid: " + guid + " localId: " + docinfoHash.get("docid"));
450
              idman.updateSystemMetadataMapping(guid, docinfoHash.get("docid"));
451
          } else { 
452
	    	  System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!creating mapping for systemMetadata: guid: " + guid + " localId: " + docinfoHash.get("docid"));
453
	          idman.createSystemMetadataMapping(guid, docinfoHash.get("docid"));
454
          }
455
          
456
          Long dateUploadedLong = new Long(docinfoHash.get("date_uploaded"));
457
          Long dateModifiedLong = new Long(docinfoHash.get("date_modified"));
458
          idman.insertAdditionalSystemMetadataFields(
459
                  dateUploadedLong.longValue(), 
460
                  docinfoHash.get("rights_holder"),
461
                  docinfoHash.get("checksum"), 
462
                  docinfoHash.get("checksum_algorithm"), 
463
                  docinfoHash.get("origin_member_node"),
464
                  docinfoHash.get("authoritive_member_node"), 
465
                  dateModifiedLong.longValue(),
466
                  docinfoHash.get("submitter"),
467
                  docinfoHash.get("guid"),
468
                  docinfoHash.get("object_format"),
469
                  new Long(docinfoHash.get("size")).longValue());
470
          System.out.println("4");
471
      }
472
      
473
      if(guid != null)
474
      {
475
          if(!docName.trim().equals("systemMetadata"))
476
          {
477
              logReplication.info("replicate D1GUID:" + guid + ":D1SCIMETADATA:" + 
478
                      accNumber + ":");
479
          }
480
          else
481
          {
482
              logReplication.info("replicate D1GUID:" + guid + ":D1SYSMETADATA:" + 
483
                      accNumber + ":");
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, 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());
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
    logD1.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
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
567
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
568
      
569
      // Get docid name (such as acl or dataset)
570
      String docName = docinfoHash.get("docname");
571
      // Get doc type (eml public id)
572
      String docType = docinfoHash.get("doctype");
573
      // Get docid home sever. it might be different to remoteserver
574
      // because of hub feature
575
      String docHomeServer = docinfoHash.get("home_server");
576
      String createdDate = docinfoHash.get("date_created");
577
      String updatedDate = docinfoHash.get("date_updated");
578
      //docid should include rev number too
579
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
580
                                              (String)docinfoHash.get("rev");*/
581

    
582

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

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

    
685

    
686

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

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

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

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

    
771
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Try to update last_check for server: "+server);
772
      // Get time from remote server
773
      URL dateurl = new URL("https://" + server + "?server="+
774
      MetacatUtil.getLocalReplicationServerName()+"&action=gettime");
775
      String datexml = ReplicationService.getURLContent(dateurl);
776
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - datexml: "+datexml);
777
      if (datexml!=null && !datexml.equals(""))
778
      {
779
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
780
         StringBuffer sql = new StringBuffer();
781
         /*sql.append("update xml_replication set last_checked = to_date('");
782
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
783
         sql.append("server like '").append(server).append("'");*/
784
         sql.append("update xml_replication set last_checked = ");
785
         sql.append(DatabaseService.getInstance().getDBAdapter().toDate(datestr, "MM/DD/YY HH24:MI:SS"));
786
         sql.append(" where server like '").append(server).append("'");
787
         pstmt = dbConn.prepareStatement(sql.toString());
788

    
789
         pstmt.executeUpdate();
790
         dbConn.commit();
791
         pstmt.close();
792
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - last_checked updated to "+datestr+" on "
793
                                      + server);
794
      }//if
795
      else
796
      {
797

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

    
804
    }//try
805
    catch(Exception e)
806
    {
807
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
808
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
809
                                server + " in db because because " + e.getMessage());
810
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - " 
811
    		  + "Error updating last checked time: " + e.getMessage());
812
    }
813
    finally
814
    {
815
       //return DBConnection
816
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
817
    }//finally
818
  }
819

    
820

    
821

    
822
  /**
823
   * updates xml_catalog with entries from other servers.
824
   */
825
  private void updateCatalog()
826
  {
827
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
828
    // ReplicationServer object in server list
829
    ReplicationServer replServer = null;
830
    PreparedStatement pstmt = null;
831
    String server = null;
832

    
833

    
834
    // Go through each ReplicationServer object in sererlist
835
    for (int j=0; j<serverList.size(); j++)
836
    {
837
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
838
      Vector<String> publicId = new Vector<String>();
839
      try
840
      {
841
        // Get ReplicationServer object from server list
842
        replServer = serverList.serverAt(j);
843
        // Get server name from the ReplicationServer object
844
        server = replServer.getServerName();
845
        // Try to get catalog
846
        URL u = new URL("https://" + server + "?server="+
847
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
848
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
849
        String catxml = ReplicationService.getURLContent(u);
850

    
851
        // Make sure there are not error, no empty string
852
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
853
        {
854
          throw new Exception("Couldn't get catalog list form server " +server);
855
        }
856
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
857
        CatalogMessageHandler cmh = new CatalogMessageHandler();
858
        XMLReader catparser = initParser(cmh);
859
        catparser.parse(new InputSource(new StringReader(catxml)));
860
        //parse the returned catalog xml and put it into a vector
861
        remoteCatalog = cmh.getCatalogVect();
862

    
863
        // Make sure remoteCatalog is not empty
864
        if (remoteCatalog.isEmpty())
865
        {
866
          throw new Exception("Couldn't get catalog list form server " +server);
867
        }
868

    
869
        String localcatxml = ReplicationService.getCatalogXML();
870

    
871
        // Make sure local catalog is no empty
872
        if (localcatxml==null||localcatxml.equals(""))
873
        {
874
          throw new Exception("Couldn't get catalog list form server " +server);
875
        }
876

    
877
        cmh = new CatalogMessageHandler();
878
        catparser = initParser(cmh);
879
        catparser.parse(new InputSource(new StringReader(localcatxml)));
880
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
881

    
882
        //now we have the catalog from the remote server and this local server
883
        //we now need to compare the two and merge the differences.
884
        //the comparison is base on the public_id fields which is the 4th
885
        //entry in each row vector.
886
        publicId = new Vector<String>();
887
        for(int i=0; i<localCatalog.size(); i++)
888
        {
889
          Vector<String> v = new Vector<String>(localCatalog.elementAt(i));
890
          logReplication.info("ReplicationHandler.updateCatalog - v1: " + v.toString());
891
          publicId.add(new String((String)v.elementAt(3)));
892
          //System.out.println("adding " + (String)v.elementAt(3));
893
        }
894
      }//try
895
      catch (Exception e)
896
      {
897
        logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
898
        logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
899
                                    server + " because " +e.getMessage());
900
      }//catch
901

    
902
      for(int i=0; i<remoteCatalog.size(); i++)
903
      {
904
         // DConnection
905
        DBConnection dbConn = null;
906
        // DBConnection checkout serial number
907
        int serialNumber = -1;
908
        try
909
        {
910
            dbConn=DBConnectionPool.
911
                  getDBConnection("ReplicationHandler.updateCatalog");
912
            serialNumber=dbConn.getCheckOutSerialNumber();
913
            Vector<String> v = remoteCatalog.elementAt(i);
914
            //System.out.println("v2: " + v.toString());
915
            //System.out.println("i: " + i);
916
            //System.out.println("remoteCatalog.size(): " + remoteCatalog.size());
917
            //System.out.println("publicID: " + publicId.toString());
918
            logReplication.info
919
                              ("ReplicationHandler.updateCatalog - v.elementAt(3): " + (String)v.elementAt(3));
920
           if(!publicId.contains(v.elementAt(3)))
921
           { //so we don't have this public id in our local table so we need to
922
             //add it.
923
             //System.out.println("in if");
924
             StringBuffer sql = new StringBuffer();
925
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
926
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
927
             sql.append("?,?)");
928
             //System.out.println("sql: " + sql.toString());
929
             pstmt = dbConn.prepareStatement(sql.toString());
930
             pstmt.setString(1, (String)v.elementAt(0));
931
             pstmt.setString(2, (String)v.elementAt(1));
932
             pstmt.setString(3, (String)v.elementAt(2));
933
             pstmt.setString(4, (String)v.elementAt(3));
934
             pstmt.setString(5, (String)v.elementAt(4));
935
             pstmt.execute();
936
             pstmt.close();
937
             logReplication.info("ReplicationHandler.updateCatalog - Success fully to insert new publicid "+
938
                               (String)v.elementAt(3) + " from server"+server);
939
           }
940
        }
941
        catch(Exception e)
942
        {
943
           logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
944
           logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
945
                                    server + " because " +e.getMessage());
946
        }//catch
947
        finally
948
        {
949
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
950
        }//finally
951
      }//for remote catalog
952
    }//for server list
953
    logReplication.info("End of updateCatalog");
954
  }
955

    
956
  /**
957
   * Method that returns true if docid has already been "deleted" from metacat.
958
   * This method really implements a truth table for deleted documents
959
   * The table is (a docid in one of the tables is represented by the X):
960
   * xml_docs      xml_revs      deleted?
961
   * ------------------------------------
962
   *   X             X             FALSE
963
   *   X             _             FALSE
964
   *   _             X             TRUE
965
   *   _             _             TRUE
966
   */
967
  private static boolean alreadyDeleted(String docid) throws HandlerException
968
  {
969
    DBConnection dbConn = null;
970
    int serialNumber = -1;
971
    PreparedStatement pstmt = null;
972
    try
973
    {
974
      dbConn=DBConnectionPool.
975
                  getDBConnection("ReplicationHandler.alreadyDeleted");
976
      serialNumber=dbConn.getCheckOutSerialNumber();
977
      boolean xml_docs = false;
978
      boolean xml_revs = false;
979

    
980
      StringBuffer sb = new StringBuffer();
981
      sb.append("select docid from xml_revisions where docid like '");
982
      sb.append(docid).append("'");
983
      pstmt = dbConn.prepareStatement(sb.toString());
984
      pstmt.execute();
985
      ResultSet rs = pstmt.getResultSet();
986
      boolean tablehasrows = rs.next();
987
      if(tablehasrows)
988
      {
989
        xml_revs = true;
990
      }
991

    
992
      sb = new StringBuffer();
993
      sb.append("select docid from xml_documents where docid like '");
994
      sb.append(docid).append("'");
995
      pstmt.close();
996
      pstmt = dbConn.prepareStatement(sb.toString());
997
      //increase usage count
998
      dbConn.increaseUsageCount(1);
999
      pstmt.execute();
1000
      rs = pstmt.getResultSet();
1001
      tablehasrows = rs.next();
1002
      pstmt.close();
1003
      if(tablehasrows)
1004
      {
1005
        xml_docs = true;
1006
      }
1007

    
1008
      if(xml_docs && xml_revs)
1009
      {
1010
        return false;
1011
      }
1012
      else if(xml_docs && !xml_revs)
1013
      {
1014
        return false;
1015
      }
1016
      else if(!xml_docs && xml_revs)
1017
      {
1018
        return true;
1019
      }
1020
      else if(!xml_docs && !xml_revs)
1021
      {
1022
        return true;
1023
      }
1024
    }
1025
    catch(Exception e)
1026
    {
1027
      logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1028
      logReplication.error("ReplicationHandler.alreadyDeleted - general error in alreadyDeleted: " +
1029
                          e.getMessage());
1030
      throw new HandlerException("ReplicationHandler.alreadyDeleted - general error: " 
1031
    		  + e.getMessage());
1032
    }
1033
    finally
1034
    {
1035
      try
1036
      {
1037
        pstmt.close();
1038
      }//try
1039
      catch (SQLException ee)
1040
      {
1041
    	logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1042
        logReplication.error("ReplicationHandler.alreadyDeleted - Error in replicationHandler.alreadyDeleted "+
1043
                          "to close pstmt: "+ee.getMessage());
1044
        throw new HandlerException("ReplicationHandler.alreadyDeleted - SQL error when closing prepared statement: " 
1045
      		  + ee.getMessage());
1046
      }//catch
1047
      finally
1048
      {
1049
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1050
      }//finally
1051
    }//finally
1052
    return false;
1053
  }
1054

    
1055

    
1056
  /**
1057
   * Method to initialize the message parser
1058
   */
1059
  public static XMLReader initParser(DefaultHandler dh)
1060
          throws HandlerException
1061
  {
1062
    XMLReader parser = null;
1063

    
1064
    try {
1065
      ContentHandler chandler = dh;
1066

    
1067
      // Get an instance of the parser
1068
      String parserName = PropertyService.getProperty("xml.saxparser");
1069
      parser = XMLReaderFactory.createXMLReader(parserName);
1070

    
1071
      // Turn off validation
1072
      parser.setFeature("http://xml.org/sax/features/validation", false);
1073

    
1074
      parser.setContentHandler((ContentHandler)chandler);
1075
      parser.setErrorHandler((ErrorHandler)chandler);
1076

    
1077
    } catch (SAXException se) {
1078
      throw new HandlerException("ReplicationHandler.initParser - Sax error when " 
1079
    		  + " initializing parser: " + se.getMessage());
1080
    } catch (PropertyNotFoundException pnfe) {
1081
        throw new HandlerException("ReplicationHandler.initParser - Property error when " 
1082
      		  + " getting parser name: " + pnfe.getMessage());
1083
    } 
1084

    
1085
    return parser;
1086
  }
1087

    
1088
  /**
1089
	 * This method will combine given time string(in short format) to current
1090
	 * date. If the given time (e.g 10:00 AM) passed the current time (e.g 2:00
1091
	 * PM Aug 21, 2005), then the time will set to second day, 10:00 AM Aug 22,
1092
	 * 2005. If the given time (e.g 10:00 AM) haven't passed the current time
1093
	 * (e.g 8:00 AM Aug 21, 2005) The time will set to be 10:00 AM Aug 21, 2005.
1094
	 * 
1095
	 * @param givenTime
1096
	 *            the format should be "10:00 AM " or "2:00 PM"
1097
	 * @return
1098
	 * @throws Exception
1099
	 */
1100
	public static Date combinateCurrentDateAndGivenTime(String givenTime) throws HandlerException
1101
  {
1102
	  try {
1103
     Date givenDate = parseTime(givenTime);
1104
     Date newDate = null;
1105
     Date now = new Date();
1106
     String currentTimeString = getTimeString(now);
1107
     Date currentTime = parseTime(currentTimeString); 
1108
     if ( currentTime.getTime() >= givenDate.getTime())
1109
     {
1110
        logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today already pass the given time, we should set it as tomorrow");
1111
        String dateAndTime = getDateString(now) + " " + givenTime;
1112
        Date combinationDate = parseDateTime(dateAndTime);
1113
        // new date should plus 24 hours to make is the second day
1114
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
1115
     }
1116
     else
1117
     {
1118
         logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today haven't pass the given time, we should it as today");
1119
         String dateAndTime = getDateString(now) + " " + givenTime;
1120
         newDate = parseDateTime(dateAndTime);
1121
     }
1122
     logReplication.warn("ReplicationHandler.combinateCurrentDateAndGivenTime - final setting time is "+ newDate.toString());
1123
     return newDate;
1124
	  } catch (ParseException pe) {
1125
		  throw new HandlerException("ReplicationHandler.combinateCurrentDateAndGivenTime - "
1126
				  + "parsing error: "  + pe.getMessage());
1127
	  }
1128
  }
1129

    
1130
  /*
1131
	 * parse a given string to Time in short format. For example, given time is
1132
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1133
	 */
1134
  private static Date parseTime(String timeString) throws ParseException
1135
  {
1136
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1137
    Date time = format.parse(timeString); 
1138
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1139
                              +time.toString());
1140
    return time;
1141

    
1142
  }
1143
  
1144
  /*
1145
   * Parse a given string to date and time. Date format is long and time
1146
   * format is short.
1147
   */
1148
  private static Date parseDateTime(String timeString) throws ParseException
1149
  {
1150
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
1151
    Date time = format.parse(timeString);
1152
    logReplication.info("ReplicationHandler.parseDateTime - Date string is after parse a time string "+
1153
                             time.toString());
1154
    return time;
1155
  }
1156
  
1157
  /*
1158
   * Get a date string from a Date object. The date format will be long
1159
   */
1160
  private static String getDateString(Date now)
1161
  {
1162
     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
1163
     String s = df.format(now);
1164
     logReplication.info("ReplicationHandler.getDateString - Today is " + s);
1165
     return s;
1166
  }
1167
  
1168
  /*
1169
   * Get a time string from a Date object, the time format will be short
1170
   */
1171
  private static String getTimeString(Date now)
1172
  {
1173
     DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
1174
     String s = df.format(now);
1175
     logReplication.info("ReplicationHandler.getTimeString - Time is " + s);
1176
     return s;
1177
  }
1178
  
1179
  
1180
  /*
1181
	 * This method will go through the docid list both in xml_Documents table
1182
	 * and in xml_revisions table @author tao
1183
	 */
1184
	private void handleDocList(Vector<Vector<String>> docList, String tableName) {
1185
		boolean dataFile = false;
1186
		for (int j = 0; j < docList.size(); j++) {
1187
			// initial dataFile is false
1188
			dataFile = false;
1189
			// w is information for one document, information contain
1190
			// docid, rev, server or datafile.
1191
			Vector<String> w = new Vector<String>(docList.elementAt(j));
1192
			// Check if the vector w contain "datafile"
1193
			// If it has, this document is data file
1194
			try {
1195
				if (w.contains((String) PropertyService.getProperty("replication.datafileflag"))) {
1196
					dataFile = true;
1197
				}
1198
			} catch (PropertyNotFoundException pnfe) {
1199
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1200
				logReplication.error("ReplicationHandler.handleDocList - Could not retrieve data file flag property.  "
1201
						+ "Leaving as false: " + pnfe.getMessage());
1202
			}
1203
			// System.out.println("w: " + w.toString());
1204
			// Get docid
1205
			String docid = (String) w.elementAt(0);
1206
			logReplication.info("docid: " + docid);
1207
			// Get revision number
1208
			int rev = Integer.parseInt((String) w.elementAt(1));
1209
			logReplication.info("rev: " + rev);
1210
			// Get remote server name (it is may not be doc home server because
1211
			// the new hub feature
1212
			String remoteServer = (String) w.elementAt(2);
1213
			remoteServer = remoteServer.trim();
1214

    
1215
			try {
1216
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1217
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1218
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1219
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1220
				} else {
1221
					continue;
1222
				}
1223

    
1224
			} catch (Exception e) {
1225
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1226
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1227
						+ " in time replication" + e.getMessage());
1228
				continue;
1229
			}
1230
			
1231
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1232
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount + 
1233
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1234
	        }
1235
	        
1236
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1237
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount + 
1238
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1239
	        }
1240

    
1241
		}// for update docs
1242

    
1243
	}
1244
   
1245
   /*
1246
	 * This method will handle doc in xml_documents table.
1247
	 */
1248
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
1249
                                        throws HandlerException
1250
   {
1251
       // compare the update rev and local rev to see what need happen
1252
       int localrev = -1;
1253
       String action = null;
1254
       boolean flag = false;
1255
       try
1256
       {
1257
    	 long docQueryStartTime = System.currentTimeMillis();
1258
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1259
         long docQueryEndTime = System.currentTimeMillis();
1260
         _xmlDocQueryTime += (docQueryEndTime - docQueryStartTime);
1261
         _xmlDocQueryCount++;
1262
       }
1263
       catch (SQLException e)
1264
       {
1265
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1266
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1267
                                " be found because " + e.getMessage());
1268
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - " + DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1269
                 "written because error happend to find it's local revision");
1270
         DOCERRORNUMBER++;
1271
         throw new HandlerException ("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1272
                 " be found: " + e.getMessage());
1273
       }
1274
       logReplication.info("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " is "+
1275
                               localrev);
1276

    
1277
       //check the revs for an update because this document is in the
1278
       //local DB, it might be out of date.
1279
       if (localrev == -1)
1280
       {
1281
          // check if the revision is in the revision table
1282
    	   Vector<Integer> localRevVector = null;
1283
    	 try {
1284
        	 long revQueryStartTime = System.currentTimeMillis();
1285
    		 localRevVector = DBUtil.getRevListFromRevisionTable(docid);
1286
             long revQueryEndTime = System.currentTimeMillis();
1287
             _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1288
             _xmlRevQueryCount++;
1289
    	 } catch (SQLException sqle) {
1290
    		 throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - SQL error " 
1291
    				 + " when getting rev list for docid: " + docid + " : " + sqle.getMessage());
1292
    	 }
1293
         if (localRevVector != null && localRevVector.contains(new Integer(rev)))
1294
         {
1295
             // this version was deleted, so don't need replicate
1296
             flag = false;
1297
         }
1298
         else
1299
         {
1300
           //insert this document as new because it is not in the local DB
1301
           action = "INSERT";
1302
           flag = true;
1303
         }
1304
       }
1305
       else
1306
       {
1307
         if(localrev == rev)
1308
         {
1309
           // Local meatacat has the same rev to remote host, don't need
1310
           // update and flag set false
1311
           flag = false;
1312
         }
1313
         else if(localrev < rev)
1314
         {
1315
           //this document needs to be updated so send an read request
1316
           action = "UPDATE";
1317
           flag = true;
1318
         }
1319
       }
1320
       
1321
       String accNumber = null;
1322
       try {
1323
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1324
       } catch (PropertyNotFoundException pnfe) {
1325
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - error getting " 
1326
    			   + "account number separator : " + pnfe.getMessage());
1327
       }
1328
       // this is non-data file
1329
       if(flag && !dataFile)
1330
       {
1331
         try
1332
         {
1333
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1334
         }
1335
         catch(HandlerException he)
1336
         {
1337
           // skip this document
1338
           throw he;
1339
         }
1340
       }//if for non-data file
1341

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

    
1355
       }//for data file
1356
   }
1357
   
1358
   /*
1359
    * This method will handle doc in xml_documents table.
1360
    */
1361
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile) 
1362
                                        throws HandlerException
1363
   {
1364
       // compare the update rev and local rev to see what need happen
1365
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - In handle repliation revsion table");
1366
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - the docid is "+ docid);
1367
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - The rev is "+rev);
1368
       Vector<Integer> localrev = null;
1369
       String action = "INSERT";
1370
       boolean flag = false;
1371
       try
1372
       {
1373
      	 long revQueryStartTime = System.currentTimeMillis();
1374
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1375
         long revQueryEndTime = System.currentTimeMillis();
1376
         _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1377
         _xmlRevQueryCount++;
1378
       }
1379
       catch (SQLException sqle)
1380
       {
1381
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1382
         logReplication.error("ReplicationHandler.handleDocInXMLRevisions - Local rev for docid "+ docid + " could not "+
1383
                                " be found because " + sqle.getMessage());
1384
         REVERRORNUMBER++;
1385
         throw new HandlerException ("ReplicationHandler.handleDocInXMLRevisions - SQL exception getting rev list: " 
1386
        		 + sqle.getMessage());
1387
       }
1388
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - rev list in xml_revision table for docid "+ docid + " is "+
1389
                               localrev.toString());
1390
       
1391
       // if the rev is not in the xml_revision, we need insert it
1392
       if (!localrev.contains(new Integer(rev)))
1393
       {
1394
           flag = true;    
1395
       }
1396
     
1397
       String accNumber = null;
1398
       try {
1399
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1400
       } catch (PropertyNotFoundException pnfe) {
1401
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLRevisions - error getting " 
1402
    			   + "account number separator : " + pnfe.getMessage());
1403
       }
1404
       // this is non-data file
1405
       if(flag && !dataFile)
1406
       {
1407
         try
1408
         {
1409
           
1410
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1411
         }
1412
         catch(HandlerException he)
1413
         {
1414
           // skip this document
1415
           throw he;
1416
         }
1417
       }//if for non-data file
1418

    
1419
        // this is for data file
1420
       if(flag && dataFile)
1421
       {
1422
         try
1423
         {
1424
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1425
         }
1426
         catch(HandlerException he)
1427
         {
1428
           // skip this data file
1429
           throw he;
1430
         }
1431

    
1432
       }//for data file
1433
   }
1434
   
1435
   /*
1436
    * Return a ip address for given url
1437
    */
1438
   private String getIpFromURL(URL url)
1439
   {
1440
	   String ip = null;
1441
	   try
1442
	   {
1443
	      InetAddress address = InetAddress.getByName(url.getHost());
1444
	      ip = address.getHostAddress();
1445
	   }
1446
	   catch(UnknownHostException e)
1447
	   {
1448
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1449
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1450
                   +e.getMessage());
1451
	   }
1452

    
1453
	   return ip;
1454
   }
1455
  
1456
}
1457

    
(3-3/7)