Project

General

Profile

1 522 berkley
/**
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$'
9
 *     '$Date$'
10
 * '$Revision$'
11 669 jones
 *
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 522 berkley
 */
26 2286 tao
27 5014 daigle
package edu.ucsb.nceas.metacat.replication;
28 522 berkley
29 6448 leinfelder
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.text.DateFormat;
39
import java.text.ParseException;
40
import java.util.Date;
41
import java.util.Hashtable;
42
import java.util.TimerTask;
43
import java.util.Vector;
44
45
import org.apache.log4j.Logger;
46
import org.dataone.service.types.v1.SystemMetadata;
47
import org.dataone.service.util.TypeMarshaller;
48
import org.xml.sax.ContentHandler;
49
import org.xml.sax.ErrorHandler;
50
import org.xml.sax.InputSource;
51
import org.xml.sax.SAXException;
52
import org.xml.sax.XMLReader;
53
import org.xml.sax.helpers.DefaultHandler;
54
import org.xml.sax.helpers.XMLReaderFactory;
55
56 5014 daigle
import edu.ucsb.nceas.metacat.CatalogMessageHandler;
57
import edu.ucsb.nceas.metacat.DBUtil;
58
import edu.ucsb.nceas.metacat.DocInfoHandler;
59
import edu.ucsb.nceas.metacat.DocumentImpl;
60
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
61
import edu.ucsb.nceas.metacat.EventLog;
62 6001 cjones
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
63 5089 daigle
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
64 5098 daigle
import edu.ucsb.nceas.metacat.accesscontrol.XMLAccessDAO;
65 6001 cjones
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
66 5014 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
67
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
68
import edu.ucsb.nceas.metacat.database.DatabaseService;
69 6447 leinfelder
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
70 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
71 5014 daigle
import edu.ucsb.nceas.metacat.shared.HandlerException;
72 4698 daigle
import edu.ucsb.nceas.metacat.util.MetacatUtil;
73 4080 daigle
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
74
75 2663 sgarg
76 522 berkley
77
/**
78
 * This class handles deltaT replication checking.  Whenever this TimerTask
79
 * is fired it checks each server in xml_replication for updates and updates
80
 * the local db as needed.
81
 */
82
public class ReplicationHandler extends TimerTask
83
{
84 573 berkley
  int serverCheckCode = 1;
85 2286 tao
  ReplicationServerList serverList = null;
86 2573 tao
  //PrintWriter out;
87 4698 daigle
//  private static final AbstractDatabase dbAdapter = MetacatUtil.dbAdapter;
88 5014 daigle
  private static Logger logReplication = Logger.getLogger("ReplicationLogging");
89 2663 sgarg
  private static Logger logMetacat = Logger.getLogger(ReplicationHandler.class);
90 5392 berkley
  private static Logger logD1 = Logger.getLogger("DataOneLogger");
91
92 2725 tao
  private static int DOCINSERTNUMBER = 1;
93
  private static int DOCERRORNUMBER  = 1;
94
  private static int REVINSERTNUMBER = 1;
95
  private static int REVERRORNUMBER  = 1;
96 5175 daigle
97
  private static int _xmlDocQueryCount = 0;
98
  private static int _xmlRevQueryCount = 0;
99
  private static long _xmlDocQueryTime = 0;
100
  private static long _xmlRevQueryTime = 0;
101
102
103 2573 tao
  public ReplicationHandler()
104 522 berkley
  {
105 2573 tao
    //this.out = o;
106 1292 tao
    serverList = new ReplicationServerList();
107 522 berkley
  }
108 2286 tao
109 2573 tao
  public ReplicationHandler(int serverCheckCode)
110 573 berkley
  {
111 2573 tao
    //this.out = o;
112 573 berkley
    this.serverCheckCode = serverCheckCode;
113 1292 tao
    serverList = new ReplicationServerList();
114 573 berkley
  }
115 2286 tao
116 522 berkley
  /**
117 2286 tao
   * Method that implements TimerTask.run().  It runs whenever the timer is
118 522 berkley
   * fired.
119
   */
120
  public void run()
121
  {
122
    //find out the last_checked time of each server in the server list and
123 2286 tao
    //send a query to each server to see if there are any documents in
124 522 berkley
    //xml_documents with an update_date > last_checked
125 5014 daigle
126 1032 tao
      //if serverList is null, metacat don't need to replication
127
      if (serverList==null||serverList.isEmpty())
128
      {
129
        return;
130
      }
131 1292 tao
      updateCatalog();
132
      update();
133 1217 tao
      //conn.close();
134 522 berkley
  }
135 2286 tao
136 522 berkley
  /**
137 5175 daigle
   * Method that uses revision tagging for replication instead of update_date.
138 577 berkley
   */
139 1292 tao
  private void update()
140 577 berkley
  {
141 5175 daigle
142
	  _xmlDocQueryCount = 0;
143
	  _xmlRevQueryCount = 0;
144
	  _xmlDocQueryTime = 0;
145
	  _xmlRevQueryTime = 0;
146 577 berkley
    /*
147
     Pseudo-algorithm
148
     - request a doc list from each server in xml_replication
149 2286 tao
     - check the rev number of each of those documents agains the
150 577 berkley
       documents in the local database
151
     - pull any documents that have a lesser rev number on the local server
152
       from the remote server
153
     - delete any documents that still exist in the local xml_documents but
154
       are in the deletedDocuments tag of the remote host response.
155
     - update last_checked to keep track of the last time it was checked.
156 2286 tao
       (this info is theoretically not needed using this system but probably
157 577 berkley
       should be kept anyway)
158
    */
159 2286 tao
160
    ReplicationServer replServer = null; // Variable to store the
161
                                        // ReplicationServer got from
162 1292 tao
                                        // Server list
163 2298 tao
    String server = null; // Variable to store server name
164 5014 daigle
//    String update;
165
    Vector<String> responses = new Vector<String>();
166 577 berkley
    URL u;
167 5175 daigle
    long replicationStartTime = System.currentTimeMillis();
168
    long timeToGetServerList = 0;
169 3898 tao
170 1585 tao
    //Check for every server in server list to get updated list and put
171
    // them in to response
172 5175 daigle
    long startTimeToGetServers = System.currentTimeMillis();
173 1585 tao
    for (int i=0; i<serverList.size(); i++)
174
    {
175 1292 tao
        // Get ReplicationServer object from server list
176
        replServer = serverList.serverAt(i);
177
        // Get server name from ReplicationServer object
178 2578 tao
        server = replServer.getServerName().trim();
179 1585 tao
        String result = null;
180 5014 daigle
        logReplication.info("ReplicationHandler.update - full update started to: " + server);
181 1292 tao
        // Send command to that server to get updated docid information
182
        try
183
        {
184 1585 tao
          u = new URL("https://" + server + "?server="
185 4698 daigle
          +MetacatUtil.getLocalReplicationServerName()+"&action=update");
186 5014 daigle
          logReplication.info("ReplicationHandler.update - Sending infomation " +u.toString());
187
          result = ReplicationService.getURLContent(u);
188 1585 tao
        }
189 1292 tao
        catch (Exception e)
190
        {
191 5014 daigle
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
192
          logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
193 2663 sgarg
                       "for server " + server + " because "+e.getMessage());
194 1292 tao
          continue;
195 1585 tao
        }
196 2286 tao
197 5175 daigle
        //logReplication.info("ReplicationHandler.update - docid: "+server+" "+result);
198 1292 tao
        //check if result have error or not, if has skip it.
199 1609 tao
        if (result.indexOf("<error>")!=-1 && result.indexOf("</error>")!=-1)
200 1102 tao
        {
201 5014 daigle
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
202
          logReplication.error( "ReplicationHandler.update - Failed to get updated doc list "+
203 2663 sgarg
                       "for server " + server + " because "+result);
204 1102 tao
          continue;
205
        }
206 1585 tao
        //Add result to vector
207 577 berkley
        responses.add(result);
208 1585 tao
    }
209 5175 daigle
    timeToGetServerList = System.currentTimeMillis() - startTimeToGetServers;
210 2286 tao
211 1585 tao
    //make sure that there is updated file list
212
    //If response is null, metacat don't need do anything
213
    if (responses==null || responses.isEmpty())
214
    {
215 5014 daigle
    	logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
216
        logReplication.info( "ReplicationHandler.update - No updated doc list for "+
217 1585 tao
                           "every server and failed to replicate");
218 1032 tao
        return;
219 1585 tao
    }
220 2286 tao
221
222 5175 daigle
    //logReplication.info("ReplicationHandler.update - Responses from remote metacat about updated "+
223
    //               "document information: "+ responses.toString());
224
225
    long totalServerListParseTime = 0;
226 1585 tao
    // go through response vector(it contains updated vector and delete vector
227
    for(int i=0; i<responses.size(); i++)
228 2286 tao
    {
229 5175 daigle
    	long startServerListParseTime = System.currentTimeMillis();
230 3898 tao
    	XMLReader parser;
231
    	ReplMessageHandler message = new ReplMessageHandler();
232
    	try
233
        {
234
          parser = initParser(message);
235
        }
236
        catch (Exception e)
237
        {
238 5014 daigle
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
239
          logReplication.error("ReplicationHandler.update - Failed to replicate becaue couldn't " +
240 3898 tao
                                " initParser for message and " +e.getMessage());
241
           // stop replication
242
           return;
243
        }
244
245 1585 tao
        try
246
        {
247
          parser.parse(new InputSource(
248 577 berkley
                     new StringReader(
249
                     (String)(responses.elementAt(i)))));
250 1585 tao
        }
251
        catch(Exception e)
252
        {
253 5014 daigle
          logMetacat.error("ReplicationHandler.update - " + ReplicationService.METACAT_REPL_ERROR_MSG);
254
          logReplication.error("ReplicationHandler.update - Couldn't parse one responses "+
255 2663 sgarg
                                   "because "+ e.getMessage());
256 1585 tao
          continue;
257
        }
258 1037 tao
        //v is the list of updated documents
259 5014 daigle
        Vector<Vector<String>> updateList = new Vector<Vector<String>>(message.getUpdatesVect());
260
        logReplication.info("ReplicationHandler.update - The document list size is "+updateList.size()+ " from "+message.getServerName());
261 1037 tao
        //d is the list of deleted documents
262 5014 daigle
        Vector<Vector<String>> deleteList = new Vector<Vector<String>>(message.getDeletesVect());
263
        logReplication.info("ReplicationHandler.update - Update vector size: "+ updateList.size()+" from "+message.getServerName());
264
        logReplication.info("ReplicationHandler.update - Delete vector size: "+ deleteList.size()+" from "+message.getServerName());
265
        logReplication.info("ReplicationHandler.update - The delete document list size is "+deleteList.size()+" from "+message.getServerName());
266 1585 tao
        // go though every element in updated document vector
267 2608 tao
        handleDocList(updateList, DocumentImpl.DOCUMENTTABLE);
268 1037 tao
        //handle deleted docs
269 1585 tao
        for(int k=0; k<deleteList.size(); k++)
270 577 berkley
        { //delete the deleted documents;
271 5014 daigle
          Vector<String> w = new Vector<String>(deleteList.elementAt(k));
272 1585 tao
          String docId = (String)w.elementAt(0);
273
          try
274 579 berkley
          {
275 2298 tao
            handleDeleteSingleDocument(docId, server);
276 579 berkley
          }
277 1585 tao
          catch (Exception ee)
278
          {
279
            continue;
280
          }
281 1037 tao
        }//for delete docs
282 2608 tao
283
        // handle replicate doc in xml_revision
284 5014 daigle
        Vector<Vector<String>> revisionList = new Vector<Vector<String>>(message.getRevisionsVect());
285
        logReplication.info("ReplicationHandler.update - The revision document list size is "+revisionList.size()+ " from "+message.getServerName());
286 2608 tao
        handleDocList(revisionList, DocumentImpl.REVISIONTABLE);
287 2725 tao
        DOCINSERTNUMBER = 1;
288
        DOCERRORNUMBER  = 1;
289
        REVINSERTNUMBER = 1;
290
        REVERRORNUMBER  = 1;
291 5175 daigle
292 6118 leinfelder
        // handle system metadata
293
        Vector<Vector<String>> systemMetadataList = message.getSystemMetadataVect();
294
        for(int k = 0; k < systemMetadataList.size(); k++) {
295
        	Vector<String> w = systemMetadataList.elementAt(k);
296
        	String guid = (String) w.elementAt(0);
297
        	String remoteserver = (String) w.elementAt(1);
298
        	try {
299
        		handleSystemMetadata(remoteserver, guid);
300
        	}
301
        	catch (Exception ee) {
302
        		logMetacat.error("Error replicating system metedata for guid: " + guid, ee);
303
        		continue;
304
        	}
305
        }
306
307 5175 daigle
        totalServerListParseTime += (System.currentTimeMillis() - startServerListParseTime);
308 1585 tao
    }//for response
309 2286 tao
310 1585 tao
    //updated last_checked
311
    for (int i=0;i<serverList.size(); i++)
312
    {
313
       // Get ReplicationServer object from server list
314
       replServer = serverList.serverAt(i);
315
       try
316
       {
317
         updateLastCheckTimeForSingleServer(replServer);
318
       }
319
       catch(Exception e)
320
       {
321
         continue;
322
       }
323
    }//for
324 5175 daigle
325
    long replicationEndTime = System.currentTimeMillis();
326
    logMetacat.debug("ReplicationHandler.update - Total replication time: " +
327
    		(replicationEndTime - replicationStartTime));
328
    logMetacat.debug("ReplicationHandler.update - time to get server list: " +
329
    		timeToGetServerList);
330
    logMetacat.debug("ReplicationHandler.update - server list parse time: " +
331
    		totalServerListParseTime);
332
    logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query count: " +
333
    		_xmlDocQueryCount);
334
    logMetacat.debug("ReplicationHandler.update - 'in xml_documents' total query time: " +
335
    		_xmlDocQueryTime + " ms");
336
    logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query count: " +
337
    		_xmlRevQueryCount);
338
    logMetacat.debug("ReplicationHandler.update - 'in xml_revisions' total query time: " +
339
    		_xmlRevQueryTime + " ms");;
340 2286 tao
341 1585 tao
  }//update
342 2286 tao
343 1585 tao
  /* Handle replicate single xml document*/
344 2286 tao
  private void handleSingleXMLDocument(String remoteserver, String actions,
345 2641 tao
                                       String accNumber, String tableName)
346 5014 daigle
               throws HandlerException
347 1585 tao
  {
348
    DBConnection dbConn = null;
349
    int serialNumber = -1;
350
    try
351
    {
352
      // Get DBConnection from pool
353
      dbConn=DBConnectionPool.
354
                  getDBConnection("ReplicationHandler.handleSingleXMLDocument");
355
      serialNumber=dbConn.getCheckOutSerialNumber();
356
      //if the document needs to be updated or inserted, this is executed
357 1600 tao
      String readDocURLString = "https://" + remoteserver + "?server="+
358 4698 daigle
              MetacatUtil.getLocalReplicationServerName()+"&action=read&docid="+accNumber;
359
      readDocURLString = MetacatUtil.replaceWhiteSpaceForURL(readDocURLString);
360 1600 tao
      URL u = new URL(readDocURLString);
361 2286 tao
362 1585 tao
      // Get docid content
363 5014 daigle
      String newxmldoc = ReplicationService.getURLContent(u);
364 1585 tao
      // If couldn't get skip it
365 1609 tao
      if ( newxmldoc.indexOf("<error>")!= -1 && newxmldoc.indexOf("</error>")!=-1)
366 1292 tao
      {
367 5014 daigle
         throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - " + newxmldoc);
368 1585 tao
      }
369 5014 daigle
      //logReplication.info("xml documnet:");
370
      //logReplication.info(newxmldoc);
371 2286 tao
372 1585 tao
      // Try get the docid info from remote server
373
      DocInfoHandler dih = new DocInfoHandler();
374
      XMLReader docinfoParser = initParser(dih);
375 2286 tao
      String docInfoURLStr = "https://" + remoteserver +
376 4698 daigle
                       "?server="+MetacatUtil.getLocalReplicationServerName()+
377 2641 tao
                       "&action=getdocumentinfo&docid="+accNumber;
378 4698 daigle
      docInfoURLStr = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLStr);
379 1600 tao
      URL docinfoUrl = new URL(docInfoURLStr);
380 6102 leinfelder
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Sending message: " + docinfoUrl.toString());
381 5014 daigle
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
382 6102 leinfelder
383 1585 tao
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
384 5014 daigle
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
385 1585 tao
      // Get home server of the docid
386 5014 daigle
      String docHomeServer = docinfoHash.get("home_server");
387
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doc home server in repl: "+docHomeServer);
388
      String createdDate = docinfoHash.get("date_created");
389
      String updatedDate = docinfoHash.get("date_updated");
390 1585 tao
      //docid should include rev number too
391 4212 daigle
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
392 2641 tao
                                              (String)docinfoHash.get("rev");*/
393 5014 daigle
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - docid in repl: "+accNumber);
394
      String docType = docinfoHash.get("doctype");
395
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - doctype in repl: "+docType);
396 2286 tao
397 1585 tao
      String parserBase = null;
398
      // this for eml2 and we need user eml2 parser
399 2169 sgarg
      if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
400 1585 tao
      {
401 2163 tao
         parserBase = DocumentImpl.EML200;
402 1585 tao
      }
403 2286 tao
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
404
      {
405
        parserBase = DocumentImpl.EML200;
406
      }
407
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
408
      {
409
        parserBase = DocumentImpl.EML210;
410
      }
411 5709 leinfelder
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_1NAMESPACE))
412
      {
413
        parserBase = DocumentImpl.EML210;
414
      }
415 1585 tao
      // Write the document into local host
416
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
417 2286 tao
      String newDocid = wrapper.writeReplication(dbConn,
418 5195 daigle
                              newxmldoc,
419 5014 daigle
                              docinfoHash.get("public_access"),
420 1585 tao
                              null,  /* the dtd text */
421 2286 tao
                              actions,
422 2641 tao
                              accNumber,
423 6015 leinfelder
                              null, //docinfoHash.get("user_owner"),
424 1585 tao
                              null, /* null for groups[] */
425 2286 tao
                              docHomeServer,
426 2624 tao
                              remoteserver, tableName, true,// true is for time replication
427
                              createdDate,
428 3230 tao
                              updatedDate);
429 4419 leinfelder
430 6015 leinfelder
      //set the user information
431
      String user = (String) docinfoHash.get("user_owner");
432
      String updated = (String) docinfoHash.get("user_updated");
433
      ReplicationService.updateUserOwner(dbConn, accNumber, user, updated);
434
435 5098 daigle
      //process extra access rules
436
      Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
437
      if (xmlAccessDAOList != null) {
438
      	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
439
      	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
440
      		if (!acfsf.accessControlExists(xmlAccessDAO)) {
441
      			acfsf.insertPermissions(xmlAccessDAO);
442
      		}
443 4419 leinfelder
          }
444
      }
445
446 5014 daigle
      logReplication.info("ReplicationHandler.handleSingleXMLDocument - Successfully replicated doc " + accNumber);
447 2725 tao
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
448
      {
449 5014 daigle
        logReplication.info("ReplicationHandler.handleSingleXMLDocument - " + DOCINSERTNUMBER + " Wrote xml doc " + accNumber +
450 2725 tao
                                     " into "+tableName + " from " +
451 1585 tao
                                         remoteserver);
452 2725 tao
        DOCINSERTNUMBER++;
453
      }
454
      else
455
      {
456 5014 daigle
          logReplication.info("ReplicationHandler.handleSingleXMLDocument - " +REVINSERTNUMBER + " Wrote xml doc " + accNumber +
457 2725 tao
                  " into "+tableName + " from " +
458
                      remoteserver);
459
          REVINSERTNUMBER++;
460
      }
461 3234 tao
      String ip = getIpFromURL(u);
462 5014 daigle
      EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, accNumber, actions);
463 2725 tao
464 2286 tao
465
    }//try
466 577 berkley
    catch(Exception e)
467
    {
468 2725 tao
469
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
470
        {
471 5014 daigle
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG);
472
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +DOCERRORNUMBER + " Failed to write xml doc " + accNumber +
473 2725 tao
                                       " into "+tableName + " from " +
474
                                           remoteserver + " because "+e.getMessage());
475
          DOCERRORNUMBER++;
476
        }
477
        else
478
        {
479 5014 daigle
        	logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG);
480
        	logReplication.error("ReplicationHandler.handleSingleXMLDocument - " +REVERRORNUMBER + " Failed to write xml doc " + accNumber +
481 2725 tao
                    " into "+tableName + " from " +
482
                        remoteserver +" because "+e.getMessage());
483
            REVERRORNUMBER++;
484
        }
485 5014 daigle
        logMetacat.error("ReplicationHandler.handleSingleXMLDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG);
486
        logReplication.error("ReplicationHandler.handleSingleXMLDocument - Failed to write doc " + accNumber +
487 2663 sgarg
                                      " into db because " +e.getMessage());
488 5014 daigle
      throw new HandlerException("ReplicationHandler.handleSingleXMLDocument - generic exception "
489
    		  + "writing Replication: " +e.getMessage());
490 577 berkley
    }
491 667 berkley
    finally
492
    {
493 1585 tao
       //return DBConnection
494
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
495
    }//finally
496 5392 berkley
    logD1.info("replication.create localId:" + accNumber);
497 1585 tao
  }
498 2286 tao
499
500
501 1585 tao
  /* Handle replicate single xml document*/
502 2286 tao
  private void handleSingleDataFile(String remoteserver, String actions,
503 2641 tao
                                    String accNumber, String tableName)
504 5014 daigle
               throws HandlerException
505 1585 tao
  {
506 5014 daigle
    logReplication.info("ReplicationHandler.handleSingleDataFile - Try to replicate data file: " + accNumber);
507 1585 tao
    DBConnection dbConn = null;
508
    int serialNumber = -1;
509
    try
510
    {
511
      // Get DBConnection from pool
512
      dbConn=DBConnectionPool.
513
                  getDBConnection("ReplicationHandler.handleSinlgeDataFile");
514
      serialNumber=dbConn.getCheckOutSerialNumber();
515
      // Try get docid info from remote server
516
      DocInfoHandler dih = new DocInfoHandler();
517
      XMLReader docinfoParser = initParser(dih);
518 2286 tao
      String docInfoURLString = "https://" + remoteserver +
519 4698 daigle
                  "?server="+MetacatUtil.getLocalReplicationServerName()+
520 2641 tao
                  "&action=getdocumentinfo&docid="+accNumber;
521 4698 daigle
      docInfoURLString = MetacatUtil.replaceWhiteSpaceForURL(docInfoURLString);
522 1600 tao
      URL docinfoUrl = new URL(docInfoURLString);
523 2286 tao
524 5014 daigle
      String docInfoStr = ReplicationService.getURLContent(docinfoUrl);
525 6102 leinfelder
526 1585 tao
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
527 5014 daigle
      Hashtable<String, String> docinfoHash = dih.getDocInfo();
528 6015 leinfelder
529 1585 tao
      // Get docid name (such as acl or dataset)
530 5014 daigle
      String docName = docinfoHash.get("docname");
531 2286 tao
      // Get doc type (eml public id)
532 5014 daigle
      String docType = docinfoHash.get("doctype");
533 1585 tao
      // Get docid home sever. it might be different to remoteserver
534 5175 daigle
      // because of hub feature
535 5014 daigle
      String docHomeServer = docinfoHash.get("home_server");
536
      String createdDate = docinfoHash.get("date_created");
537
      String updatedDate = docinfoHash.get("date_updated");
538 1585 tao
      //docid should include rev number too
539 4212 daigle
      /*String accnum=docId+util.getProperty("document.accNumSeparator")+
540 2641 tao
                                              (String)docinfoHash.get("rev");*/
541 2286 tao
542 4080 daigle
      String datafilePath = PropertyService.getProperty("application.datafilepath");
543 1585 tao
      // Get data file content
544 1600 tao
      String readDataURLString = "https://" + remoteserver + "?server="+
545 4698 daigle
                                        MetacatUtil.getLocalReplicationServerName()+
546 2641 tao
                                            "&action=readdata&docid="+accNumber;
547 4698 daigle
      readDataURLString = MetacatUtil.replaceWhiteSpaceForURL(readDataURLString);
548 1600 tao
      URL u = new URL(readDataURLString);
549 2286 tao
      InputStream input = u.openStream();
550 1585 tao
      //register data file into xml_documents table and wite data file
551
      //into file system
552 1600 tao
      if ( input != null)
553 667 berkley
      {
554 2286 tao
        DocumentImpl.writeDataFileInReplication(input,
555 2608 tao
                                                datafilePath,
556
                                                docName,docType,
557 6015 leinfelder
                                                accNumber,
558
                                                null,
559 2608 tao
                                                docHomeServer,
560
                                                remoteserver,
561
                                                tableName,
562 2624 tao
                                                true, //true means timed replication
563
                                                createdDate,
564 3230 tao
                                                updatedDate);
565 2624 tao
566 6015 leinfelder
        //set the user information
567
        String user = (String) docinfoHash.get("user_owner");
568
		String updated = (String) docinfoHash.get("user_updated");
569
        ReplicationService.updateUserOwner(dbConn, accNumber, user, updated);
570
571 4419 leinfelder
        //process extra access rules
572 5098 daigle
        Vector<XMLAccessDAO> xmlAccessDAOList = dih.getAccessControlList();
573
        if (xmlAccessDAOList != null) {
574
        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(accNumber);
575
        	for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
576
        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
577
        			acfsf.insertPermissions(xmlAccessDAO);
578
        		}
579 4419 leinfelder
            }
580
        }
581
582 5014 daigle
        logReplication.info("ReplicationHandler.handleSingleDataFile - Successfully to write datafile " + accNumber);
583 2725 tao
        /*MetacatReplication.replLog("wrote datafile " + accNumber + " from " +
584 5175 daigle
                                    remote server);*/
585 2725 tao
        if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
586
        {
587 5014 daigle
          logReplication.info("ReplicationHandler.handleSingleDataFile - " + DOCINSERTNUMBER + " Wrote data file" + accNumber +
588 2725 tao
                                       " into "+tableName + " from " +
589
                                           remoteserver);
590
          DOCINSERTNUMBER++;
591
        }
592
        else
593
        {
594 5014 daigle
            logReplication.info("ReplicationHandler.handleSingleDataFile - " + REVINSERTNUMBER + " Wrote data file" + accNumber +
595 2725 tao
                    " into "+tableName + " from " +
596
                        remoteserver);
597
            REVINSERTNUMBER++;
598
        }
599 3234 tao
        String ip = getIpFromURL(u);
600 5014 daigle
        EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, accNumber, actions);
601 2725 tao
602 1585 tao
      }//if
603
      else
604 1217 tao
      {
605 5014 daigle
         logReplication.info("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
606
         throw new HandlerException("ReplicationHandler.handleSingleDataFile - Couldn't open the data file: " + accNumber);
607 1585 tao
      }//else
608 2286 tao
609
    }//try
610 1585 tao
    catch(Exception e)
611
    {
612 5175 daigle
      /*MetacatReplication.replErrorLog("Failed to try wrote data file " + accNumber +
613 2725 tao
                                      " because " +e.getMessage());*/
614
      if (tableName.equals(DocumentImpl.DOCUMENTTABLE))
615
      {
616 5014 daigle
    	logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG);
617
    	logReplication.error("ReplicationHandler.handleSingleDataFile - " + DOCERRORNUMBER + " Failed to write data file " + accNumber +
618
                                     " into " + tableName + " from " +
619
                                         remoteserver + " because " + e.getMessage());
620 2725 tao
        DOCERRORNUMBER++;
621
      }
622
      else
623
      {
624 5014 daigle
    	  logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG);
625
    	  logReplication.error("ReplicationHandler.handleSingleDataFile - " + REVERRORNUMBER + " Failed to write data file" + accNumber +
626
                  " into " + tableName + " from " +
627
                      remoteserver +" because "+ e.getMessage());
628 2725 tao
          REVERRORNUMBER++;
629
      }
630 5014 daigle
      logMetacat.error("ReplicationHandler.handleSingleDataFile - " + ReplicationService.METACAT_REPL_ERROR_MSG);
631
      logReplication.error("ReplicationHandler.handleSingleDataFile - Failed to try wrote datafile " + accNumber +
632
                                      " because " + e.getMessage());
633
      throw new HandlerException("ReplicationHandler.handleSingleDataFile - generic exception "
634
    		  + "writing Replication: " + e.getMessage());
635 1585 tao
    }
636
    finally
637
    {
638
       //return DBConnection
639
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
640
    }//finally
641 5392 berkley
    logD1.info("replication.create localId:" + accNumber);
642 1585 tao
  }
643 2286 tao
644
645
646 1585 tao
  /* Handle delete single document*/
647 2298 tao
  private void handleDeleteSingleDocument(String docId, String notifyServer)
648 5014 daigle
               throws HandlerException
649 1585 tao
  {
650 5014 daigle
    logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Try delete doc: "+docId);
651 1585 tao
    DBConnection dbConn = null;
652
    int serialNumber = -1;
653
    try
654
    {
655
      // Get DBConnection from pool
656
      dbConn=DBConnectionPool.
657
                  getDBConnection("ReplicationHandler.handleDeleteSingleDoc");
658
      serialNumber=dbConn.getCheckOutSerialNumber();
659
      if(!alreadyDeleted(docId))
660 1217 tao
      {
661 2286 tao
662 1585 tao
         //because delete method docid should have rev number
663
         //so we just add one for it. This rev number is no sence.
664 4212 daigle
         String accnum=docId+PropertyService.getProperty("document.accNumSeparator")+"1";
665 3230 tao
         DocumentImpl.delete(accnum, null, null, notifyServer);
666 5014 daigle
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Successfully deleted doc " + docId);
667
         logReplication.info("ReplicationHandler.handleDeleteSingleDocument - Doc " + docId + " deleted");
668 3234 tao
         URL u = new URL("https://"+notifyServer);
669
         String ip = getIpFromURL(u);
670 5014 daigle
         EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, docId, "delete");
671 1585 tao
      }
672 2286 tao
673
    }//try
674 6001 cjones
    catch(McdbDocNotFoundException e)
675
    {
676
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG);
677
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
678
                                 " in db because because " + e.getMessage());
679
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception "
680
    		  + "when handling document: " + e.getMessage());
681
    }
682
    catch(InsufficientKarmaException e)
683
    {
684
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG);
685
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
686
                                 " in db because because " + e.getMessage());
687
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception "
688
    		  + "when handling document: " + e.getMessage());
689
    }
690
    catch(SQLException e)
691
    {
692
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG);
693
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
694
                                 " in db because because " + e.getMessage());
695
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception "
696
    		  + "when handling document: " + e.getMessage());
697
    }
698 1585 tao
    catch(Exception e)
699
    {
700 5014 daigle
      logMetacat.error("ReplicationHandler.handleDeleteSingleDocument - " + ReplicationService.METACAT_REPL_ERROR_MSG);
701
      logReplication.error("ReplicationHandler.handleDeleteSingleDocument - Failed to delete doc " + docId +
702 2663 sgarg
                                 " in db because because " + e.getMessage());
703 5014 daigle
      throw new HandlerException("ReplicationHandler.handleDeleteSingleDocument - generic exception "
704
    		  + "when handling document: " + e.getMessage());
705 1585 tao
    }
706
    finally
707
    {
708
       //return DBConnection
709
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
710 1037 tao
    }//finally
711 5392 berkley
    logD1.info("replication.handleDeleteSingleDocument localId:" + docId);
712 1585 tao
  }
713 2286 tao
714 1585 tao
  /* Handle updateLastCheckTimForSingleServer*/
715 2286 tao
  private void updateLastCheckTimeForSingleServer(ReplicationServer repServer)
716 5014 daigle
                                                  throws HandlerException
717 590 berkley
  {
718 1585 tao
    String server = repServer.getServerName();
719 1217 tao
    DBConnection dbConn = null;
720
    int serialNumber = -1;
721
    PreparedStatement pstmt = null;
722 590 berkley
    try
723
    {
724 1585 tao
      // Get DBConnection from pool
725 1217 tao
      dbConn=DBConnectionPool.
726 1585 tao
             getDBConnection("ReplicationHandler.updateLastCheckTimeForServer");
727 1217 tao
      serialNumber=dbConn.getCheckOutSerialNumber();
728 2286 tao
729 5014 daigle
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Try to update last_check for server: "+server);
730 1585 tao
      // Get time from remote server
731
      URL dateurl = new URL("https://" + server + "?server="+
732 4698 daigle
      MetacatUtil.getLocalReplicationServerName()+"&action=gettime");
733 5014 daigle
      String datexml = ReplicationService.getURLContent(dateurl);
734
      logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - datexml: "+datexml);
735 1585 tao
      if (datexml!=null && !datexml.equals(""))
736
      {
737
         String datestr = datexml.substring(11, datexml.indexOf('<', 11));
738
         StringBuffer sql = new StringBuffer();
739 1751 tao
         /*sql.append("update xml_replication set last_checked = to_date('");
740 1585 tao
         sql.append(datestr).append("', 'YY-MM-DD HH24:MI:SS') where ");
741 1751 tao
         sql.append("server like '").append(server).append("'");*/
742
         sql.append("update xml_replication set last_checked = ");
743 5319 jones
         sql.append(DatabaseService.getInstance().getDBAdapter().toDate(datestr, "MM/DD/YY HH24:MI:SS"));
744 1751 tao
         sql.append(" where server like '").append(server).append("'");
745 1585 tao
         pstmt = dbConn.prepareStatement(sql.toString());
746 2286 tao
747 1585 tao
         pstmt.executeUpdate();
748
         dbConn.commit();
749
         pstmt.close();
750 5014 daigle
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - last_checked updated to "+datestr+" on "
751 2663 sgarg
                                      + server);
752 1585 tao
      }//if
753
      else
754
      {
755 2286 tao
756 5014 daigle
         logReplication.info("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server "  +
757 2286 tao
                                  server + " in db because couldn't get time "
758 2663 sgarg
                                  );
759 1585 tao
         throw new Exception("Couldn't get time for server "+ server);
760
      }
761 2286 tao
762
    }//try
763 1585 tao
    catch(Exception e)
764
    {
765 5014 daigle
      logMetacat.error("ReplicationHandler.updateLastCheckTimeForSingleServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);
766
      logReplication.error("ReplicationHandler.updateLastCheckTimeForSingleServer - Failed to update last_checked for server " +
767
                                server + " in db because because " + e.getMessage());
768
      throw new HandlerException("ReplicationHandler.updateLastCheckTimeForSingleServer - "
769
    		  + "Error updating last checked time: " + e.getMessage());
770 1585 tao
    }
771
    finally
772
    {
773
       //return DBConnection
774
       DBConnectionPool.returnDBConnection(dbConn, serialNumber);
775
    }//finally
776
  }
777 6118 leinfelder
778
  	/**
779
	 * Handle replicate system metadata
780
	 *
781
	 * @param remoteserver
782
	 * @param guid
783
	 * @throws HandlerException
784
	 */
785
	private void handleSystemMetadata(String remoteserver, String guid)
786
		throws HandlerException {
787
		try {
788 2286 tao
789 6118 leinfelder
			// Try get the system metadata from remote server
790
			String sysMetaURLStr = "https://" + remoteserver + "?server="
791
					+ MetacatUtil.getLocalReplicationServerName()
792
					+ "&action=getsystemmetadata&guid=" + guid;
793
			sysMetaURLStr = MetacatUtil.replaceWhiteSpaceForURL(sysMetaURLStr);
794
			URL sysMetaUrl = new URL(sysMetaURLStr);
795
			logReplication.info("ReplicationHandler.handleSystemMetadata - Sending message: "
796
							+ sysMetaUrl.toString());
797
			String systemMetadataXML = ReplicationService.getURLContent(sysMetaUrl);
798 2286 tao
799 6118 leinfelder
			logReplication.info("ReplicationHandler.handleSystemMetadata - guid in repl: " + guid);
800 2286 tao
801 6118 leinfelder
			// process system metadata
802
			if (systemMetadataXML != null) {
803 6367 leinfelder
				SystemMetadata sysMeta = TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class,
804 6118 leinfelder
								new ByteArrayInputStream(systemMetadataXML
805
										.getBytes("UTF-8")));
806 6447 leinfelder
				HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
807 6118 leinfelder
			}
808
809
			logReplication.info("ReplicationHandler.handleSystemMetadata - Successfully replicated system metadata for guid: "
810
							+ guid);
811
812
			String ip = getIpFromURL(sysMetaUrl);
813
			EventLog.getInstance().log(ip, ReplicationService.REPLICATIONUSER, guid, "systemMetadata");
814
815
		} catch (Exception e) {
816
			logMetacat.error("ReplicationHandler.handleSystemMetadata - "
817
					+ ReplicationService.METACAT_REPL_ERROR_MSG);
818
			logReplication
819
					.error("ReplicationHandler.handleSystemMetadata - Failed to write system metadata "
820
							+ guid + " into db because " + e.getMessage());
821
			throw new HandlerException(
822
					"ReplicationHandler.handleSystemMetadata - generic exception "
823
							+ "writing Replication: " + e.getMessage());
824
		}
825
826
	}
827
828 1585 tao
  /**
829
   * updates xml_catalog with entries from other servers.
830
   */
831
  private void updateCatalog()
832
  {
833 5014 daigle
    logReplication.info("ReplicationHandler.updateCatalog - Start of updateCatalog");
834 1585 tao
    // ReplicationServer object in server list
835
    ReplicationServer replServer = null;
836
    PreparedStatement pstmt = null;
837
    String server = null;
838 2286 tao
839
840 1585 tao
    // Go through each ReplicationServer object in sererlist
841
    for (int j=0; j<serverList.size(); j++)
842 2286 tao
    {
843 5014 daigle
      Vector<Vector<String>> remoteCatalog = new Vector<Vector<String>>();
844
      Vector<String> publicId = new Vector<String>();
845 1585 tao
      try
846
      {
847 1292 tao
        // Get ReplicationServer object from server list
848
        replServer = serverList.serverAt(j);
849
        // Get server name from the ReplicationServer object
850
        server = replServer.getServerName();
851
        // Try to get catalog
852 1011 tao
        URL u = new URL("https://" + server + "?server="+
853 4698 daigle
        MetacatUtil.getLocalReplicationServerName()+"&action=getcatalog");
854 5014 daigle
        logReplication.info("ReplicationHandler.updateCatalog - sending message " + u.toString());
855
        String catxml = ReplicationService.getURLContent(u);
856 2286 tao
857 1292 tao
        // Make sure there are not error, no empty string
858
        if (catxml.indexOf("error")!=-1 || catxml==null||catxml.equals(""))
859
        {
860 1585 tao
          throw new Exception("Couldn't get catalog list form server " +server);
861 1292 tao
        }
862 5175 daigle
        logReplication.debug("ReplicationHandler.updateCatalog - catxml: " + catxml);
863 590 berkley
        CatalogMessageHandler cmh = new CatalogMessageHandler();
864
        XMLReader catparser = initParser(cmh);
865
        catparser.parse(new InputSource(new StringReader(catxml)));
866
        //parse the returned catalog xml and put it into a vector
867 1585 tao
        remoteCatalog = cmh.getCatalogVect();
868 2286 tao
869 5175 daigle
        // Make sure remoteCatalog is not empty
870 1292 tao
        if (remoteCatalog.isEmpty())
871
        {
872 1585 tao
          throw new Exception("Couldn't get catalog list form server " +server);
873 1292 tao
        }
874 2286 tao
875 5014 daigle
        String localcatxml = ReplicationService.getCatalogXML();
876 2286 tao
877 1292 tao
        // Make sure local catalog is no empty
878
        if (localcatxml==null||localcatxml.equals(""))
879
        {
880 1585 tao
          throw new Exception("Couldn't get catalog list form server " +server);
881 1292 tao
        }
882 2286 tao
883 590 berkley
        cmh = new CatalogMessageHandler();
884
        catparser = initParser(cmh);
885
        catparser.parse(new InputSource(new StringReader(localcatxml)));
886 5014 daigle
        Vector<Vector<String>> localCatalog = cmh.getCatalogVect();
887 2286 tao
888 590 berkley
        //now we have the catalog from the remote server and this local server
889
        //we now need to compare the two and merge the differences.
890
        //the comparison is base on the public_id fields which is the 4th
891
        //entry in each row vector.
892 5014 daigle
        publicId = new Vector<String>();
893 590 berkley
        for(int i=0; i<localCatalog.size(); i++)
894
        {
895 5014 daigle
          Vector<String> v = new Vector<String>(localCatalog.elementAt(i));
896
          logReplication.info("ReplicationHandler.updateCatalog - v1: " + v.toString());
897 590 berkley
          publicId.add(new String((String)v.elementAt(3)));
898
        }
899 1585 tao
      }//try
900
      catch (Exception e)
901
      {
902 5014 daigle
        logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);
903
        logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
904 1585 tao
                                    server + " because " +e.getMessage());
905
      }//catch
906 2286 tao
907 1585 tao
      for(int i=0; i<remoteCatalog.size(); i++)
908
      {
909
         // DConnection
910
        DBConnection dbConn = null;
911
        // DBConnection checkout serial number
912
        int serialNumber = -1;
913
        try
914 590 berkley
        {
915 1585 tao
            dbConn=DBConnectionPool.
916
                  getDBConnection("ReplicationHandler.updateCatalog");
917
            serialNumber=dbConn.getCheckOutSerialNumber();
918 5014 daigle
            Vector<String> v = remoteCatalog.elementAt(i);
919 6099 leinfelder
            //logMetacat.debug("v2: " + v.toString());
920
            //logMetacat.debug("i: " + i);
921
            //logMetacat.debug("remoteCatalog.size(): " + remoteCatalog.size());
922
            //logMetacat.debug("publicID: " + publicId.toString());
923 5014 daigle
            logReplication.info
924
                              ("ReplicationHandler.updateCatalog - v.elementAt(3): " + (String)v.elementAt(3));
925 1585 tao
           if(!publicId.contains(v.elementAt(3)))
926
           { //so we don't have this public id in our local table so we need to
927
             //add it.
928 6099 leinfelder
             //logMetacat.debug("in if");
929 1585 tao
             StringBuffer sql = new StringBuffer();
930
             sql.append("insert into xml_catalog (entry_type, source_doctype, ");
931
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
932
             sql.append("?,?)");
933 6099 leinfelder
             //logMetacat.debug("sql: " + sql.toString());
934 1585 tao
             pstmt = dbConn.prepareStatement(sql.toString());
935
             pstmt.setString(1, (String)v.elementAt(0));
936
             pstmt.setString(2, (String)v.elementAt(1));
937
             pstmt.setString(3, (String)v.elementAt(2));
938
             pstmt.setString(4, (String)v.elementAt(3));
939
             pstmt.setString(5, (String)v.elementAt(4));
940
             pstmt.execute();
941
             pstmt.close();
942 5014 daigle
             logReplication.info("ReplicationHandler.updateCatalog - Success fully to insert new publicid "+
943 1585 tao
                               (String)v.elementAt(3) + " from server"+server);
944
           }
945 590 berkley
        }
946 1585 tao
        catch(Exception e)
947
        {
948 5014 daigle
           logMetacat.error("ReplicationHandler.updateCatalog - " + ReplicationService.METACAT_REPL_ERROR_MSG);
949
           logReplication.error("ReplicationHandler.updateCatalog - Failed to update catalog for server "+
950 1585 tao
                                    server + " because " +e.getMessage());
951
        }//catch
952
        finally
953
        {
954
           DBConnectionPool.returnDBConnection(dbConn, serialNumber);
955 5175 daigle
        }//finally
956 1585 tao
      }//for remote catalog
957
    }//for server list
958 5014 daigle
    logReplication.info("End of updateCatalog");
959 590 berkley
  }
960 2286 tao
961 590 berkley
  /**
962 579 berkley
   * Method that returns true if docid has already been "deleted" from metacat.
963 582 berkley
   * This method really implements a truth table for deleted documents
964 590 berkley
   * The table is (a docid in one of the tables is represented by the X):
965 582 berkley
   * xml_docs      xml_revs      deleted?
966
   * ------------------------------------
967
   *   X             X             FALSE
968
   *   X             _             FALSE
969
   *   _             X             TRUE
970
   *   _             _             TRUE
971 579 berkley
   */
972 5014 daigle
  private static boolean alreadyDeleted(String docid) throws HandlerException
973 579 berkley
  {
974 1217 tao
    DBConnection dbConn = null;
975
    int serialNumber = -1;
976
    PreparedStatement pstmt = null;
977 579 berkley
    try
978
    {
979 1217 tao
      dbConn=DBConnectionPool.
980
                  getDBConnection("ReplicationHandler.alreadyDeleted");
981
      serialNumber=dbConn.getCheckOutSerialNumber();
982 582 berkley
      boolean xml_docs = false;
983
      boolean xml_revs = false;
984 2286 tao
985 579 berkley
      StringBuffer sb = new StringBuffer();
986 582 berkley
      sb.append("select docid from xml_revisions where docid like '");
987 579 berkley
      sb.append(docid).append("'");
988 1217 tao
      pstmt = dbConn.prepareStatement(sb.toString());
989 579 berkley
      pstmt.execute();
990
      ResultSet rs = pstmt.getResultSet();
991
      boolean tablehasrows = rs.next();
992
      if(tablehasrows)
993
      {
994 582 berkley
        xml_revs = true;
995
      }
996 2286 tao
997 582 berkley
      sb = new StringBuffer();
998
      sb.append("select docid from xml_documents where docid like '");
999
      sb.append(docid).append("'");
1000 667 berkley
      pstmt.close();
1001 1217 tao
      pstmt = dbConn.prepareStatement(sb.toString());
1002
      //increase usage count
1003
      dbConn.increaseUsageCount(1);
1004 582 berkley
      pstmt.execute();
1005
      rs = pstmt.getResultSet();
1006
      tablehasrows = rs.next();
1007 667 berkley
      pstmt.close();
1008 582 berkley
      if(tablehasrows)
1009
      {
1010
        xml_docs = true;
1011
      }
1012 2286 tao
1013 582 berkley
      if(xml_docs && xml_revs)
1014
      {
1015
        return false;
1016
      }
1017
      else if(xml_docs && !xml_revs)
1018
      {
1019
        return false;
1020
      }
1021
      else if(!xml_docs && xml_revs)
1022
      {
1023 579 berkley
        return true;
1024
      }
1025 582 berkley
      else if(!xml_docs && !xml_revs)
1026
      {
1027
        return true;
1028
      }
1029 579 berkley
    }
1030
    catch(Exception e)
1031
    {
1032 5014 daigle
      logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);
1033
      logReplication.error("ReplicationHandler.alreadyDeleted - general error in alreadyDeleted: " +
1034 2663 sgarg
                          e.getMessage());
1035 5014 daigle
      throw new HandlerException("ReplicationHandler.alreadyDeleted - general error: "
1036
    		  + e.getMessage());
1037 579 berkley
    }
1038 667 berkley
    finally
1039
    {
1040 1217 tao
      try
1041
      {
1042
        pstmt.close();
1043
      }//try
1044
      catch (SQLException ee)
1045
      {
1046 5014 daigle
    	logMetacat.error("ReplicationHandler.alreadyDeleted - " + ReplicationService.METACAT_REPL_ERROR_MSG);
1047
        logReplication.error("ReplicationHandler.alreadyDeleted - Error in replicationHandler.alreadyDeleted "+
1048 2663 sgarg
                          "to close pstmt: "+ee.getMessage());
1049 5014 daigle
        throw new HandlerException("ReplicationHandler.alreadyDeleted - SQL error when closing prepared statement: "
1050
      		  + ee.getMessage());
1051 1217 tao
      }//catch
1052
      finally
1053
      {
1054
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1055
      }//finally
1056
    }//finally
1057 579 berkley
    return false;
1058
  }
1059 533 berkley
1060 2286 tao
1061 533 berkley
  /**
1062 574 berkley
   * Method to initialize the message parser
1063
   */
1064
  public static XMLReader initParser(DefaultHandler dh)
1065 5014 daigle
          throws HandlerException
1066 574 berkley
  {
1067
    XMLReader parser = null;
1068
1069
    try {
1070
      ContentHandler chandler = dh;
1071
1072
      // Get an instance of the parser
1073 4213 daigle
      String parserName = PropertyService.getProperty("xml.saxparser");
1074 574 berkley
      parser = XMLReaderFactory.createXMLReader(parserName);
1075
1076
      // Turn off validation
1077
      parser.setFeature("http://xml.org/sax/features/validation", false);
1078 2286 tao
1079 574 berkley
      parser.setContentHandler((ContentHandler)chandler);
1080
      parser.setErrorHandler((ErrorHandler)chandler);
1081
1082 5014 daigle
    } catch (SAXException se) {
1083
      throw new HandlerException("ReplicationHandler.initParser - Sax error when "
1084
    		  + " initializing parser: " + se.getMessage());
1085
    } catch (PropertyNotFoundException pnfe) {
1086
        throw new HandlerException("ReplicationHandler.initParser - Property error when "
1087
      		  + " getting parser name: " + pnfe.getMessage());
1088
    }
1089 574 berkley
1090
    return parser;
1091
  }
1092 2286 tao
1093 2555 tao
  /**
1094 5175 daigle
	 * This method will combine given time string(in short format) to current
1095 5014 daigle
	 * date. If the given time (e.g 10:00 AM) passed the current time (e.g 2:00
1096
	 * PM Aug 21, 2005), then the time will set to second day, 10:00 AM Aug 22,
1097
	 * 2005. If the given time (e.g 10:00 AM) haven't passed the current time
1098
	 * (e.g 8:00 AM Aug 21, 2005) The time will set to be 10:00 AM Aug 21, 2005.
1099
	 *
1100
	 * @param givenTime
1101
	 *            the format should be "10:00 AM " or "2:00 PM"
1102
	 * @return
1103
	 * @throws Exception
1104
	 */
1105
	public static Date combinateCurrentDateAndGivenTime(String givenTime) throws HandlerException
1106 2555 tao
  {
1107 5014 daigle
	  try {
1108 2555 tao
     Date givenDate = parseTime(givenTime);
1109
     Date newDate = null;
1110
     Date now = new Date();
1111
     String currentTimeString = getTimeString(now);
1112
     Date currentTime = parseTime(currentTimeString);
1113
     if ( currentTime.getTime() >= givenDate.getTime())
1114
     {
1115 5014 daigle
        logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today already pass the given time, we should set it as tomorrow");
1116 2555 tao
        String dateAndTime = getDateString(now) + " " + givenTime;
1117
        Date combinationDate = parseDateTime(dateAndTime);
1118
        // new date should plus 24 hours to make is the second day
1119
        newDate = new Date(combinationDate.getTime()+24*3600*1000);
1120
     }
1121
     else
1122
     {
1123 5014 daigle
         logReplication.info("ReplicationHandler.combinateCurrentDateAndGivenTime - Today haven't pass the given time, we should it as today");
1124 2555 tao
         String dateAndTime = getDateString(now) + " " + givenTime;
1125
         newDate = parseDateTime(dateAndTime);
1126
     }
1127 5014 daigle
     logReplication.warn("ReplicationHandler.combinateCurrentDateAndGivenTime - final setting time is "+ newDate.toString());
1128 2555 tao
     return newDate;
1129 5014 daigle
	  } catch (ParseException pe) {
1130
		  throw new HandlerException("ReplicationHandler.combinateCurrentDateAndGivenTime - "
1131
				  + "parsing error: "  + pe.getMessage());
1132
	  }
1133 2555 tao
  }
1134 2286 tao
1135 2555 tao
  /*
1136 5014 daigle
	 * parse a given string to Time in short format. For example, given time is
1137
	 * 10:00 AM, the date will be return as Jan 1 1970, 10:00 AM
1138
	 */
1139
  private static Date parseTime(String timeString) throws ParseException
1140 2555 tao
  {
1141
    DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT);
1142
    Date time = format.parse(timeString);
1143 5014 daigle
    logReplication.info("ReplicationHandler.parseTime - Date string is after parse a time string "
1144 2663 sgarg
                              +time.toString());
1145 2555 tao
    return time;
1146
1147
  }
1148
1149
  /*
1150 5175 daigle
   * Parse a given string to date and time. Date format is long and time
1151 2555 tao
   * format is short.
1152
   */
1153 5014 daigle
  private static Date parseDateTime(String timeString) throws ParseException
1154 2555 tao
  {
1155
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
1156
    Date time = format.parse(timeString);
1157 5014 daigle
    logReplication.info("ReplicationHandler.parseDateTime - Date string is after parse a time string "+
1158 2663 sgarg
                             time.toString());
1159 2555 tao
    return time;
1160
  }
1161
1162
  /*
1163
   * Get a date string from a Date object. The date format will be long
1164
   */
1165
  private static String getDateString(Date now)
1166
  {
1167
     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
1168
     String s = df.format(now);
1169 5014 daigle
     logReplication.info("ReplicationHandler.getDateString - Today is " + s);
1170 2555 tao
     return s;
1171
  }
1172
1173
  /*
1174
   * Get a time string from a Date object, the time format will be short
1175
   */
1176
  private static String getTimeString(Date now)
1177
  {
1178
     DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
1179
     String s = df.format(now);
1180 5014 daigle
     logReplication.info("ReplicationHandler.getTimeString - Time is " + s);
1181 2555 tao
     return s;
1182
  }
1183 2608 tao
1184
1185
  /*
1186 4080 daigle
	 * This method will go through the docid list both in xml_Documents table
1187
	 * and in xml_revisions table @author tao
1188
	 */
1189 5014 daigle
	private void handleDocList(Vector<Vector<String>> docList, String tableName) {
1190 4080 daigle
		boolean dataFile = false;
1191
		for (int j = 0; j < docList.size(); j++) {
1192
			// initial dataFile is false
1193
			dataFile = false;
1194
			// w is information for one document, information contain
1195
			// docid, rev, server or datafile.
1196 5014 daigle
			Vector<String> w = new Vector<String>(docList.elementAt(j));
1197 4080 daigle
			// Check if the vector w contain "datafile"
1198
			// If it has, this document is data file
1199
			try {
1200 4173 daigle
				if (w.contains((String) PropertyService.getProperty("replication.datafileflag"))) {
1201 4080 daigle
					dataFile = true;
1202
				}
1203
			} catch (PropertyNotFoundException pnfe) {
1204 5014 daigle
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);
1205
				logReplication.error("ReplicationHandler.handleDocList - Could not retrieve data file flag property.  "
1206 4080 daigle
						+ "Leaving as false: " + pnfe.getMessage());
1207
			}
1208 6099 leinfelder
			// logMetacat.debug("w: " + w.toString());
1209 4080 daigle
			// Get docid
1210
			String docid = (String) w.elementAt(0);
1211 5014 daigle
			logReplication.info("docid: " + docid);
1212 4080 daigle
			// Get revision number
1213
			int rev = Integer.parseInt((String) w.elementAt(1));
1214 5014 daigle
			logReplication.info("rev: " + rev);
1215 5175 daigle
			// Get remote server name (it is may not be doc home server because
1216 4080 daigle
			// the new hub feature
1217
			String remoteServer = (String) w.elementAt(2);
1218
			remoteServer = remoteServer.trim();
1219 2608 tao
1220 4080 daigle
			try {
1221
				if (tableName.equals(DocumentImpl.DOCUMENTTABLE)) {
1222
					handleDocInXMLDocuments(docid, rev, remoteServer, dataFile);
1223
				} else if (tableName.equals(DocumentImpl.REVISIONTABLE)) {
1224
					handleDocInXMLRevisions(docid, rev, remoteServer, dataFile);
1225
				} else {
1226
					continue;
1227
				}
1228 2608 tao
1229 4861 daigle
			} catch (Exception e) {
1230 5014 daigle
				logMetacat.error("ReplicationHandler.handleDocList - " + ReplicationService.METACAT_REPL_ERROR_MSG);
1231
				logReplication.error("ReplicationHandler.handleDocList - error to handle update doc in " + tableName
1232 4861 daigle
						+ " in time replication" + e.getMessage());
1233 4080 daigle
				continue;
1234
			}
1235 5175 daigle
1236
	        if (_xmlDocQueryCount > 0 && (_xmlDocQueryCount % 100) == 0) {
1237
	        	logMetacat.debug("ReplicationHandler.update - xml_doc query count: " + _xmlDocQueryCount +
1238
	        			", xml_doc avg query time: " + (_xmlDocQueryTime / _xmlDocQueryCount));
1239
	        }
1240
1241
	        if (_xmlRevQueryCount > 0 && (_xmlRevQueryCount % 100) == 0) {
1242
	        	logMetacat.debug("ReplicationHandler.update - xml_rev query count: " + _xmlRevQueryCount +
1243
	        			", xml_rev avg query time: " + (_xmlRevQueryTime / _xmlRevQueryCount));
1244
	        }
1245 4080 daigle
1246
		}// for update docs
1247
1248
	}
1249 2608 tao
1250
   /*
1251 4080 daigle
	 * This method will handle doc in xml_documents table.
1252
	 */
1253 2608 tao
   private void handleDocInXMLDocuments(String docid, int rev, String remoteServer, boolean dataFile)
1254 5014 daigle
                                        throws HandlerException
1255 2608 tao
   {
1256
       // compare the update rev and local rev to see what need happen
1257
       int localrev = -1;
1258
       String action = null;
1259
       boolean flag = false;
1260
       try
1261
       {
1262 5175 daigle
    	 long docQueryStartTime = System.currentTimeMillis();
1263 2641 tao
         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
1264 5175 daigle
         long docQueryEndTime = System.currentTimeMillis();
1265
         _xmlDocQueryTime += (docQueryEndTime - docQueryStartTime);
1266
         _xmlDocQueryCount++;
1267 2608 tao
       }
1268
       catch (SQLException e)
1269
       {
1270 5014 daigle
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);
1271
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1272 2663 sgarg
                                " be found because " + e.getMessage());
1273 5014 daigle
         logReplication.error("ReplicationHandler.handleDocInXMLDocuments - " + DOCERRORNUMBER+"Docid "+ docid + " could not be "+
1274 2608 tao
                 "written because error happend to find it's local revision");
1275 2739 tao
         DOCERRORNUMBER++;
1276 5014 daigle
         throw new HandlerException ("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " could not "+
1277
                 " be found: " + e.getMessage());
1278 2608 tao
       }
1279 5014 daigle
       logReplication.info("ReplicationHandler.handleDocInXMLDocuments - Local rev for docid "+ docid + " is "+
1280 2663 sgarg
                               localrev);
1281 2608 tao
1282
       //check the revs for an update because this document is in the
1283
       //local DB, it might be out of date.
1284
       if (localrev == -1)
1285
       {
1286 2713 tao
          // check if the revision is in the revision table
1287 5014 daigle
    	   Vector<Integer> localRevVector = null;
1288
    	 try {
1289 5175 daigle
        	 long revQueryStartTime = System.currentTimeMillis();
1290 5014 daigle
    		 localRevVector = DBUtil.getRevListFromRevisionTable(docid);
1291 5175 daigle
             long revQueryEndTime = System.currentTimeMillis();
1292
             _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1293
             _xmlRevQueryCount++;
1294 5014 daigle
    	 } catch (SQLException sqle) {
1295
    		 throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - SQL error "
1296
    				 + " when getting rev list for docid: " + docid + " : " + sqle.getMessage());
1297
    	 }
1298 2713 tao
         if (localRevVector != null && localRevVector.contains(new Integer(rev)))
1299
         {
1300
             // this version was deleted, so don't need replicate
1301
             flag = false;
1302
         }
1303
         else
1304
         {
1305
           //insert this document as new because it is not in the local DB
1306
           action = "INSERT";
1307
           flag = true;
1308
         }
1309 2608 tao
       }
1310
       else
1311
       {
1312
         if(localrev == rev)
1313
         {
1314
           // Local meatacat has the same rev to remote host, don't need
1315
           // update and flag set false
1316
           flag = false;
1317
         }
1318
         else if(localrev < rev)
1319
         {
1320
           //this document needs to be updated so send an read request
1321
           action = "UPDATE";
1322
           flag = true;
1323
         }
1324
       }
1325 2641 tao
1326 5014 daigle
       String accNumber = null;
1327
       try {
1328
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1329
       } catch (PropertyNotFoundException pnfe) {
1330
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLDocuments - error getting "
1331
    			   + "account number separator : " + pnfe.getMessage());
1332
       }
1333 2608 tao
       // this is non-data file
1334
       if(flag && !dataFile)
1335
       {
1336
         try
1337
         {
1338 2641 tao
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1339 2608 tao
         }
1340 5014 daigle
         catch(HandlerException he)
1341 2608 tao
         {
1342
           // skip this document
1343 5014 daigle
           throw he;
1344 2608 tao
         }
1345
       }//if for non-data file
1346
1347
        // this is for data file
1348
       if(flag && dataFile)
1349
       {
1350
         try
1351
         {
1352 2641 tao
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
1353 2608 tao
         }
1354 5014 daigle
         catch(HandlerException he)
1355 2608 tao
         {
1356 5175 daigle
           // skip this data file
1357 5014 daigle
           throw he;
1358 2608 tao
         }
1359
1360 5175 daigle
       }//for data file
1361 2608 tao
   }
1362
1363
   /*
1364
    * This method will handle doc in xml_documents table.
1365
    */
1366
   private void handleDocInXMLRevisions(String docid, int rev, String remoteServer, boolean dataFile)
1367 5014 daigle
                                        throws HandlerException
1368 2608 tao
   {
1369
       // compare the update rev and local rev to see what need happen
1370 5014 daigle
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - In handle repliation revsion table");
1371
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - the docid is "+ docid);
1372
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - The rev is "+rev);
1373
       Vector<Integer> localrev = null;
1374 2608 tao
       String action = "INSERT";
1375
       boolean flag = false;
1376
       try
1377
       {
1378 5175 daigle
      	 long revQueryStartTime = System.currentTimeMillis();
1379 2608 tao
         localrev = DBUtil.getRevListFromRevisionTable(docid);
1380 5175 daigle
         long revQueryEndTime = System.currentTimeMillis();
1381
         _xmlRevQueryTime += (revQueryEndTime - revQueryStartTime);
1382
         _xmlRevQueryCount++;
1383 2608 tao
       }
1384 5014 daigle
       catch (SQLException sqle)
1385 2608 tao
       {
1386 5014 daigle
    	 logMetacat.error("ReplicationHandler.handleDocInXMLDocuments - " + ReplicationService.METACAT_REPL_ERROR_MSG);
1387
         logReplication.error("ReplicationHandler.handleDocInXMLRevisions - Local rev for docid "+ docid + " could not "+
1388
                                " be found because " + sqle.getMessage());
1389 2739 tao
         REVERRORNUMBER++;
1390 5014 daigle
         throw new HandlerException ("ReplicationHandler.handleDocInXMLRevisions - SQL exception getting rev list: "
1391
        		 + sqle.getMessage());
1392 2608 tao
       }
1393 5014 daigle
       logReplication.info("ReplicationHandler.handleDocInXMLRevisions - rev list in xml_revision table for docid "+ docid + " is "+
1394 2663 sgarg
                               localrev.toString());
1395 2608 tao
1396
       // if the rev is not in the xml_revision, we need insert it
1397
       if (!localrev.contains(new Integer(rev)))
1398
       {
1399
           flag = true;
1400
       }
1401 2641 tao
1402 5014 daigle
       String accNumber = null;
1403
       try {
1404
    	   accNumber = docid + PropertyService.getProperty("document.accNumSeparator") + rev;
1405
       } catch (PropertyNotFoundException pnfe) {
1406
    	   throw new HandlerException("ReplicationHandler.handleDocInXMLRevisions - error getting "
1407
    			   + "account number separator : " + pnfe.getMessage());
1408
       }
1409 2608 tao
       // this is non-data file
1410
       if(flag && !dataFile)
1411
       {
1412
         try
1413
         {
1414 2641 tao
1415
           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1416 2608 tao
         }
1417 5014 daigle
         catch(HandlerException he)
1418 2608 tao
         {
1419
           // skip this document
1420 5014 daigle
           throw he;
1421 2608 tao
         }
1422
       }//if for non-data file
1423
1424
        // this is for data file
1425
       if(flag && dataFile)
1426
       {
1427
         try
1428
         {
1429 2641 tao
           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
1430 2608 tao
         }
1431 5014 daigle
         catch(HandlerException he)
1432 2608 tao
         {
1433 5175 daigle
           // skip this data file
1434 5014 daigle
           throw he;
1435 2608 tao
         }
1436
1437 5175 daigle
       }//for data file
1438 2608 tao
   }
1439 3234 tao
1440
   /*
1441
    * Return a ip address for given url
1442
    */
1443
   private String getIpFromURL(URL url)
1444
   {
1445
	   String ip = null;
1446
	   try
1447
	   {
1448
	      InetAddress address = InetAddress.getByName(url.getHost());
1449
	      ip = address.getHostAddress();
1450
	   }
1451
	   catch(UnknownHostException e)
1452
	   {
1453 5014 daigle
		   logMetacat.error("ReplicationHandler.getIpFromURL - " + ReplicationService.METACAT_REPL_ERROR_MSG);
1454
		   logReplication.error("ReplicationHandler.getIpFromURL - Error in get ip address for host: "
1455 3234 tao
                   +e.getMessage());
1456
	   }
1457
1458
	   return ip;
1459
   }
1460 2608 tao
1461 522 berkley
}