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: rnahf $'
9
 *     '$Date: 2015-05-11 12:28:55 -0700 (Mon, 11 May 2015) $'
10
 * '$Revision: 9203 $'
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.Iterator;
44
import java.util.TimerTask;
45
import java.util.Vector;
46

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

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

    
83

    
84

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

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

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

    
143
  /**
144
   * Method that uses revision tagging for replication instead of update_date.
145
   */
146
  private void update()
147
  {
148
    Vector<InputStream> responses = new Vector<InputStream>();
149
    try {
150

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

    
169
        ReplicationServer replServer = null; // Variable to store the
170
        // ReplicationServer got from
171
        // Server list
172
        String server = null; // Variable to store server name
173
        //    String update;
174

    
175
        URL u;
176
        long replicationStartTime = System.currentTimeMillis();
177
        long timeToGetServerList = 0;
178

    
179
        //Check for every server in server list to get updated list and put
180
        // them in to response
181
        long startTimeToGetServers = System.currentTimeMillis();
182
        for (int i=0; i<serverList.size(); i++)
183
        {
184
            // Get ReplicationServer object from server list
185
            replServer = serverList.serverAt(i);
186
            // Get server name from ReplicationServer object
187
            server = replServer.getServerName().trim();
188
            InputStream result = null;
189
            logReplication.info("ReplicationHandler.update - full update started to: " + server);
190
            // Send command to that server to get updated docid information
191
            try
192
            {
193
                u = new URL("https://" + server + "?server="
194
                        +MetacatUtil.getLocalReplicationServerName()+"&action=update");
195
                logReplication.info("ReplicationHandler.update - Sending infomation " +u.toString());
196
                result = ReplicationService.getURLStream(u);
197
            }
198
            catch (Exception e)
199
            {
200
                logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
201
                logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
202
                        "for server " + server + " because "+e.getMessage());
203
                continue;
204
            }
205

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

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

    
231

    
232
        //logReplication.info("ReplicationHandler.update - Responses from remote metacat about updated "+
233
        //               "document information: "+ responses.toString());
234

    
235
        long totalServerListParseTime = 0;
236
        // go through response vector(it contains updated vector and delete vector
237
        for(int i=0; i<responses.size(); i++)
238
        {
239
            long startServerListParseTime = System.currentTimeMillis();
240
            XMLReader parser;
241
            ReplMessageHandler message = new ReplMessageHandler();
242
            try
243
            {
244
                parser = initParser(message);
245
            }
246
            catch (Exception e)
247
            {
248
                logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
249
                logReplication.error("ReplicationHandler.update - Failed to replicate becaue couldn't " +
250
                        " initParser for message and " +e.getMessage());
251
                // stop replication
252
                return;
253
            }
254

    
255
            try
256
            {
257
                parser.parse(new InputSource(responses.elementAt(i)));
258
            }
259
            catch(Exception e)
260
            {
261
                logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
262
                logReplication.error("ReplicationHandler.update - Couldn't parse one responses "+
263
                        "because "+ e.getMessage());
264
                continue;
265
            }
266
            finally 
267
            {
268
                IOUtils.closeQuietly(responses.elementAt(i));
269
            }
270
            //v is the list of updated documents
271
            Vector<Vector<String>> updateList = new Vector<Vector<String>>(message.getUpdatesVect());
272
            logReplication.info("ReplicationHandler.update - The document list size is "+updateList.size()+ " from "+message.getServerName());
273
            //d is the list of deleted documents
274
            Vector<Vector<String>> deleteList = new Vector<Vector<String>>(message.getDeletesVect());
275
            logReplication.info("ReplicationHandler.update - Update vector size: "+ updateList.size()+" from "+message.getServerName());
276
            logReplication.info("ReplicationHandler.update - Delete vector size: "+ deleteList.size()+" from "+message.getServerName());
277
            logReplication.info("ReplicationHandler.update - The delete document list size is "+deleteList.size()+" from "+message.getServerName());
278
            // go though every element in updated document vector
279
            handleDocList(updateList, DocumentImpl.DOCUMENTTABLE);
280
            //handle deleted docs
281
            for(int k=0; k<deleteList.size(); k++)
282
            { //delete the deleted documents;
283
                Vector<String> w = new Vector<String>(deleteList.elementAt(k));
284
                String docId = (String)w.elementAt(0);
285
                try
286
                {
287
                    handleDeleteSingleDocument(docId, server);
288
                }
289
                catch (Exception ee)
290
                {
291
                    continue;
292
                }
293
            }//for delete docs
294

    
295
            // handle replicate doc in xml_revision
296
            Vector<Vector<String>> revisionList = new Vector<Vector<String>>(message.getRevisionsVect());
297
            logReplication.info("ReplicationHandler.update - The revision document list size is "+revisionList.size()+ " from "+message.getServerName());
298
            handleDocList(revisionList, DocumentImpl.REVISIONTABLE);
299
            DOCINSERTNUMBER = 1;
300
            DOCERRORNUMBER  = 1;
301
            REVINSERTNUMBER = 1;
302
            REVERRORNUMBER  = 1;
303

    
304
            // handle system metadata
305
            Vector<Vector<String>> systemMetadataList = message.getSystemMetadataVect();
306
            for(int k = 0; k < systemMetadataList.size(); k++) { 
307
                Vector<String> w = systemMetadataList.elementAt(k);
308
                String guid = (String) w.elementAt(0);
309
                String remoteserver = (String) w.elementAt(1);
310
                try {
311
                    handleSystemMetadata(remoteserver, guid);
312
                }
313
                catch (Exception ee) {
314
                    logMetacat.error("Error replicating system metedata for guid: " + guid, ee);
315
                    continue;
316
                }
317
            }
318

    
319
            totalServerListParseTime += (System.currentTimeMillis() - startServerListParseTime);
320
        }//for response
321

    
322
        //updated last_checked
323
        for (int i=0;i<serverList.size(); i++)
324
        {
325
            // Get ReplicationServer object from server list
326
            replServer = serverList.serverAt(i);
327
            try
328
            {
329
                updateLastCheckTimeForSingleServer(replServer);
330
            }
331
            catch(Exception e)
332
            {
333
                continue;
334
            }
335
        }//for
336

    
337
        long replicationEndTime = System.currentTimeMillis();
338
        logMetacat.debug("ReplicationHandler.update - Total replication time: " + 
339
                (replicationEndTime - replicationStartTime));
340
        logMetacat.debug("ReplicationHandler.update - time to get server list: " + 
341
                timeToGetServerList);
342
        logMetacat.debug("ReplicationHandler.update - server list parse time: " + 
343
                totalServerListParseTime);
344
        logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query count: " + 
345
                _xmlDocQueryCount);
346
        logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query time: " + 
347
                _xmlDocQueryTime + " ms");
348
        logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query count: " + 
349
                _xmlRevQueryCount);
350
        logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query time: " + 
351
                _xmlRevQueryTime + " ms");;
352

    
353
    } finally { // need to close all inputstreams unconditionally
354
        Iterator<InputStream> isit = responses.iterator();
355
        while (isit.hasNext()) {
356
            IOUtils.closeQuietly(isit.next());
357
        }
358
    }
359
    }//update
360

    
361
  /* Handle replicate single xml document*/
362
  private void handleSingleXMLDocument(String remoteserver, String actions,
363
                                       String accNumber, String tableName)
364
               throws HandlerException
365
  {
366
    DBConnection dbConn = null;
367
    int serialNumber = -1;
368
    try
369
    {
370
      // Get DBConnection from pool
371
      dbConn=DBConnectionPool.
372
                  getDBConnection("ReplicationHandler.handleSingleXMLDocument");
373
      serialNumber=dbConn.getCheckOutSerialNumber();
374
      //if the document needs to be updated or inserted, this is executed
375
      String readDocURLString = "https://" + remoteserver + "?server="+
376
              MetacatUtil.getLocalReplicationServerName()+"&action=read&docid="+accNumber;
377
      readDocURLString = MetacatUtil.replaceWhiteSpaceForURL(readDocURLString);
378
      URL u = new URL(readDocURLString);
379

    
380
      // Get docid content
381
      byte[] xmlBytes = ReplicationService.getURLBytes(u);
382
      String newxmldoc = new String(xmlBytes, "UTF-8");
383
      // If couldn't get skip it
384
      if ( newxmldoc.indexOf("<error>")!= -1 && newxmldoc.indexOf("</error>")!=-1)
385
      {
386
         throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - " + newxmldoc);
387
      }
388
      //logReplication.info("xml documnet:");
389
      //logReplication.info(newxmldoc);
390

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

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

    
531
    }//try
532
    catch(Exception e)
533
    {
534
        
535
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
536
        {
537
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
538
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
539
                                       " into "+tableName + " from " +
540
                                           remoteserver + " because "+e.getMessage());
541
          DOCERRORNUMBER++;
542
        }
543
        else
544
        {
545
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
546
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
547
                    " into "+tableName + " from " +
548
                        remoteserver +" because "+e.getMessage());
549
            REVERRORNUMBER++;
550
        }
551
        logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
552
        logReplication.error("ReplicationHandler.handleSingleXMLDocument - Failed to write doc " + accNumber +
553
                                      " into db because " + e.getMessage(), e);
554
      throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - generic exception " 
555
    		  + "writing Replication: " +e.getMessage());
556
    }
557
    finally
558
    {
559
       //return DBConnection
560
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
561
    }//finally
562
    logMetacat.info("replication.create localId:" + accNumber);
563
  }
564

    
565

    
566

    
567
  /* Handle replicate single xml document*/
568
  private void handleSingleDataFile(String remoteserver, String actions,
569
                                    String accNumber, String tableName)
570
               throws HandlerException
571
  {
572
    logReplication.info("ReplicationHandler.handleSingleDataFile - Try to replicate data file: " + accNumber);
573
    DBConnection dbConn = null;
574
    int serialNumber = -1;
575
    InputStream input = null;
576
    try
577
    {
578
      // Get DBConnection from pool
579
      dbConn=DBConnectionPool.
580
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
581
      serialNumber=dbConn.getCheckOutSerialNumber();
582
      // Try get docid info from remote server
583
      DocInfoHandler dih = new DocInfoHandler();
584
      XMLReader docinfoParser = initParser(dih);
585
      String docInfoURLString = "https://" + remoteserver +
586
                  "?server="+MetacatUtil.getLocalReplicationServerName()+
587
                  "&action=getdocumentinfo&docid="+accNumber;
588
      docInfoURLString = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLString);
589
      URL docinfoUrl = new URL(docInfoURLString);
590

    
591
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
592
      
593
      // strip out the system metadata portion
594
      String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
595
   	  docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);  
596
   	  
597
   	  // process system metadata
598
      if (systemMetadataXML != null) {
599
    	  SystemMetadata sysMeta = 
600
    		TypeMarshaller.unmarshalTypeFromStream(
601
    				  SystemMetadata.class, 
602
    				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
603
    	  // need the guid-to-docid mapping
604
    	  if (!IdentifierManager.getInstance().mappingExists(sysMeta.getIdentifier().getValue())) {
605
	      	  IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), accNumber);
606
    	  }
607
    	  // save the system metadata
608
    	  HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
609
    	  // submit for indexing
610
          MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
611

    
612
      }
613
   	  
614
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
615
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
616
      
617
      // Get docid name (such as acl or dataset)
618
      String docName = docinfoHash.get("docname");
619
      // Get doc type (eml public id)
620
      String docType = docinfoHash.get("doctype");
621
      // Get docid home sever. it might be different to remoteserver
622
      // because of hub feature
623
      String docHomeServer = docinfoHash.get("home_server");
624
      String createdDateString = docinfoHash.get("date_created");
625
      String updatedDateString = docinfoHash.get("date_updated");
626
      Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
627
      Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
628
      //docid should include rev number too
629
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
630
                                              (String)docinfoHash.get("rev");*/
631

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

    
709
    }//try
710
    catch(Exception e)
711
    {
712
      /*MetacatReplication.replErrorLog("Failed to try wrote data file " + accNumber +
713
                                      " because " +e.getMessage());*/
714
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
715
      {
716
    	logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
717
    	logReplication.error("ReplicationHandler.handleSingleDataFile - " + DOCERRORNUMBER + " Failed to write data file " + accNumber +
718
                                     " into " + tableName + " from " +
719
                                         remoteserver + " because " + e.getMessage());
720
        DOCERRORNUMBER++;
721
      }
722
      else
723
      {
724
    	  logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
725
    	  logReplication.error("ReplicationHandler.handleSingleDataFile - " + REVERRORNUMBER + " Failed to write data file" + accNumber +
726
                  " into " + tableName + " from " +
727
                      remoteserver +" because "+ e.getMessage());
728
          REVERRORNUMBER++;
729
      }
730
      logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
731
      logReplication.error("ReplicationHandler.handleSingleDataFile - Failed to try wrote datafile " + accNumber +
732
                                      " because " + e.getMessage());
733
      throw new HandlerException("ReplicationHandler.handleSingleDataFile - generic exception " 
734
    		  + "writing Replication: " + e.getMessage());
735
    }
736
    finally
737
    {
738
       IOUtils.closeQuietly(input);
739
       //return DBConnection
740
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
741

    
742
     
743
    }//finally
744
    logMetacat.info("replication.create localId:" + accNumber);
745
  }
746

    
747

    
748

    
749
  /* Handle delete single document*/
750
  private void handleDeleteSingleDocument(String docId, String notifyServer)
751
               throws HandlerException
752
  {
753
    logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Try delete doc: "+docId);
754
    DBConnection dbConn = null;
755
    int serialNumber = -1;
756
    try
757
    {
758
      // Get DBConnection from pool
759
      dbConn=DBConnectionPool.
760
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
761
      serialNumber=dbConn.getCheckOutSerialNumber();
762
      if(!alreadyDeleted(docId))
763
      {
764

    
765
         //because delete method docid should have rev number
766
         //so we just add one for it. This rev number is no sence.
767
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
768
         DocumentImpl.delete(accnum, null, null, notifyServer, false);
769
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Successfully deleted doc " + docId);
770
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Doc " + docId + " deleted");
771
         URL u = new URL("https://"+notifyServer);
772
         String ip = getIpFromURL(u);
773
         EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, docId, "delete");
774
      }
775

    
776
    }//try
777
    catch(McdbDocNotFoundException e)
778
    {
779
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
780
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
781
                                 " in db because because " + e.getMessage());
782
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
783
    		  + "when handling document: " + e.getMessage());
784
    }
785
    catch(InsufficientKarmaException e)
786
    {
787
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
788
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
789
                                 " in db because because " + e.getMessage());
790
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
791
    		  + "when handling document: " + e.getMessage());
792
    }
793
    catch(SQLException e)
794
    {
795
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
796
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
797
                                 " in db because because " + e.getMessage());
798
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
799
    		  + "when handling document: " + e.getMessage());
800
    }
801
    catch(Exception e)
802
    {
803
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
804
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
805
                                 " in db because because " + e.getMessage());
806
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception " 
807
    		  + "when handling document: " + e.getMessage());
808
    }
809
    finally
810
    {
811
       //return DBConnection
812
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
813
    }//finally
814
    logMetacat.info("replication.handleDeleteSingleDocument localId:" + docId);
815
  }
816

    
817
  /* Handle updateLastCheckTimForSingleServer*/
818
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
819
                                                  throws HandlerException
820
  {
821
    String server = repServer.getServerName();
822
    DBConnection dbConn = null;
823
    int serialNumber = -1;
824
    PreparedStatement pstmt = null;
825
    try
826
    {
827
      // Get DBConnection from pool
828
      dbConn=DBConnectionPool.
829
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
830
      serialNumber=dbConn.getCheckOutSerialNumber();
831

    
832
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Try to update last_check for server: "+server);
833
      // Get time from remote server
834
      URL dateurl = new URL("https://" + server + "?server="+
835
      MetacatUtil.getLocalReplicationServerName()+"&action=gettime");
836
      String datexml = ReplicationService.getURLContent(dateurl);
837
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - datexml: "+datexml);
838
      if (datexml != null && !datexml.equals("")) {
839
    	  
840
    	  // parse the ISO datetime
841
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
842
         Date updated = DateTimeMarshaller.deserializeDateToUTC(datestr);
843
         
844
         StringBuffer sql = new StringBuffer();
845
         sql.append("update xml_replication set last_checked = ? ");
846
         sql.append(" where server like ? ");
847
         pstmt = dbConn.prepareStatement(sql.toString());
848
         pstmt.setTimestamp(1, new Timestamp(updated.getTime()));
849
         pstmt.setString(2, server);
850
         
851
         pstmt.executeUpdate();
852
         dbConn.commit();
853
         pstmt.close();
854
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - last_checked updated to "+datestr+" on "
855
                                      + server);
856
      }//if
857
      else
858
      {
859

    
860
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server "  +
861
                                  server + " in db because couldn't get time "
862
                                  );
863
         throw new Exception("Couldn't get time for server "+ server);
864
      }
865

    
866
    }//try
867
    catch(Exception e)
868
    {
869
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG); 
870
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
871
                                server + " in db because because " + e.getMessage());
872
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - " 
873
    		  + "Error updating last checked time: " + e.getMessage());
874
    }
875
    finally
876
    {
877
       //return DBConnection
878
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
879
    }//finally
880
  }
881
  
882
  	/**
883
	 * Handle replicate system metadata
884
	 * 
885
	 * @param remoteserver
886
	 * @param guid
887
	 * @throws HandlerException
888
	 */
889
	private void handleSystemMetadata(String remoteserver, String guid) 
890
		throws HandlerException {
891
		try {
892

    
893
			// Try get the system metadata from remote server
894
			String sysMetaURLStr = "https://" + remoteserver + "?server="
895
					+ MetacatUtil.getLocalReplicationServerName()
896
					+ "&action=getsystemmetadata&guid=" + guid;
897
			sysMetaURLStr = MetacatUtil.replaceWhiteSpaceForURL(sysMetaURLStr);
898
			URL sysMetaUrl = new URL(sysMetaURLStr);
899
			logReplication.info("ReplicationHandler.handleSystemMetadata - Sending message: "
900
							+ sysMetaUrl.toString());
901
			String systemMetadataXML = ReplicationService.getURLContent(sysMetaUrl);
902

    
903
			logReplication.info("ReplicationHandler.handleSystemMetadata - guid in repl: " + guid);
904

    
905
			// process system metadata
906
			if (systemMetadataXML != null) {
907
				SystemMetadata sysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class,
908
								new ByteArrayInputStream(systemMetadataXML
909
										.getBytes("UTF-8")));
910
				HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
911
				// submit for indexing
912
                MetacatSolrIndex.getInstance().submit(sysMeta.getIdentifier(), sysMeta, null, true);
913
			}
914

    
915
			logReplication.info("ReplicationHandler.handleSystemMetadata - Successfully replicated system metadata for guid: "
916
							+ guid);
917

    
918
			String ip = getIpFromURL(sysMetaUrl);
919
			EventLog.getInstance().log(ip, null, ReplicationService.REPLICATIONUSER, guid, "systemMetadata");
920

    
921
		} catch (Exception e) {
922
			logMetacat.error("ReplicationHandler.handleSystemMetadata - "
923
					+ ReplicationService.METACAT_REPL_ERROR_MSG);
924
			logReplication
925
					.error("ReplicationHandler.handleSystemMetadata - Failed to write system metadata "
926
							+ guid + " into db because " + e.getMessage());
927
			throw new HandlerException(
928
					"ReplicationHandler.handleSystemMetadata - generic exception "
929
							+ "writing Replication: " + e.getMessage());
930
		}
931

    
932
	}
933

    
934
  /**
935
   * updates xml_catalog with entries from other servers.
936
   */
937
  private void updateCatalog()
938
  {
939
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
940
    // ReplicationServer object in server list
941
    ReplicationServer replServer = null;
942
    PreparedStatement pstmt = null;
943
    String server = null;
944

    
945

    
946
    // Go through each ReplicationServer object in sererlist
947
    for (int j=0; j<serverList.size(); j++)
948
    {
949
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
950
      Vector<String> publicId = new Vector<String>();
951
      try
952
      {
953
        // Get ReplicationServer object from server list
954
        replServer = serverList.serverAt(j);
955
        // Get server name from the ReplicationServer object
956
        server = replServer.getServerName();
957
        // Try to get catalog
958
        URL u = new URL("https://" + server + "?server="+
959
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
960
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
961
        String catxml = ReplicationService.getURLContent(u);
962

    
963
        // Make sure there are not error, no empty string
964
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
965
        {
966
          throw new Exception("Couldn't get catalog list form server " +server);
967
        }
968
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
969
        CatalogMessageHandler cmh = new CatalogMessageHandler();
970
        XMLReader catparser = initParser(cmh);
971
        catparser.parse(new InputSource(new StringReader(catxml)));
972
        //parse the returned catalog xml and put it into a vector
973
        remoteCatalog = cmh.getCatalogVect();
974

    
975
        // Make sure remoteCatalog is not empty
976
        if (remoteCatalog.isEmpty())
977
        {
978
          throw new Exception("Couldn't get catalog list form server " +server);
979
        }
980

    
981
        String localcatxml = ReplicationService.getCatalogXML();
982

    
983
        // Make sure local catalog is no empty
984
        if (localcatxml==null||localcatxml.equals(""))
985
        {
986
          throw new Exception("Couldn't get catalog list form server " +server);
987
        }
988

    
989
        cmh = new CatalogMessageHandler();
990
        catparser = initParser(cmh);
991
        catparser.parse(new InputSource(new StringReader(localcatxml)));
992
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
993

    
994
        //now we have the catalog from the remote server and this local server
995
        //we now need to compare the two and merge the differences.
996
        //the comparison is base on the public_id fields which is the 4th
997
        //entry in each row vector.
998
        publicId = new Vector<String>();
999
        for(int i=0; i<localCatalog.size(); i++)
1000
        {
1001
          Vector<String> v = new Vector<String>(localCatalog.elementAt(i));
1002
          logReplication.info("ReplicationHandler.updateCatalog - v1: " + v.toString());
1003
          publicId.add(new String((String)v.elementAt(3)));
1004
        }
1005
      }//try
1006
      catch (Exception e)
1007
      {
1008
        logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1009
        logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
1010
                                    server + " because " +e.getMessage());
1011
      }//catch
1012

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

    
1085
  /**
1086
   * Method that returns true if docid has already been "deleted" from metacat.
1087
   * This method really implements a truth table for deleted documents
1088
   * The table is (a docid in one of the tables is represented by the X):
1089
   * xml_docs      xml_revs      deleted?
1090
   * ------------------------------------
1091
   *   X             X             FALSE
1092
   *   X             _             FALSE
1093
   *   _             X             TRUE
1094
   *   _             _             TRUE
1095
   */
1096
  private static boolean alreadyDeleted(String docid) throws HandlerException
1097
  {
1098
    DBConnection dbConn = null;
1099
    int serialNumber = -1;
1100
    PreparedStatement pstmt = null;
1101
    try
1102
    {
1103
      dbConn=DBConnectionPool.
1104
                  getDBConnection("ReplicationHandler.alreadyDeleted");
1105
      serialNumber=dbConn.getCheckOutSerialNumber();
1106
      boolean xml_docs = false;
1107
      boolean xml_revs = false;
1108

    
1109
      StringBuffer sb = new StringBuffer();
1110
      sb.append("select docid from xml_revisions where docid like ? ");
1111
      pstmt = dbConn.prepareStatement(sb.toString());
1112
      pstmt.setString(1, docid);
1113
      pstmt.execute();
1114
      ResultSet rs = pstmt.getResultSet();
1115
      boolean tablehasrows = rs.next();
1116
      if(tablehasrows)
1117
      {
1118
        xml_revs = true;
1119
      }
1120

    
1121
      sb = new StringBuffer();
1122
      sb.append("select docid from xml_documents where docid like '");
1123
      sb.append(docid).append("'");
1124
      pstmt.close();
1125
      pstmt = dbConn.prepareStatement(sb.toString());
1126
      //increase usage count
1127
      dbConn.increaseUsageCount(1);
1128
      pstmt.execute();
1129
      rs = pstmt.getResultSet();
1130
      tablehasrows = rs.next();
1131
      pstmt.close();
1132
      if(tablehasrows)
1133
      {
1134
        xml_docs = true;
1135
      }
1136

    
1137
      if(xml_docs && xml_revs)
1138
      {
1139
        return false;
1140
      }
1141
      else if(xml_docs && !xml_revs)
1142
      {
1143
        return false;
1144
      }
1145
      else if(!xml_docs && xml_revs)
1146
      {
1147
        return true;
1148
      }
1149
      else if(!xml_docs && !xml_revs)
1150
      {
1151
        return true;
1152
      }
1153
    }
1154
    catch(Exception e)
1155
    {
1156
      logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1157
      logReplication.error("ReplicationHandler.alreadyDeleted - general error in alreadyDeleted: " +
1158
                          e.getMessage());
1159
      throw new HandlerException("ReplicationHandler.alreadyDeleted - general error: " 
1160
    		  + e.getMessage());
1161
    }
1162
    finally
1163
    {
1164
      try
1165
      {
1166
        pstmt.close();
1167
      }//try
1168
      catch (SQLException ee)
1169
      {
1170
    	logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1171
        logReplication.error("ReplicationHandler.alreadyDeleted - Error in replicationHandler.alreadyDeleted "+
1172
                          "to close pstmt: "+ee.getMessage());
1173
        throw new HandlerException("ReplicationHandler.alreadyDeleted - SQL error when closing prepared statement: " 
1174
      		  + ee.getMessage());
1175
      }//catch
1176
      finally
1177
      {
1178
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1179
      }//finally
1180
    }//finally
1181
    return false;
1182
  }
1183

    
1184

    
1185
  /**
1186
   * Method to initialize the message parser
1187
   */
1188
  public static XMLReader initParser(DefaultHandler dh)
1189
          throws HandlerException
1190
  {
1191
    XMLReader parser = null;
1192

    
1193
    try {
1194
      ContentHandler chandler = dh;
1195

    
1196
      // Get an instance of the parser
1197
      String parserName = PropertyService.getProperty("xml.saxparser");
1198
      parser = XMLReaderFactory.createXMLReader(parserName);
1199

    
1200
      // Turn off validation
1201
      parser.setFeature("http://xml.org/sax/features/validation", false);
1202

    
1203
      parser.setContentHandler((ContentHandler)chandler);
1204
      parser.setErrorHandler((ErrorHandler)chandler);
1205

    
1206
    } catch (SAXException se) {
1207
      throw new HandlerException("ReplicationHandler.initParser - Sax error when " 
1208
    		  + " initializing parser: " + se.getMessage());
1209
    } catch (PropertyNotFoundException pnfe) {
1210
        throw new HandlerException("ReplicationHandler.initParser - Property error when " 
1211
      		  + " getting parser name: " + pnfe.getMessage());
1212
    } 
1213

    
1214
    return parser;
1215
  }
1216

    
1217
  /**
1218
	 * This method will combine given time string(in short format) to current
1219
	 * date. If the given time (e.g 10:00 AM) passed the current time (e.g 2:00
1220
	 * PM Aug 21, 2005), then the time will set to second day, 10:00 AM Aug 22,
1221
	 * 2005. If the given time (e.g 10:00 AM) haven't passed the current time
1222
	 * (e.g 8:00 AM Aug 21, 2005) The time will set to be 10:00 AM Aug 21, 2005.
1223
	 * 
1224
	 * @param givenTime
1225
	 *            the format should be "10:00 AM " or "2:00 PM"
1226
	 * @return
1227
	 * @throws Exception
1228
	 */
1229
	public static Date combinateCurrentDateAndGivenTime(String givenTime) throws HandlerException
1230
  {
1231
	  try {
1232
     Date givenDate = parseTime(givenTime);
1233
     Date newDate = null;
1234
     Date now = new Date();
1235
     String currentTimeString = getTimeString(now);
1236
     Date currentTime = parseTime(currentTimeString); 
1237
     if ( currentTime.getTime() >= givenDate.getTime())
1238
     {
1239
        logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today already pass the given time, we should set it as tomorrow");
1240
        String dateAndTime = getDateString(now) + " " + givenTime;
1241
        Date combinationDate = parseDateTime(dateAndTime);
1242
        // new date should plus 24 hours to make is the second day
1243
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
1244
     }
1245
     else
1246
     {
1247
         logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today haven't pass the given time, we should it as today");
1248
         String dateAndTime = getDateString(now) + " " + givenTime;
1249
         newDate = parseDateTime(dateAndTime);
1250
     }
1251
     logReplication.warn("ReplicationHandler.combinateCurrentDateAndGivenTime - final setting time is "+ newDate.toString());
1252
     return newDate;
1253
	  } catch (ParseException pe) {
1254
		  throw new HandlerException("ReplicationHandler.combinateCurrentDateAndGivenTime - "
1255
				  + "parsing error: "  + pe.getMessage());
1256
	  }
1257
  }
1258

    
1259
  /*
1260
	 * parse a given string to Time in short format. For example, given time is
1261
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1262
	 */
1263
  private static Date parseTime(String timeString) throws ParseException
1264
  {
1265
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1266
    Date time = format.parse(timeString); 
1267
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1268
                              +time.toString());
1269
    return time;
1270

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

    
1344
			try {
1345
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1346
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1347
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1348
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1349
				} else {
1350
					continue;
1351
				}
1352

    
1353
			} catch (Exception e) {
1354
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1355
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1356
						+ " in time replication" + e.getMessage(), e);
1357
				continue;
1358
			}
1359
			
1360
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1361
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount + 
1362
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1363
	        }
1364
	        
1365
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1366
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount + 
1367
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1368
	        }
1369

    
1370
		}// for update docs
1371

    
1372
	}
1373
   
1374
   /*
1375
	 * This method will handle doc in xml_documents table.
1376
	 */
1377
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile) 
1378
                                        throws HandlerException
1379
   {
1380
       // compare the update rev and local rev to see what need happen
1381
       int localrev = -1;
1382
       String action = null;
1383
       boolean flag = false;
1384
       try
1385
       {
1386
    	 long docQueryStartTime = System.currentTimeMillis();
1387
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1388
         long docQueryEndTime = System.currentTimeMillis();
1389
         _xmlDocQueryTime += (docQueryEndTime - docQueryStartTime);
1390
         _xmlDocQueryCount++;
1391
       }
1392
       catch (SQLException e)
1393
       {
1394
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1395
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1396
                                " be found because " + e.getMessage());
1397
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - " + DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1398
                 "written because error happend to find it's local revision");
1399
         DOCERRORNUMBER++;
1400
         throw new HandlerException ("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1401
                 " be found: " + e.getMessage());
1402
       }
1403
       logReplication.info("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " is "+
1404
                               localrev);
1405

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

    
1471
        // this is for data file
1472
       if(flag && dataFile)
1473
       {
1474
         try
1475
         {
1476
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1477
         }
1478
         catch(HandlerException he)
1479
         {
1480
           // skip this data file
1481
           throw he;
1482
         }
1483

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

    
1548
        // this is for data file
1549
       if(flag && dataFile)
1550
       {
1551
         try
1552
         {
1553
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1554
         }
1555
         catch(HandlerException he)
1556
         {
1557
           // skip this data file
1558
           throw he;
1559
         }
1560

    
1561
       }//for data file
1562
   }
1563
   
1564
   /*
1565
    * Return a ip address for given url
1566
    */
1567
   private String getIpFromURL(URL url)
1568
   {
1569
	   String ip = null;
1570
	   try
1571
	   {
1572
	      InetAddress address = InetAddress.getByName(url.getHost());
1573
	      ip = address.getHostAddress();
1574
	   }
1575
	   catch(UnknownHostException e)
1576
	   {
1577
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1578
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1579
                   +e.getMessage());
1580
	   }
1581

    
1582
	   return ip;
1583
   }
1584
  
1585
}
1586

    
(3-3/7)