Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements replication for metacat
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: berkley $'
9
 *     '$Date: 2010-07-28 10:00:54 -0700 (Wed, 28 Jul 2010) $'
10
 * '$Revision: 5459 $'
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.util.*;
30
import java.util.Date;
31
import java.io.*;
32
import java.sql.*;
33
import java.net.*;
34
import java.text.*;
35

    
36
import javax.servlet.http.*;
37

    
38
import edu.ucsb.nceas.metacat.DocInfoHandler;
39
import edu.ucsb.nceas.metacat.DocumentImpl;
40
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
41
import edu.ucsb.nceas.metacat.EventLog;
42
import edu.ucsb.nceas.metacat.McdbException;
43
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlException;
44
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
45
import edu.ucsb.nceas.metacat.accesscontrol.PermOrderException;
46
import edu.ucsb.nceas.metacat.accesscontrol.XMLAccessDAO;
47
import edu.ucsb.nceas.metacat.database.DBConnection;
48
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
49
import edu.ucsb.nceas.metacat.database.DatabaseService;
50
import edu.ucsb.nceas.metacat.properties.PropertyService;
51
import edu.ucsb.nceas.metacat.shared.BaseService;
52
import edu.ucsb.nceas.metacat.shared.HandlerException;
53
import edu.ucsb.nceas.metacat.shared.ServiceException;
54
import edu.ucsb.nceas.metacat.util.DocumentUtil;
55
import edu.ucsb.nceas.metacat.util.MetacatUtil;
56
import edu.ucsb.nceas.metacat.util.SystemUtil;
57
import edu.ucsb.nceas.metacat.IdentifierManager;
58
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
59
import edu.ucsb.nceas.utilities.FileUtil;
60
import edu.ucsb.nceas.utilities.GeneralPropertyException;
61
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
62

    
63
import org.apache.log4j.Logger;
64
import org.xml.sax.*;
65

    
66
public class ReplicationService extends BaseService {
67

    
68
	private static ReplicationService replicationService = null;
69

    
70
	private long timeInterval;
71
	private Date firstTime;
72
	private boolean timedReplicationIsOn = false;
73
	Timer replicationDaemon;
74
	private static Vector<String> fileLocks = new Vector<String>();
75
//	private Thread lockThread = null;
76
	public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
77
	private static String TIMEREPLICATION = "replication.timedreplication";
78
	private static String TIMEREPLICATIONINTERVAl ="replication.timedreplicationinterval";
79
	private static String FIRSTTIME = "replication.firsttimedreplication";
80
	private static final int TIMEINTERVALLIMIT = 7200000;
81
	public static final String REPLICATIONUSER = "replication";
82

    
83
	public static final String REPLICATION_LOG_FILE_NAME = "metacatreplication.log";
84
	public static String METACAT_REPL_ERROR_MSG = null;
85
	private static Logger logReplication = Logger.getLogger("ReplicationLogging");
86
	private static Logger logMetacat = Logger.getLogger(ReplicationService.class);
87

    
88
	private ReplicationService() throws ServiceException {
89
		_serviceName = "ReplicationService";
90
		
91
		initialize();
92
	}
93
	
94
	private void initialize() throws ServiceException {
95
				
96
		// initialize db connections to handle any update requests
97
		// deltaT = util.getProperty("replication.deltaT");
98
		// the default deltaT can be set from metacat.properties
99
		// create a thread to do the delta-T check but don't execute it yet
100
		replicationDaemon = new Timer(true);
101
		try {
102
			String replLogFile = PropertyService.getProperty("replication.logdir")
103
				+ FileUtil.getFS() + REPLICATION_LOG_FILE_NAME;
104
			METACAT_REPL_ERROR_MSG = "An error occurred in replication.  Please see the " +
105
				"replication log at: " + replLogFile;
106
			
107
			String timedRepIsOnStr = 
108
				PropertyService.getProperty("replication.timedreplication");
109
			timedReplicationIsOn = (new Boolean(timedRepIsOnStr)).booleanValue();
110
			logReplication.info("ReplicationService.initialize - The timed replication on is" + timedReplicationIsOn);
111

    
112
			String timeIntervalStr = 
113
				PropertyService.getProperty("replication.timedreplicationinterval");
114
			timeInterval = (new Long(timeIntervalStr)).longValue();
115
			logReplication.info("ReplicationService.initialize - The timed replication time Interval is " + timeInterval);
116

    
117
			String firstTimeStr = 
118
				PropertyService.getProperty("replication.firsttimedreplication");
119
			logReplication.info("ReplicationService.initialize - first replication time form property is " + firstTimeStr);
120
			firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
121

    
122
			logReplication.info("ReplicationService.initialize - After combine current time, the real first time is "
123
					+ firstTime.toString() + " minisec");
124

    
125
			// set up time replication if it is on
126
			if (timedReplicationIsOn) {
127
				replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(),
128
						firstTime, timeInterval);
129
				logReplication.info("ReplicationService.initialize - deltaT handler started with rate="
130
						+ timeInterval + " mini seconds at " + firstTime.toString());
131
			}
132

    
133
		} catch (PropertyNotFoundException pnfe) {
134
			throw new ServiceException(
135
					"ReplicationService.initialize - Property error while instantiating "
136
							+ "replication service: " + pnfe.getMessage());
137
		} catch (HandlerException he) {
138
			throw new ServiceException(
139
					"ReplicationService.initialize - Handler error while instantiating "
140
							+ "replication service" + he.getMessage());
141
		} 
142
	}
143

    
144
	/**
145
	 * Get the single instance of SessionService.
146
	 * 
147
	 * @return the single instance of SessionService
148
	 */
149
	public static ReplicationService getInstance() throws ServiceException {
150
		if (replicationService == null) {
151
			replicationService = new ReplicationService();
152
		}
153
		return replicationService;
154
	}
155

    
156
	public boolean refreshable() {
157
		return true;
158
	}
159

    
160
	protected void doRefresh() throws ServiceException {
161
		return;
162
	}
163
	
164
	public void stop() throws ServiceException{
165
		
166
	}
167

    
168
	public void stopReplication() throws ServiceException {
169
	      //stop the replication server
170
	      replicationDaemon.cancel();
171
	      replicationDaemon = new Timer(true);
172
	      timedReplicationIsOn = false;
173
	      try {
174
	    	  PropertyService.setProperty("replication.timedreplication", (new Boolean(timedReplicationIsOn)).toString());
175
	      } catch (GeneralPropertyException gpe) {
176
	    	  logReplication.warn("ReplicationService.stopReplication - Could not set replication.timedreplication property: " + gpe.getMessage());
177
	      }
178

    
179
	      logReplication.info("ReplicationService.stopReplication - deltaT handler stopped");
180
		return;
181
	}
182
	
183
	protected void startReplication(Hashtable<String, String[]> params) throws ServiceException {
184

    
185
	       String firstTimeStr = "";
186
	      //start the replication server
187
	       if ( params.containsKey("rate") ) {
188
	        timeInterval = new Long(
189
	               new String(((String[])params.get("rate"))[0])).longValue();
190
	        if(timeInterval < TIMEINTERVALLIMIT) {
191
	            //deltaT<30 is a timing mess!
192
	            timeInterval = TIMEINTERVALLIMIT;
193
	            throw new ServiceException("Replication deltaT rate cannot be less than "+
194
	                    TIMEINTERVALLIMIT + " millisecs and system automatically setup the rate to "+TIMEINTERVALLIMIT);
195
	        }
196
	      } else {
197
	        timeInterval = TIMEINTERVALLIMIT ;
198
	      }
199
	      logReplication.info("ReplicationService.startReplication - New rate is: " + timeInterval + " mini seconds.");
200
	      if ( params.containsKey("firsttime"))
201
	      {
202
	         firstTimeStr = ((String[])params.get("firsttime"))[0];
203
	         try
204
	         {
205
	           firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
206
	           logReplication.info("ReplicationService.startReplication - The first time setting is "+firstTime.toString());
207
	         }
208
	         catch (HandlerException e)
209
	         {
210
	            throw new ServiceException(e.getMessage());
211
	         }
212
	         logReplication.warn("After combine current time, the real first time is "
213
	                                  +firstTime.toString()+" minisec");
214
	      }
215
	      else
216
	      {
217
	    	  logMetacat.error("ReplicationService.startReplication - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
218
	          logReplication.error("ReplicationService.startReplication - You should specify the first time " +
219
	                                  "to start a time replication");
220
	          return;
221
	      }
222
	      
223
	      timedReplicationIsOn = true;
224
	      try {
225
	      // save settings to property file
226
	      PropertyService.setProperty(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
227
	      // note we couldn't use firstTime object because it has date info
228
	      // we only need time info such as 10:00 PM
229
	      PropertyService.setProperty(FIRSTTIME, firstTimeStr);
230
	      PropertyService.setProperty(TIMEREPLICATIONINTERVAl, (new Long(timeInterval)).toString());
231
	      } catch (GeneralPropertyException gpe) {
232
	    	  logReplication.warn("ReplicationService.startReplication - Could not set property: " + gpe.getMessage());
233
	      }
234
	      replicationDaemon.cancel();
235
	      replicationDaemon = new Timer(true);
236
	      replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime,
237
	                                            timeInterval);
238
	      
239
	      logReplication.info("ReplicationService.startReplication - deltaT handler started with rate=" +
240
	                                    timeInterval + " milliseconds at " +firstTime.toString());
241

    
242
	}
243
	
244
	public void runOnce() throws ServiceException {
245
	      //updates this server exactly once
246
	      replicationDaemon.schedule(new ReplicationHandler(), 0);
247
	}
248

    
249
	/**
250
	 * This method can add, delete and list the servers currently included in
251
	 * xml_replication.
252
	 * action           subaction            other needed params
253
	 * ---------------------------------------------------------
254
	 * servercontrol    add                  server
255
	 * servercontrol    delete               server
256
	 * servercontrol    list
257
	 */
258
	protected static void handleServerControlRequest(PrintWriter out,
259
			Hashtable<String, String[]> params, HttpServletResponse response) {
260
		String subaction = ((String[]) params.get("subaction"))[0];
261
		DBConnection dbConn = null;
262
		int serialNumber = -1;
263
		PreparedStatement pstmt = null;
264
		String replicate = null;
265
		String server = null;
266
		String dataReplicate = null;
267
		String hub = null;
268
		try {
269
			//conn = util.openDBConnection();
270
			dbConn = DBConnectionPool
271
					.getDBConnection("MetacatReplication.handleServerControlRequest");
272
			serialNumber = dbConn.getCheckOutSerialNumber();
273

    
274
			// add server to server list
275
			if (subaction.equals("add")) {
276
				replicate = ((String[]) params.get("replicate"))[0];
277
				server = ((String[]) params.get("server"))[0];
278

    
279
				//Get data replication value
280
				dataReplicate = ((String[]) params.get("datareplicate"))[0];
281
				//Get hub value
282
				hub = ((String[]) params.get("hub"))[0];
283

    
284
				String toDateSql = DatabaseService.getInstance().getDBAdapter().toDate("01/01/1980","MM/DD/YYYY");
285
				String sql = "INSERT INTO xml_replication "
286
						+ "(server, last_checked, replicate, datareplicate, hub) "
287
						+ "VALUES (?," + toDateSql + ",?,?,?)";
288
				
289
				pstmt = dbConn.prepareStatement(sql);
290
						
291
				pstmt.setString(1, server);
292
				pstmt.setInt(2, Integer.parseInt(replicate));
293
				pstmt.setInt(3, Integer.parseInt(dataReplicate));
294
				pstmt.setInt(4, Integer.parseInt(hub));
295
				
296
				String sqlReport = "XMLAccessAccess.getXMLAccessForDoc - SQL: " + sql;
297
				sqlReport += " [" + server + "," + replicate + 
298
					"," + dataReplicate + "," + hub + "]";
299
				
300
				logMetacat.info(sqlReport);
301
				
302
				pstmt.execute();
303
				pstmt.close();
304
				dbConn.commit();
305
				out.println("Server " + server + " added");
306
				response.setContentType("text/html");
307
				out.println("<html><body><table border=\"1\">");
308
				out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
309
				out.println("<b>replicate</b></td>");
310
				out.println("<td><b>datareplicate</b></td>");
311
				out.println("<td><b>hub</b></td></tr>");
312
				pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
313
				//increase dbconnection usage
314
				dbConn.increaseUsageCount(1);
315

    
316
				pstmt.execute();
317
				ResultSet rs = pstmt.getResultSet();
318
				boolean tablehasrows = rs.next();
319
				while (tablehasrows) {
320
					out.println("<tr><td>" + rs.getString(2) + "</td><td>");
321
					out.println(rs.getString(3) + "</td><td>");
322
					out.println(rs.getString(4) + "</td><td>");
323
					out.println(rs.getString(5) + "</td><td>");
324
					out.println(rs.getString(6) + "</td></tr>");
325

    
326
					tablehasrows = rs.next();
327
				}
328
				out.println("</table></body></html>");
329

    
330
				// download certificate with the public key on this server
331
				// and import it as a trusted certificate
332
				String certURL = ((String[]) params.get("certificate"))[0];
333
				if (certURL != null && !certURL.equals("")) {
334
					downloadCertificate(certURL);
335
				}
336

    
337
				// delete server from server list
338
			} else if (subaction.equals("delete")) {
339
				server = ((String[]) params.get("server"))[0];
340
				pstmt = dbConn.prepareStatement("DELETE FROM xml_replication "
341
						+ "WHERE server LIKE '" + server + "'");
342
				pstmt.execute();
343
				pstmt.close();
344
				dbConn.commit();
345
				out.println("Server " + server + " deleted");
346
				response.setContentType("text/html");
347
				out.println("<html><body><table border=\"1\">");
348
				out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
349
				out.println("<b>replicate</b></td>");
350
				out.println("<td><b>datareplicate</b></td>");
351
				out.println("<td><b>hub</b></td></tr>");
352

    
353
				pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
354
				//increase dbconnection usage
355
				dbConn.increaseUsageCount(1);
356
				pstmt.execute();
357
				ResultSet rs = pstmt.getResultSet();
358
				boolean tablehasrows = rs.next();
359
				while (tablehasrows) {
360
					out.println("<tr><td>" + rs.getString(2) + "</td><td>");
361
					out.println(rs.getString(3) + "</td><td>");
362
					out.println(rs.getString(4) + "</td><td>");
363
					out.println(rs.getString(5) + "</td><td>");
364
					out.println(rs.getString(6) + "</td></tr>");
365
					tablehasrows = rs.next();
366
				}
367
				out.println("</table></body></html>");
368

    
369
				// list servers in server list
370
			} else if (subaction.equals("list")) {
371
				response.setContentType("text/html");
372
				out.println("<html><body><table border=\"1\">");
373
				out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
374
				out.println("<b>replicate</b></td>");
375
				out.println("<td><b>datareplicate</b></td>");
376
				out.println("<td><b>hub</b></td></tr>");
377
				pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
378
				pstmt.execute();
379
				ResultSet rs = pstmt.getResultSet();
380
				boolean tablehasrows = rs.next();
381
				while (tablehasrows) {
382
					out.println("<tr><td>" + rs.getString(2) + "</td><td>");
383
					out.println(rs.getString(3) + "</td><td>");
384
					out.println(rs.getString(4) + "</td><td>");
385
					out.println(rs.getString(5) + "</td><td>");
386
					out.println(rs.getString(6) + "</td></tr>");
387
					tablehasrows = rs.next();
388
				}
389
				out.println("</table></body></html>");
390
			} else {
391

    
392
				out.println("<error>Unkonwn subaction</error>");
393

    
394
			}
395
			pstmt.close();
396
			//conn.close();
397

    
398
		} catch (Exception e) {
399
			logMetacat.error("ReplicationService.handleServerControlRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
400
			logReplication.error("ReplicationService.handleServerControlRequest - Error in "
401
					+ "MetacatReplication.handleServerControlRequest " + e.getMessage());
402
			e.printStackTrace(System.out);
403
		} finally {
404
			try {
405
				pstmt.close();
406
			}//try
407
			catch (SQLException ee) {
408
				logMetacat.error("ReplicationService.handleServerControlRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
409
				logReplication.error("ReplicationService.handleServerControlRequest - Error in MetacatReplication.handleServerControlRequest to close pstmt "
410
						+ ee.getMessage());
411
			}//catch
412
			finally {
413
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
414
			}//finally
415
		}//finally
416

    
417
	}
418

    
419
	// download certificate with the public key from certURL and
420
	// upload it onto this server; it then must be imported as a
421
	// trusted certificate
422
	private static void downloadCertificate(String certURL) throws FileNotFoundException,
423
			IOException, MalformedURLException, PropertyNotFoundException {
424

    
425
		// the path to be uploaded to
426
		String certPath = SystemUtil.getContextDir();
427

    
428
		// get filename from the URL of the certificate
429
		String filename = certURL;
430
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
431
		if (slash > -1) {
432
			filename = filename.substring(slash + 1);
433
		}
434

    
435
		// open file output strem to write the input into it
436
		File f = new File(certPath, filename);
437
		synchronized (f) {
438
			try {
439
				if (f.exists()) {
440
					throw new IOException("File already exist: " + f.getCanonicalFile());
441
					// if ( f.exists() && !f.canWrite() ) {
442
					// throw new IOException("Not writable: " +
443
					// f.getCanonicalFile());
444
				}
445
			} catch (SecurityException se) {
446
				// if a security manager exists,
447
				// its checkRead method is called for f.exist()
448
				// or checkWrite method is called for f.canWrite()
449
				throw se;
450
			}
451

    
452
			// create a buffered byte output stream
453
			// that uses a default-sized output buffer
454
			FileOutputStream fos = new FileOutputStream(f);
455
			BufferedOutputStream out = new BufferedOutputStream(fos);
456

    
457
			// this should be http url
458
			URL url = new URL(certURL);
459
			BufferedInputStream bis = null;
460
			try {
461
				bis = new BufferedInputStream(url.openStream());
462
				byte[] buf = new byte[4 * 1024]; // 4K buffer
463
				int b = bis.read(buf);
464
				while (b != -1) {
465
					out.write(buf, 0, b);
466
					b = bis.read(buf);
467
				}
468
			} finally {
469
				if (bis != null)
470
					bis.close();
471
			}
472
			// the input and the output streams must be closed
473
			bis.close();
474
			out.flush();
475
			out.close();
476
			fos.close();
477
		} // end of synchronized(f)
478
	}
479

    
480
	/**
481
	 * when a forcereplication request comes in, local host sends a read request
482
	 * to the requesting server (remote server) for the specified docid. Then
483
	 * store it in local database.
484
	 */
485
	protected static void handleForceReplicateRequest(PrintWriter out,
486
			Hashtable<String, String[]> params, HttpServletResponse response,
487
			HttpServletRequest request) {
488
		String server = ((String[]) params.get("server"))[0]; // the server that
489
		String docid = ((String[]) params.get("docid"))[0]; // sent the document
490
		String dbaction = "UPDATE"; // the default action is UPDATE
491
		//    boolean override = false;
492
		//    int serverCode = 1;
493
		DBConnection dbConn = null;
494
		int serialNumber = -1;
495
		String docName = null;
496

    
497
		try {
498
			//if the url contains a dbaction then the default action is overridden
499
			if (params.containsKey("dbaction")) {
500
				dbaction = ((String[]) params.get("dbaction"))[0];
501
				//serverCode = MetacatReplication.getServerCode(server);
502
				//override = true; //we are now overriding the default action
503
			}
504
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication request from: " + server);
505
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication docid: " + docid);
506
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication action: " + dbaction);
507
			// sending back read request to remote server
508
			URL u = new URL("https://" + server + "?server="
509
					+ MetacatUtil.getLocalReplicationServerName() + "&action=read&docid="
510
					+ docid);
511
			String xmldoc = ReplicationService.getURLContent(u);
512

    
513
			// get the document info from server
514
			URL docinfourl = new URL("https://" + server + "?server="
515
					+ MetacatUtil.getLocalReplicationServerName()
516
					+ "&action=getdocumentinfo&docid=" + docid);
517
			
518

    
519
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
520

    
521
			//dih is the parser for the docinfo xml format
522
			DocInfoHandler dih = new DocInfoHandler();
523
			XMLReader docinfoParser = ReplicationHandler.initParser(dih);
524
			docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
525
			//      Hashtable<String,Vector<AccessControlForSingleFile>> docinfoHash = dih.getDocInfo();
526
			Hashtable<String, String> docinfoHash = dih.getDocInfo();
527

    
528
			// Get user owner of this docid
529
			String user = (String) docinfoHash.get("user_owner");
530
			// Get home server of this docid
531
			String homeServer = (String) docinfoHash.get("home_server");
532
			String guid = (String) docinfoHash.get("guid");
533
			logReplication.info("XXXXXXXXXXXXXXXX GUID found in dociinfoHash: " + guid);
534
			
535
			logReplication.info("Processing guid " + guid + 
536
			  " information from handleForceReplicationRequest: " + 
537
			  docinfoHash.toString());
538
      IdentifierManager idman = IdentifierManager.getInstance();
539
      if(guid != null)
540
      { //if the guid was passed in, put it in the identifiers table
541
        logReplication.info("YYYYYYYYYYYYYY Creating guid/docid mapping for docid " + 
542
          docinfoHash.get("docid") + " and guid: " + guid);
543
        
544
        docName = (String) docinfoHash.get("docname");
545
        logReplication.info("ZZZZZZZZZZZZ docName: " + docName);
546
        if(docName.trim().equals("systemMetadata"))
547
        {
548
            logReplication.info("creating mapping for systemMetadata: guid: " + guid + " localId: " + docinfoHash.get("docid"));
549
            idman.createSystemMetadataMapping(guid, docinfoHash.get("docid"));
550
        }
551
        else
552
        {
553
            logReplication.info("creating mapping: guid: " + guid + " localId: " + docinfoHash.get("docid"));
554
            idman.createMapping(guid, docinfoHash.get("docid"));
555
        }
556
      }
557
      else
558
      {
559
        logReplication.debug("No guid information was included with the replicated document");
560
      }
561
      
562
			String createdDate = (String) docinfoHash.get("date_created");
563
			String updatedDate = (String) docinfoHash.get("date_updated");
564
			logReplication.info("ReplicationService.handleForceReplicateRequest - homeServer: " + homeServer);
565
			// Get Document type
566
			String docType = (String) docinfoHash.get("doctype");
567
			logReplication.info("ReplicationService.handleForceReplicateRequest - docType: " + docType);
568
			String parserBase = null;
569
			// this for eml2 and we need user eml2 parser
570
			if (docType != null
571
					&& (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE)) {
572
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml200 document!");
573
				parserBase = DocumentImpl.EML200;
574
			} else if (docType != null
575
					&& (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE)) {
576
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml2.0.1 document!");
577
				parserBase = DocumentImpl.EML200;
578
			} else if (docType != null
579
					&& (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE)) {
580
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml2.1.0 document!");
581
				parserBase = DocumentImpl.EML210;
582
			}
583
			logReplication.warn("ReplicationService.handleForceReplicateRequest - The parserBase is: " + parserBase);
584

    
585
			// Get DBConnection from pool
586
			dbConn = DBConnectionPool
587
					.getDBConnection("MetacatReplication.handleForceReplicateRequest");
588
			serialNumber = dbConn.getCheckOutSerialNumber();
589
			// write the document to local database
590
			DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
591
			//try this independently so we can set
592
//			Exception writeException = null;
593
			try {
594
				wrapper.writeReplication(dbConn, xmldoc, null, null,
595
						dbaction, docid, user, null, homeServer, server, createdDate,
596
						updatedDate);
597
			} finally {
598
//				writeException = e;
599

    
600
				//process extra access rules before dealing with the write exception (doc exist already)			
601
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
602
		        if (accessControlList != null) {
603
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
604
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
605
		        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
606
		        			acfsf.insertPermissions(xmlAccessDAO);
607
							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
608
									+ " permissions added to DB");
609
		        		}
610
		            }
611
		        }
612
//				if (accessControlList != null) {
613
//					for (int i = 0; i < accessControlList.size(); i++) {
614
//						AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList
615
//								.get(i);
616
//						if (!acfsf.accessControlExists()) {
617
//							acfsf.insertPermissions();
618
//							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
619
//									+ " permissions added to DB");
620
//						}
621
//					}
622
//				}
623

    
624
//				if (writeException != null) {
625
//					throw writeException;
626
//				}
627

    
628
				logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid + " added to DB with "
629
						+ "action " + dbaction);
630
				
631
				if(guid != null)
632
                {
633
                    if(!docName.trim().equals("systemMetadata"))
634
                    {
635
                        logReplication.info("replicate D1GUID:" + guid + ":D1SCIMETADATA:" + 
636
                                docid + ":");
637
                    }
638
                    else
639
                    {
640
                        logReplication.info("replicate D1GUID:" + guid + ":D1SYSMETADATA:" + 
641
                                docid + ":");
642
                    }
643
                }
644
				EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid,
645
						dbaction);
646
			}
647
		} catch (SQLException sqle) {
648
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
649
			logReplication.error("ReplicationService.handleForceReplicateRequest - SQL error when adding doc " + docid + 
650
					" to DB with action " + dbaction + ": " + sqle.getMessage());
651
		} catch (MalformedURLException mue) {
652
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
653
			logReplication.error("ReplicationService.handleForceReplicateRequest - URL error when adding doc " + docid + 
654
					" to DB with action " + dbaction + ": " + mue.getMessage());
655
		} catch (SAXException se) {
656
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
657
			logReplication.error("ReplicationService.handleForceReplicateRequest - SAX parsing error when adding doc " + docid + 
658
					" to DB with action " + dbaction + ": " + se.getMessage());
659
		} catch (HandlerException he) {
660
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
661
			logReplication.error("ReplicationService.handleForceReplicateRequest - Handler error when adding doc " + docid + 
662
					" to DB with action " + dbaction + ": " + he.getMessage());
663
		} catch (IOException ioe) {
664
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
665
			logReplication.error("ReplicationService.handleForceReplicateRequest - I/O error when adding doc " + docid + 
666
					" to DB with action " + dbaction + ": " + ioe.getMessage());
667
		} catch (PermOrderException poe) {
668
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
669
			logReplication.error("ReplicationService.handleForceReplicateRequest - Permissions order error when adding doc " + docid + 
670
					" to DB with action " + dbaction + ": " + poe.getMessage());
671
		} catch (AccessControlException ace) {
672
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
673
			logReplication.error("ReplicationService.handleForceReplicateRequest - Permissions order error when adding doc " + docid + 
674
					" to DB with action " + dbaction + ": " + ace.getMessage());
675
		} catch (Exception e) {
676
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
677
			logReplication.error("ReplicationService.handleForceReplicateRequest - General error when adding doc " + docid + 
678
					" to DB with action " + dbaction + ": " + e.getMessage());
679
		} finally {
680
			// Return the checked out DBConnection
681
			DBConnectionPool.returnDBConnection(dbConn, serialNumber);
682
		}//finally
683
	}
684

    
685
	/*
686
	 * when a forcereplication delete request comes in, local host will delete this
687
	 * document
688
	 */
689
	protected static void handleForceReplicateDeleteRequest(PrintWriter out,
690
			Hashtable<String, String[]> params, HttpServletResponse response,
691
			HttpServletRequest request) {
692
		String server = ((String[]) params.get("server"))[0]; // the server that
693
		String docid = ((String[]) params.get("docid"))[0]; // sent the document
694
		try {
695
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete request from " + server);
696
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete docid " + docid);
697
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete request from: " + server);
698
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete docid: " + docid);
699
			DocumentImpl.delete(docid, null, null, server);
700
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
701
			EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid,
702
					"delete");
703
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
704
		} catch (Exception e) {
705
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
706
			logReplication.error("document " + docid
707
					+ " failed to delete because " + e.getMessage());
708
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
709

    
710
		}//catch
711

    
712
	}
713

    
714
	/**
715
	 * when a forcereplication data file request comes in, local host sends a
716
	 * readdata request to the requesting server (remote server) for the specified
717
	 * docid. Then store it in local database and file system
718
	 */
719
	protected static void handleForceReplicateDataFileRequest(Hashtable<String, String[]> params,
720
			HttpServletRequest request) {
721

    
722
		//make sure there is some parameters
723
		if (params.isEmpty()) {
724
			return;
725
		}
726
		// Get remote server
727
		String server = ((String[]) params.get("server"))[0];
728
		// the docid should include rev number
729
		String docid = ((String[]) params.get("docid"))[0];
730
		// Make sure there is a docid and server
731
		if (docid == null || server == null || server.equals("")) {
732
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
733
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Didn't specify docid or server for replication");
734
			return;
735
		}
736

    
737
		// Overide or not
738
		//    boolean override = false;
739
		// dbaction - update or insert
740
		String dbaction = null;
741

    
742
		try {
743
			//docid was switch to two parts uinque code and rev
744
			//String uniqueCode=MetacatUtil.getDocIdFromString(docid);
745
			//int rev=MetacatUtil.getVersionFromString(docid);
746
			if (params.containsKey("dbaction")) {
747
				dbaction = ((String[]) params.get("dbaction"))[0];
748
			} else//default value is update
749
			{
750
				dbaction = "update";
751
			}
752

    
753
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - force replication request from " + server);
754
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication request from: " + server);
755
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication docid: " + docid);
756
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication action: " + dbaction);
757
			// get the document info from server
758
			URL docinfourl = new URL("https://" + server + "?server="
759
					+ MetacatUtil.getLocalReplicationServerName()
760
					+ "&action=getdocumentinfo&docid=" + docid);
761

    
762
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
763

    
764
			//dih is the parser for the docinfo xml format
765
			DocInfoHandler dih = new DocInfoHandler();
766
			XMLReader docinfoParser = ReplicationHandler.initParser(dih);
767
			docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
768
			Hashtable<String, String> docinfoHash = dih.getDocInfo();
769
			String user = (String) docinfoHash.get("user_owner");
770

    
771
			String docName = (String) docinfoHash.get("docname");
772

    
773
			String docType = (String) docinfoHash.get("doctype");
774

    
775
			String docHomeServer = (String) docinfoHash.get("home_server");
776

    
777
			String createdDate = (String) docinfoHash.get("date_created");
778

    
779
			String updatedDate = (String) docinfoHash.get("date_updated");
780
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - docHomeServer of datafile: " + docHomeServer);
781

    
782
			//if action is delete, we don't delete the data file. Just archieve
783
			//the xml_documents
784
			/*if (dbaction.equals("delete"))
785
			{
786
			  //conn = util.getConnection();
787
			  DocumentImpl.delete(docid,user,null);
788
			  //util.returnConnection(conn);
789
			}*/
790
			//To data file insert or update is same
791
			if (dbaction.equals("insert") || dbaction.equals("update")) {
792
				//Get data file and store it into local file system.
793
				// sending back readdata request to server
794
				URL url = new URL("https://" + server + "?server="
795
						+ MetacatUtil.getLocalReplicationServerName()
796
						+ "&action=readdata&docid=" + docid);
797
				String datafilePath = PropertyService
798
						.getProperty("application.datafilepath");
799

    
800
				Exception writeException = null;
801
				//register data file into xml_documents table and wite data file
802
				//into file system
803
				try {
804
					DocumentImpl.writeDataFileInReplication(url.openStream(),
805
							datafilePath, docName, docType, docid, user, docHomeServer,
806
							server, DocumentImpl.DOCUMENTTABLE, false, createdDate,
807
							updatedDate);
808
				} catch (Exception e) {
809
					writeException = e;
810
				}
811
				//process extra access rules
812
//				Vector<AccessControlForSingleFile> accessControlList = dih
813
//						.getAccessControlList();
814
//				if (accessControlList != null) {
815
//					for (int i = 0; i < accessControlList.size(); i++) {
816
//						AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList
817
//								.get(i);
818
//						if (!acfsf.accessControlExists()) {
819
//							acfsf.insertPermissions();
820
//							logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - datafile " + docid
821
//									+ " permissions added to DB");
822
//						}
823
//					}
824
//				}
825
				
826
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
827
		        if (accessControlList != null) {
828
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
829
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
830
		        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
831
		        			acfsf.insertPermissions(xmlAccessDAO);
832
							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
833
									+ " permissions added to DB");
834
		        		}
835
		            }
836
		        }
837

    
838
				if (writeException != null) {
839
					throw writeException;
840
				}
841

    
842
				//false means non-timed replication
843
				logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - datafile " + docid + " added to DB with "
844
						+ "action " + dbaction);
845
				EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER,
846
						docid, dbaction);
847
			}
848

    
849
		} catch (Exception e) {
850
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
851
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Datafile " + docid
852
					+ " failed to added to DB with " + "action " + dbaction + " because "
853
					+ e.getMessage());
854
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - ERROR in MetacatReplication.handleForceDataFileReplicate"
855
					+ "Request(): " + e.getMessage());
856
		}
857
	}
858

    
859
	/**
860
	 * Grants or denies a lock to a requesting host.
861
	 * The servlet parameters of interrest are:
862
	 * docid: the docid of the file the lock is being requested for
863
	 * currentdate: the timestamp of the document on the remote server
864
	 *
865
	 */
866
	protected static void handleGetLockRequest(PrintWriter out,
867
			Hashtable<String, String[]> params, HttpServletResponse response) {
868

    
869
		try {
870

    
871
			String docid = ((String[]) params.get("docid"))[0];
872
			String remoteRev = ((String[]) params.get("updaterev"))[0];
873
			DocumentImpl requestDoc = new DocumentImpl(docid);
874
			logReplication.info("ReplicationService.handleGetLockRequest - lock request for " + docid);
875
			int localRevInt = requestDoc.getRev();
876
			int remoteRevInt = Integer.parseInt(remoteRev);
877

    
878
			if (remoteRevInt >= localRevInt) {
879
				if (!fileLocks.contains(docid)) { //grant the lock if it is not already locked
880
					fileLocks.add(0, docid); //insert at the beginning of the queue Vector
881
					//send a message back to the the remote host authorizing the insert
882
					out
883
							.println("<lockgranted><docid>" + docid
884
									+ "</docid></lockgranted>");
885
					//          lockThread = new Thread(this);
886
					//          lockThread.setPriority(Thread.MIN_PRIORITY);
887
					//          lockThread.start();
888
					logReplication.info("ReplicationService.handleGetLockRequest - lock granted for " + docid);
889
				} else { //deny the lock
890
					out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
891
					logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
892
							+ "reason: file already locked");
893
				}
894
			} else {//deny the lock.
895
				out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
896
				logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
897
						+ "reason: client has outdated file");
898
			}
899
			//conn.close();
900
		} catch (Exception e) {
901
			logMetacat.error("ReplicationService.handleGetLockRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
902
			logReplication.error("ReplicationService.handleGetLockRequest - error requesting file lock from MetacatReplication."
903
					+ "handleGetLockRequest: " + e.getMessage());
904
			e.printStackTrace(System.out);
905
		}
906
	}
907

    
908
	/**
909
	 * Sends all of the xml_documents information encoded in xml to a requestor
910
	 * the format is:
911
	 * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
912
	 *                  user_updated, home_server, public_access, rev)/>
913
	 * all of the subelements of document info are #PCDATA
914
	 */
915
	protected static void handleGetDocumentInfoRequest(PrintWriter out,
916
			Hashtable<String, String[]> params, HttpServletResponse response) {
917
		String docid = ((String[]) (params.get("docid")))[0];
918
		StringBuffer sb = new StringBuffer();
919

    
920
		try {
921
		  IdentifierManager idman = IdentifierManager.getInstance();
922

    
923
			DocumentImpl doc = new DocumentImpl(docid);
924
			sb.append("<documentinfo><docid>").append(docid);
925
			sb.append("</docid>");
926
			try
927
			{
928
			  String guid = idman.getGUID(doc.getDocID(), doc.getRev());
929
			  sb.append("<guid>").append(guid).append("</guid>");
930
			  String smLocalId = idman.getSystemMetadataLocalId(guid);
931
			  if(smLocalId != null && !smLocalId.trim().equals(""))
932
			  {
933
			      sb.append("<systemmetadatalocalid>").append(smLocalId).append("</systemmetadatalocalid>");
934
			  }
935
			}
936
			catch(McdbDocNotFoundException e)
937
			{
938
			  //do nothing, there was no guid for this document
939
			}
940
			sb.append("<docname>").append(doc.getDocname());
941
			sb.append("</docname><doctype>").append(doc.getDoctype());
942
			sb.append("</doctype>");
943
			sb.append("<user_owner>").append(doc.getUserowner());
944
			sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
945
			sb.append("</user_updated>");
946
			sb.append("<date_created>");
947
			sb.append(doc.getCreateDate());
948
			sb.append("</date_created>");
949
			sb.append("<date_updated>");
950
			sb.append(doc.getUpdateDate());
951
			sb.append("</date_updated>");
952
			sb.append("<home_server>");
953
			sb.append(doc.getDocHomeServer());
954
			sb.append("</home_server>");
955
			sb.append("<public_access>").append(doc.getPublicaccess());
956
			sb.append("</public_access><rev>").append(doc.getRev());
957
			sb.append("</rev>");
958

    
959
			sb.append("<accessControl>");
960

    
961
			AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid); 
962
			sb.append(acfsf.getAccessString());
963
			
964
			sb.append("</accessControl>");
965

    
966
			sb.append("</documentinfo>");
967
			response.setContentType("text/xml");
968
			out.println(sb.toString());
969

    
970
		} catch (Exception e) {
971
			logMetacat.error("ReplicationService.handleGetDocumentInfoRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
972
			logReplication.error("ReplicationService.handleGetDocumentInfoRequest - error in metacatReplication.handlegetdocumentinforequest "
973
					+ "for doc: " + docid + " : " + e.getMessage());
974
		}
975

    
976
	}
977

    
978
	/**
979
	 * Sends a datafile to a remote host
980
	 */
981
	protected static void handleGetDataFileRequest(OutputStream outPut,
982
			Hashtable<String, String[]> params, HttpServletResponse response)
983

    
984
	{
985
		// File path for data file
986
		String filepath;
987
		// Request docid
988
		String docId = ((String[]) (params.get("docid")))[0];
989
		//check if the doicd is null
990
		if (docId == null) {
991
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
992
			logReplication.error("ReplicationService.handleGetDataFileRequest - Didn't specify docid for replication");
993
			return;
994
		}
995

    
996
		//try to open a https stream to test if the request server's public key
997
		//in the key store, this is security issue
998
		try {
999
			filepath = PropertyService.getProperty("application.datafilepath");
1000
			String server = params.get("server")[0];
1001
			URL u = new URL("https://" + server + "?server="
1002
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test");
1003
			String test = ReplicationService.getURLContent(u);
1004
			//couldn't pass the test
1005
			if (test.indexOf("successfully") == -1) {
1006
				//response.setContentType("text/xml");
1007
				//outPut.println("<error>Couldn't pass the trust test</error>");
1008
				logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1009
				logReplication.error("ReplicationService.handleGetDataFileRequest - Couldn't pass the trust test");
1010
				return;
1011
			}
1012
		}//try
1013
		catch (Exception ee) {
1014
			return;
1015
		}//catch
1016

    
1017
		if (!filepath.endsWith("/")) {
1018
			filepath += "/";
1019
		}
1020
		// Get file aboslute file name
1021
		String filename = filepath + docId;
1022

    
1023
		//MIME type
1024
		String contentType = null;
1025
		if (filename.endsWith(".xml")) {
1026
			contentType = "text/xml";
1027
		} else if (filename.endsWith(".css")) {
1028
			contentType = "text/css";
1029
		} else if (filename.endsWith(".dtd")) {
1030
			contentType = "text/plain";
1031
		} else if (filename.endsWith(".xsd")) {
1032
			contentType = "text/xml";
1033
		} else if (filename.endsWith("/")) {
1034
			contentType = "text/html";
1035
		} else {
1036
			File f = new File(filename);
1037
			if (f.isDirectory()) {
1038
				contentType = "text/html";
1039
			} else {
1040
				contentType = "application/octet-stream";
1041
			}
1042
		}
1043

    
1044
		// Set the mime type
1045
		response.setContentType(contentType);
1046

    
1047
		// Get the content of the file
1048
		FileInputStream fin = null;
1049
		try {
1050
			// FileInputStream to metacat
1051
			fin = new FileInputStream(filename);
1052
			// 4K buffer
1053
			byte[] buf = new byte[4 * 1024];
1054
			// Read data from file input stream to byte array
1055
			int b = fin.read(buf);
1056
			// Write to outStream from byte array
1057
			while (b != -1) {
1058
				outPut.write(buf, 0, b);
1059
				b = fin.read(buf);
1060
			}
1061
			// close file input stream
1062
			fin.close();
1063

    
1064
		}//try
1065
		catch (Exception e) {
1066
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1067
			logReplication.error("ReplicationService.handleGetDataFileRequest - error getting data file from MetacatReplication."
1068
					+ "handlGetDataFileRequest " + e.getMessage());
1069
			e.printStackTrace(System.out);
1070
		}//catch
1071

    
1072
	}
1073

    
1074
	/**
1075
	 * Sends a document to a remote host
1076
	 */
1077
	protected static void handleGetDocumentRequest(PrintWriter out,
1078
			Hashtable<String, String[]> params, HttpServletResponse response) {
1079

    
1080
		String urlString = null;
1081
		String documentPath = null;
1082
		try {
1083
			// try to open a https stream to test if the request server's public
1084
			// key
1085
			// in the key store, this is security issue
1086
			String server = params.get("server")[0];
1087
			urlString = "https://" + server + "?server="
1088
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test";
1089
			URL u = new URL(urlString);
1090
			String test = ReplicationService.getURLContent(u);
1091
			// couldn't pass the test
1092
			if (test.indexOf("successfully") == -1) {
1093
				response.setContentType("text/xml");
1094
				out.println("<error>Couldn't pass the trust test " + test + " </error>");
1095
				out.close();
1096
				return;
1097
			}
1098

    
1099
			String docid = params.get("docid")[0];
1100
			logReplication.debug("ReplicationService.handleGetDocumentRequest - MetacatReplication.handleGetDocumentRequest for docid: "
1101
					+ docid);
1102
			DocumentImpl di = new DocumentImpl(docid);
1103

    
1104
			String documentDir = PropertyService
1105
					.getProperty("application.documentfilepath");
1106
			documentPath = documentDir + FileUtil.getFS() + docid;
1107

    
1108
			// if the document does not exist on disk, read it from db and write
1109
			// it to disk.
1110
			if (FileUtil.getFileStatus(documentPath) == FileUtil.DOES_NOT_EXIST
1111
					|| FileUtil.getFileSize(documentPath) == 0) {
1112
				FileWriter fileWriter = new FileWriter(documentPath);
1113
				di.toXml(fileWriter, null, null, true);
1114
			}
1115

    
1116
			// read the file from disk and sent it to PrintWriter
1117
			// PrintWriter out = new PrintWriter(streamOut);
1118
			di.readFromFileSystem(out, null, null, documentPath);
1119

    
1120
			// response.setContentType("text/xml");
1121
			// out.print(di.toString(null, null, true));
1122

    
1123
			logReplication.info("ReplicationService.handleGetDocumentRequest - document " + docid + " sent");
1124

    
1125
		} catch (MalformedURLException mue) {
1126
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1127
			logReplication.error("ReplicationService.handleGetDocumentRequest - Url error when getting document from MetacatReplication."
1128
					+ "handlGetDocumentRequest for url: " + urlString + " : "
1129
					+ mue.getMessage());
1130
			// e.printStackTrace(System.out);
1131
			response.setContentType("text/xml");
1132
			out.println("<error>" + mue.getMessage() + "</error>");
1133
		} catch (IOException ioe) {
1134
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1135
			logReplication.error("ReplicationService.handleGetDocumentRequest - I/O error when getting document from MetacatReplication."
1136
					+ "handlGetDocumentRequest for file: " + documentPath + " : "
1137
					+ ioe.getMessage());
1138
			// e.printStackTrace(System.out);
1139
			response.setContentType("text/xml");
1140
			out.println("<error>" + ioe.getMessage() + "</error>");
1141
		} catch (PropertyNotFoundException pnfe) {
1142
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1143
			logReplication
1144
					.error("ReplicationService.handleGetDocumentRequest - Error getting property when getting document from MetacatReplication."
1145
							+ "handlGetDocumentRequest for file: "
1146
							+ documentPath
1147
							+ " : "
1148
							+ pnfe.getMessage());
1149
			// e.printStackTrace(System.out);
1150
			response.setContentType("text/xml");
1151
			out.println("<error>" + pnfe.getMessage() + "</error>");
1152
		} catch (McdbException me) {
1153
			logReplication
1154
					.error("ReplicationService.handleGetDocumentRequest - Document implementation error  getting property when getting document from MetacatReplication."
1155
							+ "handlGetDocumentRequest for file: "
1156
							+ documentPath
1157
							+ " : "
1158
							+ me.getMessage());
1159
			// e.printStackTrace(System.out);
1160
			response.setContentType("text/xml");
1161
			out.println("<error>" + me.getMessage() + "</error>");
1162
		}
1163

    
1164
	}
1165

    
1166
	/**
1167
	 * Sends a list of all of the documents on this sever along with their
1168
	 * revision numbers. The format is: <!ELEMENT replication (server, updates)>
1169
	 * <!ELEMENT server (#PCDATA)> <!ELEMENT updates ((updatedDocument |
1170
	 * deleteDocument | revisionDocument)*)> <!ELEMENT updatedDocument (docid,
1171
	 * rev, datafile*)> <!ELEMENT deletedDocument (docid, rev)> <!ELEMENT
1172
	 * revisionDocument (docid, rev, datafile*)> <!ELEMENT docid (#PCDATA)>
1173
	 * <!ELEMENT rev (#PCDATA)> <!ELEMENT datafile (#PCDATA)> note that the rev
1174
	 * in deletedDocument is always empty. I just left it in there to make the
1175
	 * parser implementation easier.
1176
	 */
1177
	protected static void handleUpdateRequest(PrintWriter out, Hashtable<String, String[]> params,
1178
			HttpServletResponse response) {
1179
		// Checked out DBConnection
1180
		DBConnection dbConn = null;
1181
		// DBConenction serial number when checked it out
1182
		int serialNumber = -1;
1183
		PreparedStatement pstmt = null;
1184
		// Server list to store server info of xml_replication table
1185
		ReplicationServerList serverList = null;
1186

    
1187
		try {
1188
			// Check out a DBConnection from pool
1189
			dbConn = DBConnectionPool
1190
					.getDBConnection("MetacatReplication.handleUpdateRequest");
1191
			serialNumber = dbConn.getCheckOutSerialNumber();
1192
			// Create a server list from xml_replication table
1193
			serverList = new ReplicationServerList();
1194

    
1195
			// Get remote server name from param
1196
			String server = ((String[]) params.get("server"))[0];
1197
			// If no servr name in param, return a error
1198
			if (server == null || server.equals("")) {
1199
				response.setContentType("text/xml");
1200
				out.println("<error>Request didn't specify server name</error>");
1201
				out.close();
1202
				return;
1203
			}//if
1204

    
1205
			//try to open a https stream to test if the request server's public key
1206
			//in the key store, this is security issue
1207
			String testUrl = "https://" + server + "?server="
1208
            + MetacatUtil.getLocalReplicationServerName() + "&action=test";
1209
			logReplication.info("Running trust test: " + testUrl);
1210
			URL u = new URL(testUrl);
1211
			String test = ReplicationService.getURLContent(u);
1212
			logReplication.info("Ouput from test is '" + test + "'");
1213
			//couldn't pass the test
1214
			if (test.indexOf("successfully") == -1) {
1215
			    logReplication.error("Trust test failed.");
1216
				response.setContentType("text/xml");
1217
				out.println("<error>Couldn't pass the trust test</error>");
1218
				out.close();
1219
				return;
1220
			}
1221
			logReplication.info("Trust test succeeded.");
1222

    
1223
			// Check if local host configure to replicate xml documents to remote
1224
			// server. If not send back a error message
1225
			if (!serverList.getReplicationValue(server)) {
1226
				response.setContentType("text/xml");
1227
				out
1228
						.println("<error>Configuration not allow to replicate document to you</error>");
1229
				out.close();
1230
				return;
1231
			}//if
1232

    
1233
			// Store the sql command
1234
			StringBuffer docsql = new StringBuffer();
1235
			StringBuffer revisionSql = new StringBuffer();
1236
			// Stroe the docid list
1237
			StringBuffer doclist = new StringBuffer();
1238
			// Store the deleted docid list
1239
			StringBuffer delsql = new StringBuffer();
1240
			// Store the data set file
1241
			Vector<Vector<String>> packageFiles = new Vector<Vector<String>>();
1242

    
1243
			// Append local server's name and replication servlet to doclist
1244
			doclist.append("<?xml version=\"1.0\"?><replication>");
1245
			doclist.append("<server>")
1246
					.append(MetacatUtil.getLocalReplicationServerName());
1247
			//doclist.append(util.getProperty("replicationpath"));
1248
			doclist.append("</server><updates>");
1249

    
1250
			// Get correct docid that reside on this server according the requesting
1251
			// server's replicate and data replicate value in xml_replication table
1252
			docsql.append(DatabaseService.getInstance().getDBAdapter().getReplicationDocumentListSQL());
1253
			//docsql.append("select docid, rev, doctype from xml_documents where (docid not in (select a.docid from xml_documents a, xml_revisions b where a.docid=b.docid and a.rev<=b.rev)) ");
1254
			revisionSql.append("select docid, rev, doctype from xml_revisions ");
1255
			// If the localhost is not a hub to the remote server, only replicate
1256
			// the docid' which home server is local host (server_location =1)
1257
			if (!serverList.getHubValue(server)) {
1258
				String serverLocationDoc = " and a.server_location = 1";
1259
				String serverLocationRev = "where server_location = 1";
1260
				docsql.append(serverLocationDoc);
1261
				revisionSql.append(serverLocationRev);
1262
			}
1263
			logReplication.info("ReplicationService.handleUpdateRequest - Doc sql: " + docsql.toString());
1264

    
1265
			// Get any deleted documents
1266
			delsql.append("select distinct docid from ");
1267
			delsql.append("xml_revisions where docid not in (select docid from ");
1268
			delsql.append("xml_documents) ");
1269
			// If the localhost is not a hub to the remote server, only replicate
1270
			// the docid' which home server is local host (server_location =1)
1271
			if (!serverList.getHubValue(server)) {
1272
				delsql.append("and server_location = 1");
1273
			}
1274
			logReplication.info("ReplicationService.handleUpdateRequest - Deleted sql: " + delsql.toString());
1275

    
1276
			// Get docid list of local host
1277
			pstmt = dbConn.prepareStatement(docsql.toString());
1278
			pstmt.execute();
1279
			ResultSet rs = pstmt.getResultSet();
1280
			boolean tablehasrows = rs.next();
1281
			//If metacat configed to replicate data file
1282
			//if ((util.getProperty("replicationsenddata")).equals("on"))
1283
			boolean replicateData = serverList.getDataReplicationValue(server);
1284
			if (replicateData) {
1285
				while (tablehasrows) {
1286
					String recordDoctype = rs.getString(3);
1287
					Vector<String> packagedoctypes = MetacatUtil
1288
							.getOptionList(PropertyService
1289
									.getProperty("xml.packagedoctype"));
1290
					//if this is a package file, put it at the end
1291
					//because if a package file is read before all of the files it
1292
					//refers to are loaded then there is an error
1293
					if (recordDoctype != null && !packagedoctypes.contains(recordDoctype)) {
1294
						//If this is not data file
1295
						if (!recordDoctype.equals("BIN")) {
1296
							//for non-data file document
1297
							doclist.append("<updatedDocument>");
1298
							doclist.append("<docid>").append(rs.getString(1));
1299
							doclist.append("</docid><rev>").append(rs.getInt(2));
1300
							doclist.append("</rev>");
1301
							doclist.append("</updatedDocument>");
1302
						}//if
1303
						else {
1304
							//for data file document, in datafile attributes
1305
							//we put "datafile" value there
1306
							doclist.append("<updatedDocument>");
1307
							doclist.append("<docid>").append(rs.getString(1));
1308
							doclist.append("</docid><rev>").append(rs.getInt(2));
1309
							doclist.append("</rev>");
1310
							doclist.append("<datafile>");
1311
							doclist.append(PropertyService
1312
									.getProperty("replication.datafileflag"));
1313
							doclist.append("</datafile>");
1314
							doclist.append("</updatedDocument>");
1315
						}//else
1316
					}//if packagedoctpes
1317
					else { //the package files are saved to be put into the xml later.
1318
						Vector<String> v = new Vector<String>();
1319
						v.add(rs.getString(1));
1320
						v.add(String.valueOf(rs.getInt(2)));
1321
						packageFiles.add(v);
1322
					}//esle
1323
					tablehasrows = rs.next();
1324
				}//while
1325
			}//if
1326
			else //metacat was configured not to send data file
1327
			{
1328
				while (tablehasrows) {
1329
					String recordDoctype = rs.getString(3);
1330
					if (!recordDoctype.equals("BIN")) { //don't replicate data files
1331
						Vector<String> packagedoctypes = MetacatUtil
1332
								.getOptionList(PropertyService
1333
										.getProperty("xml.packagedoctype"));
1334
						if (recordDoctype != null
1335
								&& !packagedoctypes.contains(recordDoctype)) { //if this is a package file, put it at the end
1336
							//because if a package file is read before all of the files it
1337
							//refers to are loaded then there is an error
1338
							doclist.append("<updatedDocument>");
1339
							doclist.append("<docid>").append(rs.getString(1));
1340
							doclist.append("</docid><rev>").append(rs.getInt(2));
1341
							doclist.append("</rev>");
1342
							doclist.append("</updatedDocument>");
1343
						} else { //the package files are saved to be put into the xml later.
1344
							Vector<String> v = new Vector<String>();
1345
							v.add(rs.getString(1));
1346
							v.add(String.valueOf(rs.getInt(2)));
1347
							packageFiles.add(v);
1348
						}
1349
					}//if
1350
					tablehasrows = rs.next();
1351
				}//while
1352
			}//else
1353

    
1354
			pstmt = dbConn.prepareStatement(delsql.toString());
1355
			//usage count should increas 1
1356
			dbConn.increaseUsageCount(1);
1357

    
1358
			pstmt.execute();
1359
			rs = pstmt.getResultSet();
1360
			tablehasrows = rs.next();
1361
			while (tablehasrows) { //handle the deleted documents
1362
				doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1363
				doclist.append("</docid><rev></rev></deletedDocument>");
1364
				//note that rev is always empty for deleted docs
1365
				tablehasrows = rs.next();
1366
			}
1367

    
1368
			//now we can put the package files into the xml results
1369
			for (int i = 0; i < packageFiles.size(); i++) {
1370
				Vector<String> v = packageFiles.elementAt(i);
1371
				doclist.append("<updatedDocument>");
1372
				doclist.append("<docid>").append(v.elementAt(0));
1373
				doclist.append("</docid><rev>");
1374
				doclist.append(v.elementAt(1));
1375
				doclist.append("</rev>");
1376
				doclist.append("</updatedDocument>");
1377
			}
1378
			// add revision doc list  
1379
			doclist.append(prepareRevisionDoc(dbConn, revisionSql.toString(),
1380
					replicateData));
1381

    
1382
			doclist.append("</updates></replication>");
1383
			logReplication.info("ReplicationService.handleUpdateRequest - doclist: " + doclist.toString());
1384
			pstmt.close();
1385
			//conn.close();
1386
			response.setContentType("text/xml");
1387
			out.println(doclist.toString());
1388

    
1389
		} catch (Exception e) {
1390
			logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1391
			logReplication.error("ReplicationService.handleUpdateRequest - error in MetacatReplication." + "handleupdaterequest: "
1392
					+ e.getMessage());
1393
			//e.printStackTrace(System.out);
1394
			response.setContentType("text/xml");
1395
			out.println("<error>" + e.getMessage() + "</error>");
1396
		} finally {
1397
			try {
1398
				pstmt.close();
1399
			}//try
1400
			catch (SQLException ee) {
1401
				logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1402
				logReplication.error("ReplicationService.handleUpdateRequest - Error in MetacatReplication."
1403
						+ "handleUpdaterequest to close pstmt: " + ee.getMessage());
1404
			}//catch
1405
			finally {
1406
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1407
			}//finally
1408
		}//finally
1409

    
1410
	}//handlUpdateRequest
1411

    
1412
	/*
1413
	 * This method will get the xml string for document in xml_revision
1414
	 * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1415
	 */
1416
	private static String prepareRevisionDoc(DBConnection dbConn, String revSql,
1417
			boolean replicateData) throws Exception {
1418
		logReplication.warn("ReplicationService.prepareRevisionDoc - The revision document sql is " + revSql);
1419
		StringBuffer revDocList = new StringBuffer();
1420
		PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1421
		//usage count should increas 1
1422
		dbConn.increaseUsageCount(1);
1423

    
1424
		pstmt.execute();
1425
		ResultSet rs = pstmt.getResultSet();
1426
		boolean tablehasrows = rs.next();
1427
		while (tablehasrows) {
1428
			String recordDoctype = rs.getString(3);
1429

    
1430
			//If this is data file and it isn't configured to replicate data
1431
			if (recordDoctype.equals("BIN") && !replicateData) {
1432
				// do nothing
1433
				continue;
1434
			} else {
1435

    
1436
				revDocList.append("<revisionDocument>");
1437
				revDocList.append("<docid>").append(rs.getString(1));
1438
				revDocList.append("</docid><rev>").append(rs.getInt(2));
1439
				revDocList.append("</rev>");
1440
				// data file
1441
				if (recordDoctype.equals("BIN")) {
1442
					revDocList.append("<datafile>");
1443
					revDocList.append(PropertyService
1444
							.getProperty("replication.datafileflag"));
1445
					revDocList.append("</datafile>");
1446
				}
1447
				revDocList.append("</revisionDocument>");
1448

    
1449
			}//else
1450
			tablehasrows = rs.next();
1451
		}
1452
		//System.out.println("The revision list is"+ revDocList.toString());
1453
		return revDocList.toString();
1454
	}
1455

    
1456
	/**
1457
	 * Returns the xml_catalog table encoded in xml
1458
	 */
1459
	public static String getCatalogXML() {
1460
		return handleGetCatalogRequest(null, null, null, false);
1461
	}
1462

    
1463
	/**
1464
	 * Sends the contents of the xml_catalog table encoded in xml
1465
	 * The xml format is:
1466
	 * <!ELEMENT xml_catalog (row*)>
1467
	 * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1468
	 *                system_id)>
1469
	 * All of the sub elements of row are #PCDATA
1470

    
1471
	 * If printFlag == false then do not print to out.
1472
	 */
1473
	protected static String handleGetCatalogRequest(PrintWriter out,
1474
			Hashtable<String, String[]> params, HttpServletResponse response,
1475
			boolean printFlag) {
1476
		DBConnection dbConn = null;
1477
		int serialNumber = -1;
1478
		PreparedStatement pstmt = null;
1479
		try {
1480
			/*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1481
			                                          "handleGetCatalogRequest");*/
1482
			dbConn = DBConnectionPool
1483
					.getDBConnection("MetacatReplication.handleGetCatalogRequest");
1484
			serialNumber = dbConn.getCheckOutSerialNumber();
1485
			pstmt = dbConn.prepareStatement("select entry_type, "
1486
					+ "source_doctype, target_doctype, public_id, "
1487
					+ "system_id from xml_catalog");
1488
			pstmt.execute();
1489
			ResultSet rs = pstmt.getResultSet();
1490
			boolean tablehasrows = rs.next();
1491
			StringBuffer sb = new StringBuffer();
1492
			sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1493
			while (tablehasrows) {
1494
				sb.append("<row><entry_type>").append(rs.getString(1));
1495
				sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1496
				sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1497
				sb.append("</target_doctype><public_id>").append(rs.getString(4));
1498
				// system id may not have server url on front.  Add it if not.
1499
				String systemID = rs.getString(5);
1500
				if (!systemID.startsWith("http://")) {
1501
					systemID = SystemUtil.getContextURL() + systemID;
1502
				}
1503
				sb.append("</public_id><system_id>").append(systemID);
1504
				sb.append("</system_id></row>");
1505

    
1506
				tablehasrows = rs.next();
1507
			}
1508
			sb.append("</xml_catalog>");
1509
			//conn.close();
1510
			if (printFlag) {
1511
				response.setContentType("text/xml");
1512
				out.println(sb.toString());
1513
			}
1514
			pstmt.close();
1515
			return sb.toString();
1516
		} catch (Exception e) {
1517
			logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1518
			logReplication.error("ReplicationService.handleGetCatalogRequest - error in MetacatReplication.handleGetCatalogRequest:"
1519
					+ e.getMessage());
1520
			e.printStackTrace(System.out);
1521
			if (printFlag) {
1522
				out.println("<error>" + e.getMessage() + "</error>");
1523
			}
1524
		} finally {
1525
			try {
1526
				pstmt.close();
1527
			}//try
1528
			catch (SQLException ee) {
1529
				logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1530
				logReplication.error("ReplicationService.handleGetCatalogRequest - Error in MetacatReplication.handleGetCatalogRequest: "
1531
						+ ee.getMessage());
1532
			}//catch
1533
			finally {
1534
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1535
			}//finally
1536
		}//finally
1537

    
1538
		return null;
1539
	}
1540

    
1541
	/**
1542
	 * Sends the current system date to the remote server.  Using this action
1543
	 * for replication gets rid of any problems with syncronizing clocks
1544
	 * because a time specific to a document is always kept on its home server.
1545
	 */
1546
	protected static void handleGetTimeRequest(PrintWriter out,
1547
			Hashtable<String, String[]> params, HttpServletResponse response) {
1548
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
1549
		java.util.Date localtime = new java.util.Date();
1550
		String dateString = formatter.format(localtime);
1551
		response.setContentType("text/xml");
1552

    
1553
		out.println("<timestamp>" + dateString + "</timestamp>");
1554
	}
1555

    
1556
	/**
1557
	 * this method handles the timeout for a file lock.  when a lock is
1558
	 * granted it is granted for 30 seconds.  When this thread runs out
1559
	 * it deletes the docid from the queue, thus eliminating the lock.
1560
	 */
1561
	public void run() {
1562
		try {
1563
			logReplication.info("ReplicationService.run - thread started for docid: "
1564
					+ (String) fileLocks.elementAt(0));
1565

    
1566
			Thread.sleep(30000); //the lock will expire in 30 seconds
1567
			logReplication.info("thread for docid: "
1568
					+ (String) fileLocks.elementAt(fileLocks.size() - 1) + " exiting.");
1569

    
1570
			fileLocks.remove(fileLocks.size() - 1);
1571
			//fileLocks is treated as a FIFO queue.  If there are more than one lock
1572
			//in the vector, the first one inserted will be removed.
1573
		} catch (Exception e) {
1574
			logMetacat.error("ReplicationService.run - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1575
			logReplication.error("ReplicationService.run - error in file lock thread from "
1576
					+ "MetacatReplication.run: " + e.getMessage());
1577
		}
1578
	}
1579

    
1580
	/**
1581
	 * Returns the name of a server given a serverCode
1582
	 * @param serverCode the serverid of the server
1583
	 * @return the servername or null if the specified serverCode does not
1584
	 *         exist.
1585
	 */
1586
	public static String getServerNameForServerCode(int serverCode) {
1587
		//System.out.println("serverid: " + serverCode);
1588
		DBConnection dbConn = null;
1589
		int serialNumber = -1;
1590
		PreparedStatement pstmt = null;
1591
		try {
1592
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServer");
1593
			serialNumber = dbConn.getCheckOutSerialNumber();
1594
			String sql = new String("select server from "
1595
					+ "xml_replication where serverid = " + serverCode);
1596
			pstmt = dbConn.prepareStatement(sql);
1597
			//System.out.println("getserver sql: " + sql);
1598
			pstmt.execute();
1599
			ResultSet rs = pstmt.getResultSet();
1600
			boolean tablehasrows = rs.next();
1601
			if (tablehasrows) {
1602
				//System.out.println("server: " + rs.getString(1));
1603
				return rs.getString(1);
1604
			}
1605

    
1606
			//conn.close();
1607
		} catch (Exception e) {
1608
			logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1609
			logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplication.getServer: " + e.getMessage());
1610
		} finally {
1611
			try {
1612
				pstmt.close();
1613
			}//try
1614
			catch (SQLException ee) {
1615
				logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1616
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacactReplication.getserver: "
1617
						+ ee.getMessage());
1618
			}//catch
1619
			finally {
1620
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1621
			}//fianlly
1622
		}//finally
1623

    
1624
		return null;
1625
		//return null if the server does not exist
1626
	}
1627

    
1628
	/**
1629
	 * Returns a server code given a server name
1630
	 * @param server the name of the server
1631
	 * @return integer > 0 representing the code of the server, 0 if the server
1632
	 *  does not exist.
1633
	 */
1634
	public static int getServerCodeForServerName(String server) throws ServiceException {
1635
		DBConnection dbConn = null;
1636
		int serialNumber = -1;
1637
		PreparedStatement pstmt = null;
1638
		int serverCode = 0;
1639

    
1640
		try {
1641

    
1642
			//conn = util.openDBConnection();
1643
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServerCode");
1644
			serialNumber = dbConn.getCheckOutSerialNumber();
1645
			pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication "
1646
					+ "WHERE server LIKE '" + server + "'");
1647
			pstmt.execute();
1648
			ResultSet rs = pstmt.getResultSet();
1649
			boolean tablehasrows = rs.next();
1650
			if (tablehasrows) {
1651
				serverCode = rs.getInt(1);
1652
				pstmt.close();
1653
				//conn.close();
1654
				return serverCode;
1655
			}
1656

    
1657
		} catch (SQLException sqle) {
1658
			throw new ServiceException("ReplicationService.getServerCodeForServerName - " 
1659
					+ "SQL error when getting server code: " + sqle.getMessage());
1660

    
1661
		} finally {
1662
			try {
1663
				pstmt.close();
1664
				//conn.close();
1665
			}//try
1666
			catch (Exception ee) {
1667
				logMetacat.error("ReplicationService.getServerCodeForServerName - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1668
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplicatio.getServerCode: "
1669
						+ ee.getMessage());
1670

    
1671
			}//catch
1672
			finally {
1673
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1674
			}//finally
1675
		}//finally
1676

    
1677
		return serverCode;
1678
	}
1679

    
1680
	/**
1681
	 * Method to get a host server information for given docid
1682
	 * @param conn a connection to the database
1683
	 */
1684
	public static Hashtable<String, String> getHomeServerInfoForDocId(String docId) {
1685
		Hashtable<String, String> sl = new Hashtable<String, String>();
1686
		DBConnection dbConn = null;
1687
		int serialNumber = -1;
1688
		docId = DocumentUtil.getDocIdFromString(docId);
1689
		PreparedStatement pstmt = null;
1690
		int serverLocation;
1691
		try {
1692
			//get conection
1693
			dbConn = DBConnectionPool.getDBConnection("ReplicationHandler.getHomeServer");
1694
			serialNumber = dbConn.getCheckOutSerialNumber();
1695
			//get a server location from xml_document table
1696
			pstmt = dbConn.prepareStatement("select server_location from xml_documents "
1697
					+ "where docid = ?");
1698
			pstmt.setString(1, docId);
1699
			pstmt.execute();
1700
			ResultSet serverName = pstmt.getResultSet();
1701
			//get a server location
1702
			if (serverName.next()) {
1703
				serverLocation = serverName.getInt(1);
1704
				pstmt.close();
1705
			} else {
1706
				pstmt.close();
1707
				//ut.returnConnection(conn);
1708
				return null;
1709
			}
1710
			pstmt = dbConn.prepareStatement("select server, last_checked, replicate "
1711
					+ "from xml_replication where serverid = ?");
1712
			//increase usage count
1713
			dbConn.increaseUsageCount(1);
1714
			pstmt.setInt(1, serverLocation);
1715
			pstmt.execute();
1716
			ResultSet rs = pstmt.getResultSet();
1717
			boolean tableHasRows = rs.next();
1718
			if (tableHasRows) {
1719

    
1720
				String server = rs.getString(1);
1721
				String last_checked = rs.getString(2);
1722
				if (!server.equals("localhost")) {
1723
					sl.put(server, last_checked);
1724
				}
1725

    
1726
			} else {
1727
				pstmt.close();
1728
				//ut.returnConnection(conn);
1729
				return null;
1730
			}
1731
			pstmt.close();
1732
		} catch (Exception e) {
1733
			logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1734
			logReplication.error("ReplicationService.getHomeServerInfoForDocId - error in replicationHandler.getHomeServer(): "
1735
					+ e.getMessage());
1736
		} finally {
1737
			try {
1738
				pstmt.close();
1739
				//ut.returnConnection(conn);
1740
			} catch (Exception ee) {
1741
				logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1742
				logReplication.error("ReplicationService.getHomeServerInfoForDocId - Eror irn rplicationHandler.getHomeServer() "
1743
						+ "to close pstmt: " + ee.getMessage());
1744
			} finally {
1745
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1746
			}
1747

    
1748
		}//finally
1749
		return sl;
1750
	}
1751

    
1752
	/**
1753
	 * Returns a home server location  given a accnum
1754
	 * @param accNum , given accNum for a document
1755
	 *
1756
	 */
1757
	public static int getHomeServerCodeForDocId(String accNum) throws ServiceException {
1758
		DBConnection dbConn = null;
1759
		int serialNumber = -1;
1760
		PreparedStatement pstmt = null;
1761
		int serverCode = 1;
1762
		String docId = DocumentUtil.getDocIdFromString(accNum);
1763

    
1764
		try {
1765

    
1766
			// Get DBConnection
1767
			dbConn = DBConnectionPool
1768
					.getDBConnection("ReplicationHandler.getServerLocation");
1769
			serialNumber = dbConn.getCheckOutSerialNumber();
1770
			pstmt = dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1771
					+ "WHERE docid LIKE '" + docId + "'");
1772
			pstmt.execute();
1773
			ResultSet rs = pstmt.getResultSet();
1774
			boolean tablehasrows = rs.next();
1775
			//If a document is find, return the server location for it
1776
			if (tablehasrows) {
1777
				serverCode = rs.getInt(1);
1778
				pstmt.close();
1779
				//conn.close();
1780
				return serverCode;
1781
			}
1782
			//if couldn't find in xml_documents table, we think server code is 1
1783
			//(this is new document)
1784
			else {
1785
				pstmt.close();
1786
				//conn.close();
1787
				return serverCode;
1788
			}
1789

    
1790
		} catch (SQLException sqle) {
1791
			throw new ServiceException("ReplicationService.getHomeServerCodeForDocId - " 
1792
					+ "SQL error when getting home server code for docid: " + docId + " : " 
1793
					+ sqle.getMessage());
1794

    
1795
		} finally {
1796
			try {
1797
				pstmt.close();
1798
				//conn.close();
1799

    
1800
			} catch (SQLException sqle) {
1801
				logMetacat.error("ReplicationService.getHomeServerCodeForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1802
				logReplication.error("ReplicationService.getHomeServerCodeForDocId - ReplicationService.getHomeServerCodeForDocId - " 
1803
						+ "SQL error when getting home server code for docid: " + docId + " : " 
1804
						+ sqle.getMessage());
1805
			} finally {
1806
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1807
			}//finally
1808
		}//finally
1809
		//return serverCode;
1810
	}
1811

    
1812
	/**
1813
	 * This method returns the content of a url
1814
	 * @param u the url to return the content from
1815
	 * @return a string representing the content of the url
1816
	 * @throws java.io.IOException
1817
	 */
1818
	public static String getURLContent(URL u) throws java.io.IOException {
1819
	    logReplication.info("Getting url content from " + u.toString());
1820
		char istreamChar;
1821
		int istreamInt;
1822
		logReplication.info("ReplicationService.getURLContent - Before open the stream" + u.toString());
1823
		InputStream input = u.openStream();
1824
		logReplication.info("ReplicationService.getURLContent - After open the stream" + u.toString());
1825
		InputStreamReader istream = new InputStreamReader(input);
1826
		StringBuffer serverResponse = new StringBuffer();
1827
		while ((istreamInt = istream.read()) != -1) {
1828
			istreamChar = (char) istreamInt;
1829
			serverResponse.append(istreamChar);
1830
		}
1831
		istream.close();
1832
		input.close();
1833

    
1834
		return serverResponse.toString();
1835
	}
1836

    
1837
//	/**
1838
//	 * Method for writing replication messages to a log file specified in
1839
//	 * metacat.properties
1840
//	 */
1841
//	public static void replLog(String message) {
1842
//		try {
1843
//			FileOutputStream fos = new FileOutputStream(PropertyService
1844
//					.getProperty("replication.logdir")
1845
//					+ "/metacatreplication.log", true);
1846
//			PrintWriter pw = new PrintWriter(fos);
1847
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
1848
//			java.util.Date localtime = new java.util.Date();
1849
//			String dateString = formatter.format(localtime);
1850
//			dateString += " :: " + message;
1851
//			// time stamp each entry
1852
//			pw.println(dateString);
1853
//			pw.flush();
1854
//		} catch (Exception e) {
1855
//			logReplication.error("error writing to replication log from "
1856
//					+ "MetacatReplication.replLog: " + e.getMessage());
1857
//			// e.printStackTrace(System.out);
1858
//		}
1859
//	}
1860

    
1861
//	/**
1862
//	 * Method for writing replication messages to a log file specified in
1863
//	 * metacat.properties
1864
//	 */
1865
//	public static void replErrorLog(String message) {
1866
//		try {
1867
//			FileOutputStream fos = new FileOutputStream(PropertyService
1868
//					.getProperty("replication.logdir")
1869
//					+ "/metacatreplicationerror.log", true);
1870
//			PrintWriter pw = new PrintWriter(fos);
1871
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
1872
//			java.util.Date localtime = new java.util.Date();
1873
//			String dateString = formatter.format(localtime);
1874
//			dateString += " :: " + message;
1875
//			//time stamp each entry
1876
//			pw.println(dateString);
1877
//			pw.flush();
1878
//		} catch (Exception e) {
1879
//			logReplication.error("error writing to replication error log from "
1880
//					+ "MetacatReplication.replErrorLog: " + e.getMessage());
1881
//			//e.printStackTrace(System.out);
1882
//		}
1883
//	}
1884

    
1885
	/**
1886
	 * Returns true if the replicate field for server in xml_replication is 1.
1887
	 * Returns false otherwise
1888
	 */
1889
	public static boolean replToServer(String server) {
1890
		DBConnection dbConn = null;
1891
		int serialNumber = -1;
1892
		PreparedStatement pstmt = null;
1893
		try {
1894
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.repltoServer");
1895
			serialNumber = dbConn.getCheckOutSerialNumber();
1896
			pstmt = dbConn.prepareStatement("select replicate from "
1897
					+ "xml_replication where server like '" + server + "'");
1898
			pstmt.execute();
1899
			ResultSet rs = pstmt.getResultSet();
1900
			boolean tablehasrows = rs.next();
1901
			if (tablehasrows) {
1902
				int i = rs.getInt(1);
1903
				if (i == 1) {
1904
					pstmt.close();
1905
					//conn.close();
1906
					return true;
1907
				} else {
1908
					pstmt.close();
1909
					//conn.close();
1910
					return false;
1911
				}
1912
			}
1913
		} catch (SQLException sqle) {
1914
			logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1915
			logReplication.error("ReplicationService.replToServer - SQL error in MetacatReplication.replToServer: "
1916
					+ sqle.getMessage());
1917
		} finally {
1918
			try {
1919
				pstmt.close();
1920
				//conn.close();
1921
			}//try
1922
			catch (Exception ee) {
1923
				logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1924
				logReplication.error("ReplicationService.replToServer - Error in MetacatReplication.replToServer: "
1925
						+ ee.getMessage());
1926
			}//catch
1927
			finally {
1928
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1929
			}//finally
1930
		}//finally
1931
		return false;
1932
		//the default if this server does not exist is to not replicate to it.
1933
	}
1934

    
1935
}
(6-6/7)