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-04-26 16:11:12 -0700 (Mon, 26 Apr 2010) $'
10
 * '$Revision: 5324 $'
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

    
496
		try {
497
			//if the url contains a dbaction then the default action is overridden
498
			if (params.containsKey("dbaction")) {
499
				dbaction = ((String[]) params.get("dbaction"))[0];
500
				//serverCode = MetacatReplication.getServerCode(server);
501
				//override = true; //we are now overriding the default action
502
			}
503
			logReplication.info("ReplicationService.handleForceReplicateRequest - force replication request from " + server);
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
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
519

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

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

    
571
			// Get DBConnection from pool
572
			dbConn = DBConnectionPool
573
					.getDBConnection("MetacatReplication.handleForceReplicateRequest");
574
			serialNumber = dbConn.getCheckOutSerialNumber();
575
			// write the document to local database
576
			DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
577
			//try this independently so we can set
578
//			Exception writeException = null;
579
			try {
580
				wrapper.writeReplication(dbConn, xmldoc, null, null,
581
						dbaction, docid, user, null, homeServer, server, createdDate,
582
						updatedDate);
583
			} finally {
584
//				writeException = e;
585

    
586
				//process extra access rules before dealing with the write exception (doc exist already)			
587
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
588
		        if (accessControlList != null) {
589
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
590
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
591
		        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
592
		        			acfsf.insertPermissions(xmlAccessDAO);
593
							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
594
									+ " permissions added to DB");
595
		        		}
596
		            }
597
		        }
598
//				if (accessControlList != null) {
599
//					for (int i = 0; i < accessControlList.size(); i++) {
600
//						AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList
601
//								.get(i);
602
//						if (!acfsf.accessControlExists()) {
603
//							acfsf.insertPermissions();
604
//							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
605
//									+ " permissions added to DB");
606
//						}
607
//					}
608
//				}
609

    
610
//				if (writeException != null) {
611
//					throw writeException;
612
//				}
613

    
614
				logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid + " added to DB with "
615
						+ "action " + dbaction);
616
				EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid,
617
						dbaction);
618
			}
619
		} catch (SQLException sqle) {
620
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
621
			logReplication.error("ReplicationService.handleForceReplicateRequest - SQL error when adding doc " + docid + 
622
					" to DB with action " + dbaction + ": " + sqle.getMessage());
623
		} catch (MalformedURLException mue) {
624
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
625
			logReplication.error("ReplicationService.handleForceReplicateRequest - URL error when adding doc " + docid + 
626
					" to DB with action " + dbaction + ": " + mue.getMessage());
627
		} catch (SAXException se) {
628
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
629
			logReplication.error("ReplicationService.handleForceReplicateRequest - SAX parsing error when adding doc " + docid + 
630
					" to DB with action " + dbaction + ": " + se.getMessage());
631
		} catch (HandlerException he) {
632
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
633
			logReplication.error("ReplicationService.handleForceReplicateRequest - Handler error when adding doc " + docid + 
634
					" to DB with action " + dbaction + ": " + he.getMessage());
635
		} catch (IOException ioe) {
636
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
637
			logReplication.error("ReplicationService.handleForceReplicateRequest - I/O error when adding doc " + docid + 
638
					" to DB with action " + dbaction + ": " + ioe.getMessage());
639
		} catch (PermOrderException poe) {
640
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
641
			logReplication.error("ReplicationService.handleForceReplicateRequest - Permissions order error when adding doc " + docid + 
642
					" to DB with action " + dbaction + ": " + poe.getMessage());
643
		} catch (AccessControlException ace) {
644
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
645
			logReplication.error("ReplicationService.handleForceReplicateRequest - Permissions order error when adding doc " + docid + 
646
					" to DB with action " + dbaction + ": " + ace.getMessage());
647
		} catch (Exception e) {
648
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
649
			logReplication.error("ReplicationService.handleForceReplicateRequest - General error when adding doc " + docid + 
650
					" to DB with action " + dbaction + ": " + e.getMessage());
651
		} finally {
652
			// Return the checked out DBConnection
653
			DBConnectionPool.returnDBConnection(dbConn, serialNumber);
654
		}//finally
655
	}
656

    
657
	/*
658
	 * when a forcereplication delete request comes in, local host will delete this
659
	 * document
660
	 */
661
	protected static void handleForceReplicateDeleteRequest(PrintWriter out,
662
			Hashtable<String, String[]> params, HttpServletResponse response,
663
			HttpServletRequest request) {
664
		String server = ((String[]) params.get("server"))[0]; // the server that
665
		String docid = ((String[]) params.get("docid"))[0]; // sent the document
666
		try {
667
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete request from " + server);
668
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete docid " + docid);
669
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete request from: " + server);
670
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete docid: " + docid);
671
			DocumentImpl.delete(docid, null, null, server);
672
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
673
			EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid,
674
					"delete");
675
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
676
		} catch (Exception e) {
677
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
678
			logReplication.error("document " + docid
679
					+ " failed to delete because " + e.getMessage());
680
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
681

    
682
		}//catch
683

    
684
	}
685

    
686
	/**
687
	 * when a forcereplication data file request comes in, local host sends a
688
	 * readdata request to the requesting server (remote server) for the specified
689
	 * docid. Then store it in local database and file system
690
	 */
691
	protected static void handleForceReplicateDataFileRequest(Hashtable<String, String[]> params,
692
			HttpServletRequest request) {
693

    
694
		//make sure there is some parameters
695
		if (params.isEmpty()) {
696
			return;
697
		}
698
		// Get remote server
699
		String server = ((String[]) params.get("server"))[0];
700
		// the docid should include rev number
701
		String docid = ((String[]) params.get("docid"))[0];
702
		// Make sure there is a docid and server
703
		if (docid == null || server == null || server.equals("")) {
704
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
705
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Didn't specify docid or server for replication");
706
			return;
707
		}
708

    
709
		// Overide or not
710
		//    boolean override = false;
711
		// dbaction - update or insert
712
		String dbaction = null;
713

    
714
		try {
715
			//docid was switch to two parts uinque code and rev
716
			//String uniqueCode=MetacatUtil.getDocIdFromString(docid);
717
			//int rev=MetacatUtil.getVersionFromString(docid);
718
			if (params.containsKey("dbaction")) {
719
				dbaction = ((String[]) params.get("dbaction"))[0];
720
			} else//default value is update
721
			{
722
				dbaction = "update";
723
			}
724

    
725
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - force replication request from " + server);
726
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication request from: " + server);
727
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication docid: " + docid);
728
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication action: " + dbaction);
729
			// get the document info from server
730
			URL docinfourl = new URL("https://" + server + "?server="
731
					+ MetacatUtil.getLocalReplicationServerName()
732
					+ "&action=getdocumentinfo&docid=" + docid);
733

    
734
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
735

    
736
			//dih is the parser for the docinfo xml format
737
			DocInfoHandler dih = new DocInfoHandler();
738
			XMLReader docinfoParser = ReplicationHandler.initParser(dih);
739
			docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
740
			Hashtable<String, String> docinfoHash = dih.getDocInfo();
741
			String user = (String) docinfoHash.get("user_owner");
742

    
743
			String docName = (String) docinfoHash.get("docname");
744

    
745
			String docType = (String) docinfoHash.get("doctype");
746

    
747
			String docHomeServer = (String) docinfoHash.get("home_server");
748

    
749
			String createdDate = (String) docinfoHash.get("date_created");
750

    
751
			String updatedDate = (String) docinfoHash.get("date_updated");
752
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - docHomeServer of datafile: " + docHomeServer);
753

    
754
			//if action is delete, we don't delete the data file. Just archieve
755
			//the xml_documents
756
			/*if (dbaction.equals("delete"))
757
			{
758
			  //conn = util.getConnection();
759
			  DocumentImpl.delete(docid,user,null);
760
			  //util.returnConnection(conn);
761
			}*/
762
			//To data file insert or update is same
763
			if (dbaction.equals("insert") || dbaction.equals("update")) {
764
				//Get data file and store it into local file system.
765
				// sending back readdata request to server
766
				URL url = new URL("https://" + server + "?server="
767
						+ MetacatUtil.getLocalReplicationServerName()
768
						+ "&action=readdata&docid=" + docid);
769
				String datafilePath = PropertyService
770
						.getProperty("application.datafilepath");
771

    
772
				Exception writeException = null;
773
				//register data file into xml_documents table and wite data file
774
				//into file system
775
				try {
776
					DocumentImpl.writeDataFileInReplication(url.openStream(),
777
							datafilePath, docName, docType, docid, user, docHomeServer,
778
							server, DocumentImpl.DOCUMENTTABLE, false, createdDate,
779
							updatedDate);
780
				} catch (Exception e) {
781
					writeException = e;
782
				}
783
				//process extra access rules
784
//				Vector<AccessControlForSingleFile> accessControlList = dih
785
//						.getAccessControlList();
786
//				if (accessControlList != null) {
787
//					for (int i = 0; i < accessControlList.size(); i++) {
788
//						AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList
789
//								.get(i);
790
//						if (!acfsf.accessControlExists()) {
791
//							acfsf.insertPermissions();
792
//							logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - datafile " + docid
793
//									+ " permissions added to DB");
794
//						}
795
//					}
796
//				}
797
				
798
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
799
		        if (accessControlList != null) {
800
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
801
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
802
		        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
803
		        			acfsf.insertPermissions(xmlAccessDAO);
804
							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
805
									+ " permissions added to DB");
806
		        		}
807
		            }
808
		        }
809

    
810
				if (writeException != null) {
811
					throw writeException;
812
				}
813

    
814
				//false means non-timed replication
815
				logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - datafile " + docid + " added to DB with "
816
						+ "action " + dbaction);
817
				EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER,
818
						docid, dbaction);
819
			}
820

    
821
		} catch (Exception e) {
822
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
823
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Datafile " + docid
824
					+ " failed to added to DB with " + "action " + dbaction + " because "
825
					+ e.getMessage());
826
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - ERROR in MetacatReplication.handleForceDataFileReplicate"
827
					+ "Request(): " + e.getMessage());
828
		}
829
	}
830

    
831
	/**
832
	 * Grants or denies a lock to a requesting host.
833
	 * The servlet parameters of interrest are:
834
	 * docid: the docid of the file the lock is being requested for
835
	 * currentdate: the timestamp of the document on the remote server
836
	 *
837
	 */
838
	protected static void handleGetLockRequest(PrintWriter out,
839
			Hashtable<String, String[]> params, HttpServletResponse response) {
840

    
841
		try {
842

    
843
			String docid = ((String[]) params.get("docid"))[0];
844
			String remoteRev = ((String[]) params.get("updaterev"))[0];
845
			DocumentImpl requestDoc = new DocumentImpl(docid);
846
			logReplication.info("ReplicationService.handleGetLockRequest - lock request for " + docid);
847
			int localRevInt = requestDoc.getRev();
848
			int remoteRevInt = Integer.parseInt(remoteRev);
849

    
850
			if (remoteRevInt >= localRevInt) {
851
				if (!fileLocks.contains(docid)) { //grant the lock if it is not already locked
852
					fileLocks.add(0, docid); //insert at the beginning of the queue Vector
853
					//send a message back to the the remote host authorizing the insert
854
					out
855
							.println("<lockgranted><docid>" + docid
856
									+ "</docid></lockgranted>");
857
					//          lockThread = new Thread(this);
858
					//          lockThread.setPriority(Thread.MIN_PRIORITY);
859
					//          lockThread.start();
860
					logReplication.info("ReplicationService.handleGetLockRequest - lock granted for " + docid);
861
				} else { //deny the lock
862
					out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
863
					logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
864
							+ "reason: file already locked");
865
				}
866
			} else {//deny the lock.
867
				out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
868
				logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
869
						+ "reason: client has outdated file");
870
			}
871
			//conn.close();
872
		} catch (Exception e) {
873
			logMetacat.error("ReplicationService.handleGetLockRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
874
			logReplication.error("ReplicationService.handleGetLockRequest - error requesting file lock from MetacatReplication."
875
					+ "handleGetLockRequest: " + e.getMessage());
876
			e.printStackTrace(System.out);
877
		}
878
	}
879

    
880
	/**
881
	 * Sends all of the xml_documents information encoded in xml to a requestor
882
	 * the format is:
883
	 * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
884
	 *                  user_updated, home_server, public_access, rev)/>
885
	 * all of the subelements of document info are #PCDATA
886
	 */
887
	protected static void handleGetDocumentInfoRequest(PrintWriter out,
888
			Hashtable<String, String[]> params, HttpServletResponse response) {
889
		String docid = ((String[]) (params.get("docid")))[0];
890
		StringBuffer sb = new StringBuffer();
891

    
892
		try {
893
		  IdentifierManager idman = IdentifierManager.getInstance();
894

    
895
			DocumentImpl doc = new DocumentImpl(docid);
896
			sb.append("<documentinfo><docid>").append(docid);
897
			sb.append("</docid>");
898
			try
899
			{
900
			  String guid = idman.getGUID(doc.getDocID(), doc.getRev());
901
			  sb.append("<guid>").append(guid).append("</guid>");
902
			}
903
			catch(McdbDocNotFoundException e)
904
			{
905
			  //do nothing, there was no guid for this document
906
			}
907
			sb.append("<docname>").append(doc.getDocname());
908
			sb.append("</docname><doctype>").append(doc.getDoctype());
909
			sb.append("</doctype>");
910
			sb.append("<user_owner>").append(doc.getUserowner());
911
			sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
912
			sb.append("</user_updated>");
913
			sb.append("<date_created>");
914
			sb.append(doc.getCreateDate());
915
			sb.append("</date_created>");
916
			sb.append("<date_updated>");
917
			sb.append(doc.getUpdateDate());
918
			sb.append("</date_updated>");
919
			sb.append("<home_server>");
920
			sb.append(doc.getDocHomeServer());
921
			sb.append("</home_server>");
922
			sb.append("<public_access>").append(doc.getPublicaccess());
923
			sb.append("</public_access><rev>").append(doc.getRev());
924
			sb.append("</rev>");
925

    
926
			sb.append("<accessControl>");
927

    
928
			AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid); 
929
			sb.append(acfsf.getAccessString());
930
			
931
			sb.append("</accessControl>");
932

    
933
			sb.append("</documentinfo>");
934
			response.setContentType("text/xml");
935
			out.println(sb.toString());
936

    
937
		} catch (Exception e) {
938
			logMetacat.error("ReplicationService.handleGetDocumentInfoRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
939
			logReplication.error("ReplicationService.handleGetDocumentInfoRequest - error in metacatReplication.handlegetdocumentinforequest "
940
					+ "for doc: " + docid + " : " + e.getMessage());
941
		}
942

    
943
	}
944

    
945
	/**
946
	 * Sends a datafile to a remote host
947
	 */
948
	protected static void handleGetDataFileRequest(OutputStream outPut,
949
			Hashtable<String, String[]> params, HttpServletResponse response)
950

    
951
	{
952
		// File path for data file
953
		String filepath;
954
		// Request docid
955
		String docId = ((String[]) (params.get("docid")))[0];
956
		//check if the doicd is null
957
		if (docId == null) {
958
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
959
			logReplication.error("ReplicationService.handleGetDataFileRequest - Didn't specify docid for replication");
960
			return;
961
		}
962

    
963
		//try to open a https stream to test if the request server's public key
964
		//in the key store, this is security issue
965
		try {
966
			filepath = PropertyService.getProperty("application.datafilepath");
967
			String server = params.get("server")[0];
968
			URL u = new URL("https://" + server + "?server="
969
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test");
970
			String test = ReplicationService.getURLContent(u);
971
			//couldn't pass the test
972
			if (test.indexOf("successfully") == -1) {
973
				//response.setContentType("text/xml");
974
				//outPut.println("<error>Couldn't pass the trust test</error>");
975
				logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
976
				logReplication.error("ReplicationService.handleGetDataFileRequest - Couldn't pass the trust test");
977
				return;
978
			}
979
		}//try
980
		catch (Exception ee) {
981
			return;
982
		}//catch
983

    
984
		if (!filepath.endsWith("/")) {
985
			filepath += "/";
986
		}
987
		// Get file aboslute file name
988
		String filename = filepath + docId;
989

    
990
		//MIME type
991
		String contentType = null;
992
		if (filename.endsWith(".xml")) {
993
			contentType = "text/xml";
994
		} else if (filename.endsWith(".css")) {
995
			contentType = "text/css";
996
		} else if (filename.endsWith(".dtd")) {
997
			contentType = "text/plain";
998
		} else if (filename.endsWith(".xsd")) {
999
			contentType = "text/xml";
1000
		} else if (filename.endsWith("/")) {
1001
			contentType = "text/html";
1002
		} else {
1003
			File f = new File(filename);
1004
			if (f.isDirectory()) {
1005
				contentType = "text/html";
1006
			} else {
1007
				contentType = "application/octet-stream";
1008
			}
1009
		}
1010

    
1011
		// Set the mime type
1012
		response.setContentType(contentType);
1013

    
1014
		// Get the content of the file
1015
		FileInputStream fin = null;
1016
		try {
1017
			// FileInputStream to metacat
1018
			fin = new FileInputStream(filename);
1019
			// 4K buffer
1020
			byte[] buf = new byte[4 * 1024];
1021
			// Read data from file input stream to byte array
1022
			int b = fin.read(buf);
1023
			// Write to outStream from byte array
1024
			while (b != -1) {
1025
				outPut.write(buf, 0, b);
1026
				b = fin.read(buf);
1027
			}
1028
			// close file input stream
1029
			fin.close();
1030

    
1031
		}//try
1032
		catch (Exception e) {
1033
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1034
			logReplication.error("ReplicationService.handleGetDataFileRequest - error getting data file from MetacatReplication."
1035
					+ "handlGetDataFileRequest " + e.getMessage());
1036
			e.printStackTrace(System.out);
1037
		}//catch
1038

    
1039
	}
1040

    
1041
	/**
1042
	 * Sends a document to a remote host
1043
	 */
1044
	protected static void handleGetDocumentRequest(PrintWriter out,
1045
			Hashtable<String, String[]> params, HttpServletResponse response) {
1046

    
1047
		String urlString = null;
1048
		String documentPath = null;
1049
		try {
1050
			// try to open a https stream to test if the request server's public
1051
			// key
1052
			// in the key store, this is security issue
1053
			String server = params.get("server")[0];
1054
			urlString = "https://" + server + "?server="
1055
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test";
1056
			URL u = new URL(urlString);
1057
			String test = ReplicationService.getURLContent(u);
1058
			// couldn't pass the test
1059
			if (test.indexOf("successfully") == -1) {
1060
				response.setContentType("text/xml");
1061
				out.println("<error>Couldn't pass the trust test " + test + " </error>");
1062
				out.close();
1063
				return;
1064
			}
1065

    
1066
			String docid = params.get("docid")[0];
1067
			logReplication.debug("ReplicationService.handleGetDocumentRequest - MetacatReplication.handleGetDocumentRequest for docid: "
1068
					+ docid);
1069
			DocumentImpl di = new DocumentImpl(docid);
1070

    
1071
			String documentDir = PropertyService
1072
					.getProperty("application.documentfilepath");
1073
			documentPath = documentDir + FileUtil.getFS() + docid;
1074

    
1075
			// if the document does not exist on disk, read it from db and write
1076
			// it to disk.
1077
			if (FileUtil.getFileStatus(documentPath) == FileUtil.DOES_NOT_EXIST
1078
					|| FileUtil.getFileSize(documentPath) == 0) {
1079
				FileWriter fileWriter = new FileWriter(documentPath);
1080
				di.toXml(fileWriter, null, null, true);
1081
			}
1082

    
1083
			// read the file from disk and sent it to PrintWriter
1084
			// PrintWriter out = new PrintWriter(streamOut);
1085
			di.readFromFileSystem(out, null, null, documentPath);
1086

    
1087
			// response.setContentType("text/xml");
1088
			// out.print(di.toString(null, null, true));
1089

    
1090
			logReplication.info("ReplicationService.handleGetDocumentRequest - document " + docid + " sent");
1091

    
1092
		} catch (MalformedURLException mue) {
1093
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1094
			logReplication.error("ReplicationService.handleGetDocumentRequest - Url error when getting document from MetacatReplication."
1095
					+ "handlGetDocumentRequest for url: " + urlString + " : "
1096
					+ mue.getMessage());
1097
			// e.printStackTrace(System.out);
1098
			response.setContentType("text/xml");
1099
			out.println("<error>" + mue.getMessage() + "</error>");
1100
		} catch (IOException ioe) {
1101
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1102
			logReplication.error("ReplicationService.handleGetDocumentRequest - I/O error when getting document from MetacatReplication."
1103
					+ "handlGetDocumentRequest for file: " + documentPath + " : "
1104
					+ ioe.getMessage());
1105
			// e.printStackTrace(System.out);
1106
			response.setContentType("text/xml");
1107
			out.println("<error>" + ioe.getMessage() + "</error>");
1108
		} catch (PropertyNotFoundException pnfe) {
1109
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1110
			logReplication
1111
					.error("ReplicationService.handleGetDocumentRequest - Error getting property when getting document from MetacatReplication."
1112
							+ "handlGetDocumentRequest for file: "
1113
							+ documentPath
1114
							+ " : "
1115
							+ pnfe.getMessage());
1116
			// e.printStackTrace(System.out);
1117
			response.setContentType("text/xml");
1118
			out.println("<error>" + pnfe.getMessage() + "</error>");
1119
		} catch (McdbException me) {
1120
			logReplication
1121
					.error("ReplicationService.handleGetDocumentRequest - Document implementation error  getting property when getting document from MetacatReplication."
1122
							+ "handlGetDocumentRequest for file: "
1123
							+ documentPath
1124
							+ " : "
1125
							+ me.getMessage());
1126
			// e.printStackTrace(System.out);
1127
			response.setContentType("text/xml");
1128
			out.println("<error>" + me.getMessage() + "</error>");
1129
		}
1130

    
1131
	}
1132

    
1133
	/**
1134
	 * Sends a list of all of the documents on this sever along with their
1135
	 * revision numbers. The format is: <!ELEMENT replication (server, updates)>
1136
	 * <!ELEMENT server (#PCDATA)> <!ELEMENT updates ((updatedDocument |
1137
	 * deleteDocument | revisionDocument)*)> <!ELEMENT updatedDocument (docid,
1138
	 * rev, datafile*)> <!ELEMENT deletedDocument (docid, rev)> <!ELEMENT
1139
	 * revisionDocument (docid, rev, datafile*)> <!ELEMENT docid (#PCDATA)>
1140
	 * <!ELEMENT rev (#PCDATA)> <!ELEMENT datafile (#PCDATA)> note that the rev
1141
	 * in deletedDocument is always empty. I just left it in there to make the
1142
	 * parser implementation easier.
1143
	 */
1144
	protected static void handleUpdateRequest(PrintWriter out, Hashtable<String, String[]> params,
1145
			HttpServletResponse response) {
1146
		// Checked out DBConnection
1147
		DBConnection dbConn = null;
1148
		// DBConenction serial number when checked it out
1149
		int serialNumber = -1;
1150
		PreparedStatement pstmt = null;
1151
		// Server list to store server info of xml_replication table
1152
		ReplicationServerList serverList = null;
1153

    
1154
		try {
1155
			// Check out a DBConnection from pool
1156
			dbConn = DBConnectionPool
1157
					.getDBConnection("MetacatReplication.handleUpdateRequest");
1158
			serialNumber = dbConn.getCheckOutSerialNumber();
1159
			// Create a server list from xml_replication table
1160
			serverList = new ReplicationServerList();
1161

    
1162
			// Get remote server name from param
1163
			String server = ((String[]) params.get("server"))[0];
1164
			// If no servr name in param, return a error
1165
			if (server == null || server.equals("")) {
1166
				response.setContentType("text/xml");
1167
				out.println("<error>Request didn't specify server name</error>");
1168
				out.close();
1169
				return;
1170
			}//if
1171

    
1172
			//try to open a https stream to test if the request server's public key
1173
			//in the key store, this is security issue
1174
			URL u = new URL("https://" + server + "?server="
1175
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test");
1176
			String test = ReplicationService.getURLContent(u);
1177
			//couldn't pass the test
1178
			if (test.indexOf("successfully") == -1) {
1179
				response.setContentType("text/xml");
1180
				out.println("<error>Couldn't pass the trust test</error>");
1181
				out.close();
1182
				return;
1183
			}
1184

    
1185
			// Check if local host configure to replicate xml documents to remote
1186
			// server. If not send back a error message
1187
			if (!serverList.getReplicationValue(server)) {
1188
				response.setContentType("text/xml");
1189
				out
1190
						.println("<error>Configuration not allow to replicate document to you</error>");
1191
				out.close();
1192
				return;
1193
			}//if
1194

    
1195
			// Store the sql command
1196
			StringBuffer docsql = new StringBuffer();
1197
			StringBuffer revisionSql = new StringBuffer();
1198
			// Stroe the docid list
1199
			StringBuffer doclist = new StringBuffer();
1200
			// Store the deleted docid list
1201
			StringBuffer delsql = new StringBuffer();
1202
			// Store the data set file
1203
			Vector<Vector<String>> packageFiles = new Vector<Vector<String>>();
1204

    
1205
			// Append local server's name and replication servlet to doclist
1206
			doclist.append("<?xml version=\"1.0\"?><replication>");
1207
			doclist.append("<server>")
1208
					.append(MetacatUtil.getLocalReplicationServerName());
1209
			//doclist.append(util.getProperty("replicationpath"));
1210
			doclist.append("</server><updates>");
1211

    
1212
			// Get correct docid that reside on this server according the requesting
1213
			// server's replicate and data replicate value in xml_replication table
1214
			docsql.append(DatabaseService.getInstance().getDBAdapter().getReplicationDocumentListSQL());
1215
			//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)) ");
1216
			revisionSql.append("select docid, rev, doctype from xml_revisions ");
1217
			// If the localhost is not a hub to the remote server, only replicate
1218
			// the docid' which home server is local host (server_location =1)
1219
			if (!serverList.getHubValue(server)) {
1220
				String serverLocationDoc = " and a.server_location = 1";
1221
				String serverLocationRev = "where server_location = 1";
1222
				docsql.append(serverLocationDoc);
1223
				revisionSql.append(serverLocationRev);
1224
			}
1225
			logReplication.info("ReplicationService.handleUpdateRequest - Doc sql: " + docsql.toString());
1226

    
1227
			// Get any deleted documents
1228
			delsql.append("select distinct docid from ");
1229
			delsql.append("xml_revisions where docid not in (select docid from ");
1230
			delsql.append("xml_documents) ");
1231
			// If the localhost is not a hub to the remote server, only replicate
1232
			// the docid' which home server is local host (server_location =1)
1233
			if (!serverList.getHubValue(server)) {
1234
				delsql.append("and server_location = 1");
1235
			}
1236
			logReplication.info("ReplicationService.handleUpdateRequest - Deleted sql: " + delsql.toString());
1237

    
1238
			// Get docid list of local host
1239
			pstmt = dbConn.prepareStatement(docsql.toString());
1240
			pstmt.execute();
1241
			ResultSet rs = pstmt.getResultSet();
1242
			boolean tablehasrows = rs.next();
1243
			//If metacat configed to replicate data file
1244
			//if ((util.getProperty("replicationsenddata")).equals("on"))
1245
			boolean replicateData = serverList.getDataReplicationValue(server);
1246
			if (replicateData) {
1247
				while (tablehasrows) {
1248
					String recordDoctype = rs.getString(3);
1249
					Vector<String> packagedoctypes = MetacatUtil
1250
							.getOptionList(PropertyService
1251
									.getProperty("xml.packagedoctype"));
1252
					//if this is a package file, put it at the end
1253
					//because if a package file is read before all of the files it
1254
					//refers to are loaded then there is an error
1255
					if (recordDoctype != null && !packagedoctypes.contains(recordDoctype)) {
1256
						//If this is not data file
1257
						if (!recordDoctype.equals("BIN")) {
1258
							//for non-data file document
1259
							doclist.append("<updatedDocument>");
1260
							doclist.append("<docid>").append(rs.getString(1));
1261
							doclist.append("</docid><rev>").append(rs.getInt(2));
1262
							doclist.append("</rev>");
1263
							doclist.append("</updatedDocument>");
1264
						}//if
1265
						else {
1266
							//for data file document, in datafile attributes
1267
							//we put "datafile" value there
1268
							doclist.append("<updatedDocument>");
1269
							doclist.append("<docid>").append(rs.getString(1));
1270
							doclist.append("</docid><rev>").append(rs.getInt(2));
1271
							doclist.append("</rev>");
1272
							doclist.append("<datafile>");
1273
							doclist.append(PropertyService
1274
									.getProperty("replication.datafileflag"));
1275
							doclist.append("</datafile>");
1276
							doclist.append("</updatedDocument>");
1277
						}//else
1278
					}//if packagedoctpes
1279
					else { //the package files are saved to be put into the xml later.
1280
						Vector<String> v = new Vector<String>();
1281
						v.add(rs.getString(1));
1282
						v.add(String.valueOf(rs.getInt(2)));
1283
						packageFiles.add(v);
1284
					}//esle
1285
					tablehasrows = rs.next();
1286
				}//while
1287
			}//if
1288
			else //metacat was configured not to send data file
1289
			{
1290
				while (tablehasrows) {
1291
					String recordDoctype = rs.getString(3);
1292
					if (!recordDoctype.equals("BIN")) { //don't replicate data files
1293
						Vector<String> packagedoctypes = MetacatUtil
1294
								.getOptionList(PropertyService
1295
										.getProperty("xml.packagedoctype"));
1296
						if (recordDoctype != null
1297
								&& !packagedoctypes.contains(recordDoctype)) { //if this is a package file, put it at the end
1298
							//because if a package file is read before all of the files it
1299
							//refers to are loaded then there is an error
1300
							doclist.append("<updatedDocument>");
1301
							doclist.append("<docid>").append(rs.getString(1));
1302
							doclist.append("</docid><rev>").append(rs.getInt(2));
1303
							doclist.append("</rev>");
1304
							doclist.append("</updatedDocument>");
1305
						} else { //the package files are saved to be put into the xml later.
1306
							Vector<String> v = new Vector<String>();
1307
							v.add(rs.getString(1));
1308
							v.add(String.valueOf(rs.getInt(2)));
1309
							packageFiles.add(v);
1310
						}
1311
					}//if
1312
					tablehasrows = rs.next();
1313
				}//while
1314
			}//else
1315

    
1316
			pstmt = dbConn.prepareStatement(delsql.toString());
1317
			//usage count should increas 1
1318
			dbConn.increaseUsageCount(1);
1319

    
1320
			pstmt.execute();
1321
			rs = pstmt.getResultSet();
1322
			tablehasrows = rs.next();
1323
			while (tablehasrows) { //handle the deleted documents
1324
				doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1325
				doclist.append("</docid><rev></rev></deletedDocument>");
1326
				//note that rev is always empty for deleted docs
1327
				tablehasrows = rs.next();
1328
			}
1329

    
1330
			//now we can put the package files into the xml results
1331
			for (int i = 0; i < packageFiles.size(); i++) {
1332
				Vector<String> v = packageFiles.elementAt(i);
1333
				doclist.append("<updatedDocument>");
1334
				doclist.append("<docid>").append(v.elementAt(0));
1335
				doclist.append("</docid><rev>");
1336
				doclist.append(v.elementAt(1));
1337
				doclist.append("</rev>");
1338
				doclist.append("</updatedDocument>");
1339
			}
1340
			// add revision doc list  
1341
			doclist.append(prepareRevisionDoc(dbConn, revisionSql.toString(),
1342
					replicateData));
1343

    
1344
			doclist.append("</updates></replication>");
1345
			logReplication.info("ReplicationService.handleUpdateRequest - doclist: " + doclist.toString());
1346
			pstmt.close();
1347
			//conn.close();
1348
			response.setContentType("text/xml");
1349
			out.println(doclist.toString());
1350

    
1351
		} catch (Exception e) {
1352
			logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1353
			logReplication.error("ReplicationService.handleUpdateRequest - error in MetacatReplication." + "handleupdaterequest: "
1354
					+ e.getMessage());
1355
			//e.printStackTrace(System.out);
1356
			response.setContentType("text/xml");
1357
			out.println("<error>" + e.getMessage() + "</error>");
1358
		} finally {
1359
			try {
1360
				pstmt.close();
1361
			}//try
1362
			catch (SQLException ee) {
1363
				logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1364
				logReplication.error("ReplicationService.handleUpdateRequest - Error in MetacatReplication."
1365
						+ "handleUpdaterequest to close pstmt: " + ee.getMessage());
1366
			}//catch
1367
			finally {
1368
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1369
			}//finally
1370
		}//finally
1371

    
1372
	}//handlUpdateRequest
1373

    
1374
	/*
1375
	 * This method will get the xml string for document in xml_revision
1376
	 * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1377
	 */
1378
	private static String prepareRevisionDoc(DBConnection dbConn, String revSql,
1379
			boolean replicateData) throws Exception {
1380
		logReplication.warn("ReplicationService.prepareRevisionDoc - The revision document sql is " + revSql);
1381
		StringBuffer revDocList = new StringBuffer();
1382
		PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1383
		//usage count should increas 1
1384
		dbConn.increaseUsageCount(1);
1385

    
1386
		pstmt.execute();
1387
		ResultSet rs = pstmt.getResultSet();
1388
		boolean tablehasrows = rs.next();
1389
		while (tablehasrows) {
1390
			String recordDoctype = rs.getString(3);
1391

    
1392
			//If this is data file and it isn't configured to replicate data
1393
			if (recordDoctype.equals("BIN") && !replicateData) {
1394
				// do nothing
1395
				continue;
1396
			} else {
1397

    
1398
				revDocList.append("<revisionDocument>");
1399
				revDocList.append("<docid>").append(rs.getString(1));
1400
				revDocList.append("</docid><rev>").append(rs.getInt(2));
1401
				revDocList.append("</rev>");
1402
				// data file
1403
				if (recordDoctype.equals("BIN")) {
1404
					revDocList.append("<datafile>");
1405
					revDocList.append(PropertyService
1406
							.getProperty("replication.datafileflag"));
1407
					revDocList.append("</datafile>");
1408
				}
1409
				revDocList.append("</revisionDocument>");
1410

    
1411
			}//else
1412
			tablehasrows = rs.next();
1413
		}
1414
		//System.out.println("The revision list is"+ revDocList.toString());
1415
		return revDocList.toString();
1416
	}
1417

    
1418
	/**
1419
	 * Returns the xml_catalog table encoded in xml
1420
	 */
1421
	public static String getCatalogXML() {
1422
		return handleGetCatalogRequest(null, null, null, false);
1423
	}
1424

    
1425
	/**
1426
	 * Sends the contents of the xml_catalog table encoded in xml
1427
	 * The xml format is:
1428
	 * <!ELEMENT xml_catalog (row*)>
1429
	 * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1430
	 *                system_id)>
1431
	 * All of the sub elements of row are #PCDATA
1432

    
1433
	 * If printFlag == false then do not print to out.
1434
	 */
1435
	protected static String handleGetCatalogRequest(PrintWriter out,
1436
			Hashtable<String, String[]> params, HttpServletResponse response,
1437
			boolean printFlag) {
1438
		DBConnection dbConn = null;
1439
		int serialNumber = -1;
1440
		PreparedStatement pstmt = null;
1441
		try {
1442
			/*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1443
			                                          "handleGetCatalogRequest");*/
1444
			dbConn = DBConnectionPool
1445
					.getDBConnection("MetacatReplication.handleGetCatalogRequest");
1446
			serialNumber = dbConn.getCheckOutSerialNumber();
1447
			pstmt = dbConn.prepareStatement("select entry_type, "
1448
					+ "source_doctype, target_doctype, public_id, "
1449
					+ "system_id from xml_catalog");
1450
			pstmt.execute();
1451
			ResultSet rs = pstmt.getResultSet();
1452
			boolean tablehasrows = rs.next();
1453
			StringBuffer sb = new StringBuffer();
1454
			sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1455
			while (tablehasrows) {
1456
				sb.append("<row><entry_type>").append(rs.getString(1));
1457
				sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1458
				sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1459
				sb.append("</target_doctype><public_id>").append(rs.getString(4));
1460
				// system id may not have server url on front.  Add it if not.
1461
				String systemID = rs.getString(5);
1462
				if (!systemID.startsWith("http://")) {
1463
					systemID = SystemUtil.getContextURL() + systemID;
1464
				}
1465
				sb.append("</public_id><system_id>").append(systemID);
1466
				sb.append("</system_id></row>");
1467

    
1468
				tablehasrows = rs.next();
1469
			}
1470
			sb.append("</xml_catalog>");
1471
			//conn.close();
1472
			if (printFlag) {
1473
				response.setContentType("text/xml");
1474
				out.println(sb.toString());
1475
			}
1476
			pstmt.close();
1477
			return sb.toString();
1478
		} catch (Exception e) {
1479
			logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1480
			logReplication.error("ReplicationService.handleGetCatalogRequest - error in MetacatReplication.handleGetCatalogRequest:"
1481
					+ e.getMessage());
1482
			e.printStackTrace(System.out);
1483
			if (printFlag) {
1484
				out.println("<error>" + e.getMessage() + "</error>");
1485
			}
1486
		} finally {
1487
			try {
1488
				pstmt.close();
1489
			}//try
1490
			catch (SQLException ee) {
1491
				logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1492
				logReplication.error("ReplicationService.handleGetCatalogRequest - Error in MetacatReplication.handleGetCatalogRequest: "
1493
						+ ee.getMessage());
1494
			}//catch
1495
			finally {
1496
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1497
			}//finally
1498
		}//finally
1499

    
1500
		return null;
1501
	}
1502

    
1503
	/**
1504
	 * Sends the current system date to the remote server.  Using this action
1505
	 * for replication gets rid of any problems with syncronizing clocks
1506
	 * because a time specific to a document is always kept on its home server.
1507
	 */
1508
	protected static void handleGetTimeRequest(PrintWriter out,
1509
			Hashtable<String, String[]> params, HttpServletResponse response) {
1510
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
1511
		java.util.Date localtime = new java.util.Date();
1512
		String dateString = formatter.format(localtime);
1513
		response.setContentType("text/xml");
1514

    
1515
		out.println("<timestamp>" + dateString + "</timestamp>");
1516
	}
1517

    
1518
	/**
1519
	 * this method handles the timeout for a file lock.  when a lock is
1520
	 * granted it is granted for 30 seconds.  When this thread runs out
1521
	 * it deletes the docid from the queue, thus eliminating the lock.
1522
	 */
1523
	public void run() {
1524
		try {
1525
			logReplication.info("ReplicationService.run - thread started for docid: "
1526
					+ (String) fileLocks.elementAt(0));
1527

    
1528
			Thread.sleep(30000); //the lock will expire in 30 seconds
1529
			logReplication.info("thread for docid: "
1530
					+ (String) fileLocks.elementAt(fileLocks.size() - 1) + " exiting.");
1531

    
1532
			fileLocks.remove(fileLocks.size() - 1);
1533
			//fileLocks is treated as a FIFO queue.  If there are more than one lock
1534
			//in the vector, the first one inserted will be removed.
1535
		} catch (Exception e) {
1536
			logMetacat.error("ReplicationService.run - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1537
			logReplication.error("ReplicationService.run - error in file lock thread from "
1538
					+ "MetacatReplication.run: " + e.getMessage());
1539
		}
1540
	}
1541

    
1542
	/**
1543
	 * Returns the name of a server given a serverCode
1544
	 * @param serverCode the serverid of the server
1545
	 * @return the servername or null if the specified serverCode does not
1546
	 *         exist.
1547
	 */
1548
	public static String getServerNameForServerCode(int serverCode) {
1549
		//System.out.println("serverid: " + serverCode);
1550
		DBConnection dbConn = null;
1551
		int serialNumber = -1;
1552
		PreparedStatement pstmt = null;
1553
		try {
1554
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServer");
1555
			serialNumber = dbConn.getCheckOutSerialNumber();
1556
			String sql = new String("select server from "
1557
					+ "xml_replication where serverid = " + serverCode);
1558
			pstmt = dbConn.prepareStatement(sql);
1559
			//System.out.println("getserver sql: " + sql);
1560
			pstmt.execute();
1561
			ResultSet rs = pstmt.getResultSet();
1562
			boolean tablehasrows = rs.next();
1563
			if (tablehasrows) {
1564
				//System.out.println("server: " + rs.getString(1));
1565
				return rs.getString(1);
1566
			}
1567

    
1568
			//conn.close();
1569
		} catch (Exception e) {
1570
			logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1571
			logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplication.getServer: " + e.getMessage());
1572
		} finally {
1573
			try {
1574
				pstmt.close();
1575
			}//try
1576
			catch (SQLException ee) {
1577
				logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1578
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacactReplication.getserver: "
1579
						+ ee.getMessage());
1580
			}//catch
1581
			finally {
1582
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1583
			}//fianlly
1584
		}//finally
1585

    
1586
		return null;
1587
		//return null if the server does not exist
1588
	}
1589

    
1590
	/**
1591
	 * Returns a server code given a server name
1592
	 * @param server the name of the server
1593
	 * @return integer > 0 representing the code of the server, 0 if the server
1594
	 *  does not exist.
1595
	 */
1596
	public static int getServerCodeForServerName(String server) throws ServiceException {
1597
		DBConnection dbConn = null;
1598
		int serialNumber = -1;
1599
		PreparedStatement pstmt = null;
1600
		int serverCode = 0;
1601

    
1602
		try {
1603

    
1604
			//conn = util.openDBConnection();
1605
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServerCode");
1606
			serialNumber = dbConn.getCheckOutSerialNumber();
1607
			pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication "
1608
					+ "WHERE server LIKE '" + server + "'");
1609
			pstmt.execute();
1610
			ResultSet rs = pstmt.getResultSet();
1611
			boolean tablehasrows = rs.next();
1612
			if (tablehasrows) {
1613
				serverCode = rs.getInt(1);
1614
				pstmt.close();
1615
				//conn.close();
1616
				return serverCode;
1617
			}
1618

    
1619
		} catch (SQLException sqle) {
1620
			throw new ServiceException("ReplicationService.getServerCodeForServerName - " 
1621
					+ "SQL error when getting server code: " + sqle.getMessage());
1622

    
1623
		} finally {
1624
			try {
1625
				pstmt.close();
1626
				//conn.close();
1627
			}//try
1628
			catch (Exception ee) {
1629
				logMetacat.error("ReplicationService.getServerCodeForServerName - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1630
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplicatio.getServerCode: "
1631
						+ ee.getMessage());
1632

    
1633
			}//catch
1634
			finally {
1635
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1636
			}//finally
1637
		}//finally
1638

    
1639
		return serverCode;
1640
	}
1641

    
1642
	/**
1643
	 * Method to get a host server information for given docid
1644
	 * @param conn a connection to the database
1645
	 */
1646
	public static Hashtable<String, String> getHomeServerInfoForDocId(String docId) {
1647
		Hashtable<String, String> sl = new Hashtable<String, String>();
1648
		DBConnection dbConn = null;
1649
		int serialNumber = -1;
1650
		docId = DocumentUtil.getDocIdFromString(docId);
1651
		PreparedStatement pstmt = null;
1652
		int serverLocation;
1653
		try {
1654
			//get conection
1655
			dbConn = DBConnectionPool.getDBConnection("ReplicationHandler.getHomeServer");
1656
			serialNumber = dbConn.getCheckOutSerialNumber();
1657
			//get a server location from xml_document table
1658
			pstmt = dbConn.prepareStatement("select server_location from xml_documents "
1659
					+ "where docid = ?");
1660
			pstmt.setString(1, docId);
1661
			pstmt.execute();
1662
			ResultSet serverName = pstmt.getResultSet();
1663
			//get a server location
1664
			if (serverName.next()) {
1665
				serverLocation = serverName.getInt(1);
1666
				pstmt.close();
1667
			} else {
1668
				pstmt.close();
1669
				//ut.returnConnection(conn);
1670
				return null;
1671
			}
1672
			pstmt = dbConn.prepareStatement("select server, last_checked, replicate "
1673
					+ "from xml_replication where serverid = ?");
1674
			//increase usage count
1675
			dbConn.increaseUsageCount(1);
1676
			pstmt.setInt(1, serverLocation);
1677
			pstmt.execute();
1678
			ResultSet rs = pstmt.getResultSet();
1679
			boolean tableHasRows = rs.next();
1680
			if (tableHasRows) {
1681

    
1682
				String server = rs.getString(1);
1683
				String last_checked = rs.getString(2);
1684
				if (!server.equals("localhost")) {
1685
					sl.put(server, last_checked);
1686
				}
1687

    
1688
			} else {
1689
				pstmt.close();
1690
				//ut.returnConnection(conn);
1691
				return null;
1692
			}
1693
			pstmt.close();
1694
		} catch (Exception e) {
1695
			logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1696
			logReplication.error("ReplicationService.getHomeServerInfoForDocId - error in replicationHandler.getHomeServer(): "
1697
					+ e.getMessage());
1698
		} finally {
1699
			try {
1700
				pstmt.close();
1701
				//ut.returnConnection(conn);
1702
			} catch (Exception ee) {
1703
				logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1704
				logReplication.error("ReplicationService.getHomeServerInfoForDocId - Eror irn rplicationHandler.getHomeServer() "
1705
						+ "to close pstmt: " + ee.getMessage());
1706
			} finally {
1707
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1708
			}
1709

    
1710
		}//finally
1711
		return sl;
1712
	}
1713

    
1714
	/**
1715
	 * Returns a home server location  given a accnum
1716
	 * @param accNum , given accNum for a document
1717
	 *
1718
	 */
1719
	public static int getHomeServerCodeForDocId(String accNum) throws ServiceException {
1720
		DBConnection dbConn = null;
1721
		int serialNumber = -1;
1722
		PreparedStatement pstmt = null;
1723
		int serverCode = 1;
1724
		String docId = DocumentUtil.getDocIdFromString(accNum);
1725

    
1726
		try {
1727

    
1728
			// Get DBConnection
1729
			dbConn = DBConnectionPool
1730
					.getDBConnection("ReplicationHandler.getServerLocation");
1731
			serialNumber = dbConn.getCheckOutSerialNumber();
1732
			pstmt = dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1733
					+ "WHERE docid LIKE '" + docId + "'");
1734
			pstmt.execute();
1735
			ResultSet rs = pstmt.getResultSet();
1736
			boolean tablehasrows = rs.next();
1737
			//If a document is find, return the server location for it
1738
			if (tablehasrows) {
1739
				serverCode = rs.getInt(1);
1740
				pstmt.close();
1741
				//conn.close();
1742
				return serverCode;
1743
			}
1744
			//if couldn't find in xml_documents table, we think server code is 1
1745
			//(this is new document)
1746
			else {
1747
				pstmt.close();
1748
				//conn.close();
1749
				return serverCode;
1750
			}
1751

    
1752
		} catch (SQLException sqle) {
1753
			throw new ServiceException("ReplicationService.getHomeServerCodeForDocId - " 
1754
					+ "SQL error when getting home server code for docid: " + docId + " : " 
1755
					+ sqle.getMessage());
1756

    
1757
		} finally {
1758
			try {
1759
				pstmt.close();
1760
				//conn.close();
1761

    
1762
			} catch (SQLException sqle) {
1763
				logMetacat.error("ReplicationService.getHomeServerCodeForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1764
				logReplication.error("ReplicationService.getHomeServerCodeForDocId - ReplicationService.getHomeServerCodeForDocId - " 
1765
						+ "SQL error when getting home server code for docid: " + docId + " : " 
1766
						+ sqle.getMessage());
1767
			} finally {
1768
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1769
			}//finally
1770
		}//finally
1771
		//return serverCode;
1772
	}
1773

    
1774
	/**
1775
	 * This method returns the content of a url
1776
	 * @param u the url to return the content from
1777
	 * @return a string representing the content of the url
1778
	 * @throws java.io.IOException
1779
	 */
1780
	public static String getURLContent(URL u) throws java.io.IOException {
1781
		char istreamChar;
1782
		int istreamInt;
1783
		logReplication.debug("ReplicationService.getURLContent - Before open the stream" + u.toString());
1784
		InputStream input = u.openStream();
1785
		logReplication.debug("ReplicationService.getURLContent - After open the stream" + u.toString());
1786
		InputStreamReader istream = new InputStreamReader(input);
1787
		StringBuffer serverResponse = new StringBuffer();
1788
		while ((istreamInt = istream.read()) != -1) {
1789
			istreamChar = (char) istreamInt;
1790
			serverResponse.append(istreamChar);
1791
		}
1792
		istream.close();
1793
		input.close();
1794

    
1795
		return serverResponse.toString();
1796
	}
1797

    
1798
//	/**
1799
//	 * Method for writing replication messages to a log file specified in
1800
//	 * metacat.properties
1801
//	 */
1802
//	public static void replLog(String message) {
1803
//		try {
1804
//			FileOutputStream fos = new FileOutputStream(PropertyService
1805
//					.getProperty("replication.logdir")
1806
//					+ "/metacatreplication.log", true);
1807
//			PrintWriter pw = new PrintWriter(fos);
1808
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
1809
//			java.util.Date localtime = new java.util.Date();
1810
//			String dateString = formatter.format(localtime);
1811
//			dateString += " :: " + message;
1812
//			// time stamp each entry
1813
//			pw.println(dateString);
1814
//			pw.flush();
1815
//		} catch (Exception e) {
1816
//			logReplication.error("error writing to replication log from "
1817
//					+ "MetacatReplication.replLog: " + e.getMessage());
1818
//			// e.printStackTrace(System.out);
1819
//		}
1820
//	}
1821

    
1822
//	/**
1823
//	 * Method for writing replication messages to a log file specified in
1824
//	 * metacat.properties
1825
//	 */
1826
//	public static void replErrorLog(String message) {
1827
//		try {
1828
//			FileOutputStream fos = new FileOutputStream(PropertyService
1829
//					.getProperty("replication.logdir")
1830
//					+ "/metacatreplicationerror.log", true);
1831
//			PrintWriter pw = new PrintWriter(fos);
1832
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
1833
//			java.util.Date localtime = new java.util.Date();
1834
//			String dateString = formatter.format(localtime);
1835
//			dateString += " :: " + message;
1836
//			//time stamp each entry
1837
//			pw.println(dateString);
1838
//			pw.flush();
1839
//		} catch (Exception e) {
1840
//			logReplication.error("error writing to replication error log from "
1841
//					+ "MetacatReplication.replErrorLog: " + e.getMessage());
1842
//			//e.printStackTrace(System.out);
1843
//		}
1844
//	}
1845

    
1846
	/**
1847
	 * Returns true if the replicate field for server in xml_replication is 1.
1848
	 * Returns false otherwise
1849
	 */
1850
	public static boolean replToServer(String server) {
1851
		DBConnection dbConn = null;
1852
		int serialNumber = -1;
1853
		PreparedStatement pstmt = null;
1854
		try {
1855
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.repltoServer");
1856
			serialNumber = dbConn.getCheckOutSerialNumber();
1857
			pstmt = dbConn.prepareStatement("select replicate from "
1858
					+ "xml_replication where server like '" + server + "'");
1859
			pstmt.execute();
1860
			ResultSet rs = pstmt.getResultSet();
1861
			boolean tablehasrows = rs.next();
1862
			if (tablehasrows) {
1863
				int i = rs.getInt(1);
1864
				if (i == 1) {
1865
					pstmt.close();
1866
					//conn.close();
1867
					return true;
1868
				} else {
1869
					pstmt.close();
1870
					//conn.close();
1871
					return false;
1872
				}
1873
			}
1874
		} catch (SQLException sqle) {
1875
			logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1876
			logReplication.error("ReplicationService.replToServer - SQL error in MetacatReplication.replToServer: "
1877
					+ sqle.getMessage());
1878
		} finally {
1879
			try {
1880
				pstmt.close();
1881
				//conn.close();
1882
			}//try
1883
			catch (Exception ee) {
1884
				logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1885
				logReplication.error("ReplicationService.replToServer - Error in MetacatReplication.replToServer: "
1886
						+ ee.getMessage());
1887
			}//catch
1888
			finally {
1889
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1890
			}//finally
1891
		}//finally
1892
		return false;
1893
		//the default if this server does not exist is to not replicate to it.
1894
	}
1895

    
1896
}
(6-6/7)