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: leinfelder $'
9
 *     '$Date: 2011-11-17 12:19:22 -0800 (Thu, 17 Nov 2011) $'
10
 * '$Revision: 6669 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

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

    
29
import java.io.BufferedInputStream;
30
import java.io.BufferedOutputStream;
31
import java.io.ByteArrayInputStream;
32
import java.io.ByteArrayOutputStream;
33
import java.io.File;
34
import java.io.FileInputStream;
35
import java.io.FileNotFoundException;
36
import java.io.FileOutputStream;
37
import java.io.IOException;
38
import java.io.InputStream;
39
import java.io.InputStreamReader;
40
import java.io.OutputStream;
41
import java.io.StringReader;
42
import java.io.Writer;
43
import java.net.MalformedURLException;
44
import java.net.URL;
45
import java.security.PrivateKey;
46
import java.security.cert.X509Certificate;
47
import java.sql.PreparedStatement;
48
import java.sql.ResultSet;
49
import java.sql.SQLException;
50
import java.sql.Timestamp;
51
import java.util.Calendar;
52
import java.util.Date;
53
import java.util.Hashtable;
54
import java.util.List;
55
import java.util.Timer;
56
import java.util.Vector;
57

    
58
import javax.servlet.http.HttpServletRequest;
59
import javax.servlet.http.HttpServletResponse;
60

    
61
import org.apache.http.HttpResponse;
62
import org.apache.http.conn.scheme.Scheme;
63
import org.apache.http.conn.ssl.SSLSocketFactory;
64
import org.apache.log4j.Logger;
65
import org.dataone.client.RestClient;
66
import org.dataone.client.auth.CertificateManager;
67
import org.dataone.service.types.v1.SystemMetadata;
68
import org.dataone.service.util.DateTimeMarshaller;
69
import org.dataone.service.util.TypeMarshaller;
70
import org.xml.sax.InputSource;
71
import org.xml.sax.SAXException;
72
import org.xml.sax.XMLReader;
73

    
74
import edu.ucsb.nceas.metacat.DocInfoHandler;
75
import edu.ucsb.nceas.metacat.DocumentImpl;
76
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
77
import edu.ucsb.nceas.metacat.EventLog;
78
import edu.ucsb.nceas.metacat.IdentifierManager;
79
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
80
import edu.ucsb.nceas.metacat.McdbException;
81
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlException;
82
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
83
import edu.ucsb.nceas.metacat.accesscontrol.PermOrderException;
84
import edu.ucsb.nceas.metacat.accesscontrol.XMLAccessDAO;
85
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
86
import edu.ucsb.nceas.metacat.database.DBConnection;
87
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
88
import edu.ucsb.nceas.metacat.database.DatabaseService;
89
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
90
import edu.ucsb.nceas.metacat.properties.PropertyService;
91
import edu.ucsb.nceas.metacat.shared.BaseService;
92
import edu.ucsb.nceas.metacat.shared.HandlerException;
93
import edu.ucsb.nceas.metacat.shared.ServiceException;
94
import edu.ucsb.nceas.metacat.util.DocumentUtil;
95
import edu.ucsb.nceas.metacat.util.MetacatUtil;
96
import edu.ucsb.nceas.metacat.util.ReplicationUtil;
97
import edu.ucsb.nceas.metacat.util.SystemUtil;
98
import edu.ucsb.nceas.utilities.FileUtil;
99
import edu.ucsb.nceas.utilities.GeneralPropertyException;
100
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
101

    
102
public class ReplicationService extends BaseService {
103

    
104
	private static ReplicationService replicationService = null;
105

    
106
	private long timeInterval;
107
	private Date firstTime;
108
	private boolean timedReplicationIsOn = false;
109
	Timer replicationDaemon;
110
	private static Vector<String> fileLocks = new Vector<String>();
111
//	private Thread lockThread = null;
112
	public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
113
	private static String TIMEREPLICATION = "replication.timedreplication";
114
	private static String TIMEREPLICATIONINTERVAl ="replication.timedreplicationinterval";
115
	private static String FIRSTTIME = "replication.firsttimedreplication";
116
	private static final int TIMEINTERVALLIMIT = 7200000;
117
	public static final String REPLICATIONUSER = "replication";
118

    
119
	public static final String REPLICATION_LOG_FILE_NAME = "metacatreplication.log";
120
	public static String METACAT_REPL_ERROR_MSG = null;
121
	private static Logger logReplication = Logger.getLogger("ReplicationLogging");
122
	private static Logger logMetacat = Logger.getLogger(ReplicationService.class);
123

    
124
	private ReplicationService() throws ServiceException {
125
		_serviceName = "ReplicationService";
126
		
127
		initialize();
128
	}
129
	
130
	private void initialize() throws ServiceException {
131
				
132
		// initialize db connections to handle any update requests
133
		// deltaT = util.getProperty("replication.deltaT");
134
		// the default deltaT can be set from metacat.properties
135
		// create a thread to do the delta-T check but don't execute it yet
136
		replicationDaemon = new Timer(true);
137
		try {
138
			String replLogFile = PropertyService.getProperty("replication.logdir")
139
				+ FileUtil.getFS() + REPLICATION_LOG_FILE_NAME;
140
			METACAT_REPL_ERROR_MSG = "An error occurred in replication.  Please see the " +
141
				"replication log at: " + replLogFile;
142
			
143
			String timedRepIsOnStr = 
144
				PropertyService.getProperty("replication.timedreplication");
145
			timedReplicationIsOn = (new Boolean(timedRepIsOnStr)).booleanValue();
146
			logReplication.info("ReplicationService.initialize - The timed replication on is" + timedReplicationIsOn);
147

    
148
			String timeIntervalStr = 
149
				PropertyService.getProperty("replication.timedreplicationinterval");
150
			timeInterval = (new Long(timeIntervalStr)).longValue();
151
			logReplication.info("ReplicationService.initialize - The timed replication time Interval is " + timeInterval);
152

    
153
			String firstTimeStr = 
154
				PropertyService.getProperty("replication.firsttimedreplication");
155
			logReplication.info("ReplicationService.initialize - first replication time form property is " + firstTimeStr);
156
			firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
157

    
158
			logReplication.info("ReplicationService.initialize - After combine current time, the real first time is "
159
					+ firstTime.toString() + " minisec");
160

    
161
			// set up time replication if it is on
162
			if (timedReplicationIsOn) {
163
				replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(),
164
						firstTime, timeInterval);
165
				logReplication.info("ReplicationService.initialize - deltaT handler started with rate="
166
						+ timeInterval + " mini seconds at " + firstTime.toString());
167
			}
168

    
169
		} catch (PropertyNotFoundException pnfe) {
170
			throw new ServiceException(
171
					"ReplicationService.initialize - Property error while instantiating "
172
							+ "replication service: " + pnfe.getMessage());
173
		} catch (HandlerException he) {
174
			throw new ServiceException(
175
					"ReplicationService.initialize - Handler error while instantiating "
176
							+ "replication service" + he.getMessage());
177
		} 
178
	}
179

    
180
	/**
181
	 * Get the single instance of SessionService.
182
	 * 
183
	 * @return the single instance of SessionService
184
	 */
185
	public static ReplicationService getInstance() throws ServiceException {
186
		if (replicationService == null) {
187
			replicationService = new ReplicationService();
188
		}
189
		return replicationService;
190
	}
191

    
192
	public boolean refreshable() {
193
		return true;
194
	}
195

    
196
	protected void doRefresh() throws ServiceException {
197
		return;
198
	}
199
	
200
	public void stop() throws ServiceException{
201
		
202
	}
203

    
204
	public void stopReplication() throws ServiceException {
205
	      //stop the replication server
206
	      replicationDaemon.cancel();
207
	      replicationDaemon = new Timer(true);
208
	      timedReplicationIsOn = false;
209
	      try {
210
	    	  PropertyService.setProperty("replication.timedreplication", (new Boolean(timedReplicationIsOn)).toString());
211
	      } catch (GeneralPropertyException gpe) {
212
	    	  logReplication.warn("ReplicationService.stopReplication - Could not set replication.timedreplication property: " + gpe.getMessage());
213
	      }
214

    
215
	      logReplication.info("ReplicationService.stopReplication - deltaT handler stopped");
216
		return;
217
	}
218
	
219
	public void startReplication(Hashtable<String, String[]> params) throws ServiceException {
220

    
221
	       String firstTimeStr = "";
222
	      //start the replication server
223
	       if ( params.containsKey("rate") ) {
224
	        timeInterval = new Long(
225
	               new String(((String[])params.get("rate"))[0])).longValue();
226
	        if(timeInterval < TIMEINTERVALLIMIT) {
227
	            //deltaT<30 is a timing mess!
228
	            timeInterval = TIMEINTERVALLIMIT;
229
	            throw new ServiceException("Replication deltaT rate cannot be less than "+
230
	                    TIMEINTERVALLIMIT + " millisecs and system automatically setup the rate to "+TIMEINTERVALLIMIT);
231
	        }
232
	      } else {
233
	        timeInterval = TIMEINTERVALLIMIT ;
234
	      }
235
	      logReplication.info("ReplicationService.startReplication - New rate is: " + timeInterval + " mini seconds.");
236
	      if ( params.containsKey("firsttime"))
237
	      {
238
	         firstTimeStr = ((String[])params.get("firsttime"))[0];
239
	         try
240
	         {
241
	           firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
242
	           logReplication.info("ReplicationService.startReplication - The first time setting is "+firstTime.toString());
243
	         }
244
	         catch (HandlerException e)
245
	         {
246
	            throw new ServiceException(e.getMessage());
247
	         }
248
	         logReplication.warn("After combine current time, the real first time is "
249
	                                  +firstTime.toString()+" minisec");
250
	      }
251
	      else
252
	      {
253
	    	  logMetacat.error("ReplicationService.startReplication - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
254
	          logReplication.error("ReplicationService.startReplication - You should specify the first time " +
255
	                                  "to start a time replication");
256
	          return;
257
	      }
258
	      
259
	      timedReplicationIsOn = true;
260
	      try {
261
	      // save settings to property file
262
	      PropertyService.setProperty(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
263
	      // note we couldn't use firstTime object because it has date info
264
	      // we only need time info such as 10:00 PM
265
	      PropertyService.setProperty(FIRSTTIME, firstTimeStr);
266
	      PropertyService.setProperty(TIMEREPLICATIONINTERVAl, (new Long(timeInterval)).toString());
267
	      } catch (GeneralPropertyException gpe) {
268
	    	  logReplication.warn("ReplicationService.startReplication - Could not set property: " + gpe.getMessage());
269
	      }
270
	      replicationDaemon.cancel();
271
	      replicationDaemon = new Timer(true);
272
	      replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime,
273
	                                            timeInterval);
274
	      
275
	      logReplication.info("ReplicationService.startReplication - deltaT handler started with rate=" +
276
	                                    timeInterval + " milliseconds at " +firstTime.toString());
277

    
278
	}
279
	
280
	public void runOnce() throws ServiceException {
281
	      //updates this server exactly once
282
	      replicationDaemon.schedule(new ReplicationHandler(), 0);
283
	}
284

    
285
	/**
286
	 * This method can add, delete and list the servers currently included in
287
	 * xml_replication.
288
	 * action           subaction            other needed params
289
	 * ---------------------------------------------------------
290
	 * servercontrol    add                  server
291
	 * servercontrol    delete               server
292
	 * servercontrol    list
293
	 */
294
	public static void handleServerControlRequest(
295
			Hashtable<String, String[]> params, HttpServletResponse response) {
296
		String subaction = ((String[]) params.get("subaction"))[0];
297
		DBConnection dbConn = null;
298
		int serialNumber = -1;
299
		PreparedStatement pstmt = null;
300
		String replicate = null;
301
		String server = null;
302
		String dataReplicate = null;
303
		String systemMetadataReplicate = null;
304
		String hub = null;
305
		Writer out = null;
306
		try {
307
			response.setContentType("text/xml");
308
			out = response.getWriter();
309
			
310
			//conn = util.openDBConnection();
311
			dbConn = DBConnectionPool
312
					.getDBConnection("MetacatReplication.handleServerControlRequest");
313
			serialNumber = dbConn.getCheckOutSerialNumber();
314

    
315
			// add server to server list
316
			if (subaction.equals("add")) {
317
				replicate = ((String[]) params.get("replicate"))[0];
318
				server = ((String[]) params.get("server"))[0];
319

    
320
				//Get data replication value
321
				dataReplicate = ((String[]) params.get("datareplicate"))[0];
322
				//Get system metadata replication value
323
				systemMetadataReplicate = ((String[]) params.get("systemmetadatareplicate"))[0];
324
				//Get hub value
325
				hub = ((String[]) params.get("hub"))[0];
326

    
327
				Calendar cal = Calendar.getInstance();
328
                cal.set(1980, 1, 1);
329
				String sql = "INSERT INTO xml_replication "
330
						+ "(server, last_checked, replicate, datareplicate, systemmetadatareplicate, hub) "
331
						+ "VALUES (?,?,?,?,?,?)";
332
				
333
				pstmt = dbConn.prepareStatement(sql);
334
						
335
				pstmt.setString(1, server);
336
				pstmt.setTimestamp(2, new Timestamp(cal.getTimeInMillis()));
337
				pstmt.setInt(3, Integer.parseInt(replicate));
338
				pstmt.setInt(4, Integer.parseInt(dataReplicate));
339
				pstmt.setInt(5, Integer.parseInt(systemMetadataReplicate));
340
				pstmt.setInt(6, Integer.parseInt(hub));
341
				
342
				String sqlReport = "XMLAccessAccess.getXMLAccessForDoc - SQL: " + sql;
343
				sqlReport += " [" + server + "," + replicate + 
344
					"," + dataReplicate + "," + hub + "]";
345
				
346
				logMetacat.info(sqlReport);
347
				
348
				pstmt.execute();
349
				pstmt.close();
350
				dbConn.commit();
351
				out.write("Server " + server + " added");
352
				response.setContentType("text/html");
353
				out.write("<html><body><table border=\"1\">");
354
				out.write("<tr><td><b>server</b></td>");
355
				out.write("<td><b>last_checked</b></td>");
356
				out.write("<td><b>replicate</b></td>");
357
				out.write("<td><b>datareplicate</b></td>");
358
				out.write("<td><b>systemmetadatareplicate</b></td>");
359
				out.write("<td><b>hub</b></td></tr>");
360
				pstmt = dbConn.prepareStatement("SELECT serverid, server, last_checked, replicate, datareplicate, systemmetadatareplicate, hub FROM xml_replication");
361
				//increase dbconnection usage
362
				dbConn.increaseUsageCount(1);
363

    
364
				pstmt.execute();
365
				ResultSet rs = pstmt.getResultSet();
366
				boolean tablehasrows = rs.next();
367
				while (tablehasrows) {
368
					out.write("<tr><td>" + rs.getString(2) + "</td><td>");
369
					out.write(rs.getString(3) + "</td><td>");
370
					out.write(rs.getString(4) + "</td><td>");
371
					out.write(rs.getString(5) + "</td><td>");
372
					out.write(rs.getString(6) + "</td><td>");
373
					out.write(rs.getString(7) + "</td></tr>");
374

    
375
					tablehasrows = rs.next();
376
				}
377
				out.write("</table></body></html>");
378

    
379
				// download certificate with the public key on this server
380
				// and import it as a trusted certificate
381
				String certURL = ((String[]) params.get("certificate"))[0];
382
				if (certURL != null && !certURL.equals("")) {
383
					downloadCertificate(certURL);
384
				}
385

    
386
				// delete server from server list
387
			} else if (subaction.equals("delete")) {
388
				server = ((String[]) params.get("server"))[0];
389
				pstmt = dbConn.prepareStatement("DELETE FROM xml_replication "
390
						+ "WHERE server LIKE ?");
391
				pstmt.setString(1, server);
392
				pstmt.execute();
393
				pstmt.close();
394
				dbConn.commit();
395
				out.write("Server " + server + " deleted");
396
				response.setContentType("text/html");
397
				out.write("<html><body><table border=\"1\">");
398
				out.write("<tr><td><b>server</b></td>");
399
				out.write("<td><b>last_checked</b></td>");
400
				out.write("<td><b>replicate</b></td>");
401
				out.write("<td><b>datareplicate</b></td>");
402
				out.write("<td><b>systemmetadatareplicate</b></td>");
403
				out.write("<td><b>hub</b></td></tr>");
404

    
405
				pstmt = dbConn.prepareStatement("SELECT serverid, server, last_checked, replicate, datareplicate, systemmetadatareplicate, hub FROM xml_replication");
406
				//increase dbconnection usage
407
				dbConn.increaseUsageCount(1);
408
				pstmt.execute();
409
				ResultSet rs = pstmt.getResultSet();
410
				boolean tablehasrows = rs.next();
411
				while (tablehasrows) {
412
					out.write("<tr><td>" + rs.getString(2) + "</td><td>");
413
					out.write(rs.getString(3) + "</td><td>");
414
					out.write(rs.getString(4) + "</td><td>");
415
					out.write(rs.getString(5) + "</td><td>");
416
					out.write(rs.getString(6) + "</td><td>");
417
					out.write(rs.getString(7) + "</td></tr>");
418
					tablehasrows = rs.next();
419
				}
420
				out.write("</table></body></html>");
421

    
422
				// list servers in server list
423
			} else if (subaction.equals("list")) {
424
				response.setContentType("text/html");
425
				out.write("<html><body><table border=\"1\">");
426
				out.write("<tr><td><b>server</b></td>");
427
				out.write("<td><b>last_checked</b></td>");
428
				out.write("<td><b>replicate</b></td>");
429
				out.write("<td><b>datareplicate</b></td>");
430
				out.write("<td><b>systemmetadatareplicate</b></td>");
431
				out.write("<td><b>hub</b></td></tr>");
432
				pstmt = dbConn.prepareStatement("SELECT serverid, server, last_checked, replicate, datareplicate, systemmetadatareplicate, hub FROM xml_replication");
433
				pstmt.execute();
434
				ResultSet rs = pstmt.getResultSet();
435
				boolean tablehasrows = rs.next();
436
				while (tablehasrows) {
437
					out.write("<tr><td>" + rs.getString(2) + "</td><td>");
438
					out.write(rs.getString(3) + "</td><td>");
439
					out.write(rs.getString(4) + "</td><td>");
440
					out.write(rs.getString(5) + "</td><td>");
441
					out.write(rs.getString(6) + "</td><td>");
442
					out.write(rs.getString(7) + "</td></tr>");
443

    
444
					tablehasrows = rs.next();
445
				}
446
				out.write("</table></body></html>");
447
			} else {
448

    
449
				out.write("<error>Unkonwn subaction</error>");
450

    
451
			}
452
			pstmt.close();
453
			//conn.close();
454

    
455
		} catch (Exception e) {
456
			logMetacat.error("ReplicationService.handleServerControlRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
457
			logReplication.error("ReplicationService.handleServerControlRequest - Error in "
458
					+ "MetacatReplication.handleServerControlRequest " + e.getMessage());
459
			e.printStackTrace(System.out);
460
		} finally {
461
			try {
462
				pstmt.close();
463
			}//try
464
			catch (SQLException ee) {
465
				logMetacat.error("ReplicationService.handleServerControlRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
466
				logReplication.error("ReplicationService.handleServerControlRequest - Error in MetacatReplication.handleServerControlRequest to close pstmt "
467
						+ ee.getMessage());
468
			}//catch
469
			finally {
470
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
471
			}//finally
472
			if (out != null) {
473
				try {
474
					out.close();
475
				} catch (IOException e) {
476
					logMetacat.error(e.getMessage(), e);
477
				}
478
			}
479
		}//finally
480

    
481
	}
482

    
483
	// download certificate with the public key from certURL and
484
	// upload it onto this server; it then must be imported as a
485
	// trusted certificate
486
	private static void downloadCertificate(String certURL) throws FileNotFoundException,
487
			IOException, MalformedURLException, PropertyNotFoundException {
488

    
489
		// the path to be uploaded to
490
		String certPath = SystemUtil.getContextDir();
491

    
492
		// get filename from the URL of the certificate
493
		String filename = certURL;
494
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
495
		if (slash > -1) {
496
			filename = filename.substring(slash + 1);
497
		}
498

    
499
		// open file output strem to write the input into it
500
		File f = new File(certPath, filename);
501
		synchronized (f) {
502
			try {
503
				if (f.exists()) {
504
					throw new IOException("File already exist: " + f.getCanonicalFile());
505
					// if ( f.exists() && !f.canWrite() ) {
506
					// throw new IOException("Not writable: " +
507
					// f.getCanonicalFile());
508
				}
509
			} catch (SecurityException se) {
510
				// if a security manager exists,
511
				// its checkRead method is called for f.exist()
512
				// or checkWrite method is called for f.canWrite()
513
				throw se;
514
			}
515

    
516
			// create a buffered byte output stream
517
			// that uses a default-sized output buffer
518
			FileOutputStream fos = new FileOutputStream(f);
519
			BufferedOutputStream out = new BufferedOutputStream(fos);
520

    
521
			// this should be http url
522
			URL url = new URL(certURL);
523
			BufferedInputStream bis = null;
524
			try {
525
				bis = new BufferedInputStream(url.openStream());
526
				byte[] buf = new byte[4 * 1024]; // 4K buffer
527
				int b = bis.read(buf);
528
				while (b != -1) {
529
					out.write(buf, 0, b);
530
					b = bis.read(buf);
531
				}
532
			} finally {
533
				if (bis != null)
534
					bis.close();
535
			}
536
			// the input and the output streams must be closed
537
			bis.close();
538
			out.flush();
539
			out.close();
540
			fos.close();
541
		} // end of synchronized(f)
542
	}
543

    
544
	/**
545
	 * when a forcereplication request comes in, local host sends a read request
546
	 * to the requesting server (remote server) for the specified docid. Then
547
	 * store it in local database.
548
	 */
549
	protected static void handleForceReplicateRequest(
550
			Hashtable<String, String[]> params, HttpServletResponse response,
551
			HttpServletRequest request) {
552
		String server = ((String[]) params.get("server"))[0]; // the server that
553
		String docid = ((String[]) params.get("docid"))[0]; // sent the document
554
		String dbaction = "UPDATE"; // the default action is UPDATE
555
		//    boolean override = false;
556
		//    int serverCode = 1;
557
		DBConnection dbConn = null;
558
		int serialNumber = -1;
559
		String docName = null;
560

    
561
		try {
562
			//if the url contains a dbaction then the default action is overridden
563
			if (params.containsKey("dbaction")) {
564
				dbaction = ((String[]) params.get("dbaction"))[0];
565
				//serverCode = MetacatReplication.getServerCode(server);
566
				//override = true; //we are now overriding the default action
567
			}
568
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication request from: " + server);
569
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication docid: " + docid);
570
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication action: " + dbaction);
571
			// sending back read request to remote server
572
			URL u = new URL("https://" + server + "?server="
573
					+ MetacatUtil.getLocalReplicationServerName() + "&action=read&docid="
574
					+ docid);
575
			String xmldoc = ReplicationService.getURLContent(u);
576

    
577
			// get the document info from server
578
			URL docinfourl = new URL("https://" + server + "?server="
579
					+ MetacatUtil.getLocalReplicationServerName()
580
					+ "&action=getdocumentinfo&docid=" + docid);
581
			
582

    
583
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
584
			// strip out the system metadata portion
585
			String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
586
			docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);
587
		   	  
588
			//dih is the parser for the docinfo xml format
589
			DocInfoHandler dih = new DocInfoHandler();
590
			XMLReader docinfoParser = ReplicationHandler.initParser(dih);
591
			docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
592
			//      Hashtable<String,Vector<AccessControlForSingleFile>> docinfoHash = dih.getDocInfo();
593
			Hashtable<String, String> docinfoHash = dih.getDocInfo();
594
			
595
			// Get home server of this docid
596
			String homeServer = (String) docinfoHash.get("home_server");
597
			
598
			// process system metadata
599
			if (systemMetadataXML != null) {
600
				SystemMetadata sysMeta = 
601
					TypeMarshaller.unmarshalTypeFromStream(
602
							SystemMetadata.class,
603
							new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
604
				// need the guid-to-docid mapping
605
				IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), docid);
606
				// save the system metadata
607
				HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
608
			}
609
      
610
			// dates
611
			String createdDateString = docinfoHash.get("date_created");
612
			String updatedDateString = docinfoHash.get("date_updated");
613
			Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
614
			Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
615
		      
616
			logReplication.info("ReplicationService.handleForceReplicateRequest - homeServer: " + homeServer);
617
			// Get Document type
618
			String docType = (String) docinfoHash.get("doctype");
619
			logReplication.info("ReplicationService.handleForceReplicateRequest - docType: " + docType);
620
			String parserBase = null;
621
			// this for eml2 and we need user eml2 parser
622
			if (docType != null
623
					&& (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE)) {
624
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml200 document!");
625
				parserBase = DocumentImpl.EML200;
626
			} else if (docType != null
627
					&& (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE)) {
628
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml2.0.1 document!");
629
				parserBase = DocumentImpl.EML200;
630
			} else if (docType != null
631
					&& (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE)) {
632
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml2.1.0 document!");
633
				parserBase = DocumentImpl.EML210;
634
			} else if (docType != null
635
					&& (docType.trim()).equals(DocumentImpl.EML2_1_1NAMESPACE)) {
636
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml2.1.1 document!");
637
				parserBase = DocumentImpl.EML210;
638
			}
639
			logReplication.warn("ReplicationService.handleForceReplicateRequest - The parserBase is: " + parserBase);
640

    
641
			// Get DBConnection from pool
642
			dbConn = DBConnectionPool
643
					.getDBConnection("MetacatReplication.handleForceReplicateRequest");
644
			serialNumber = dbConn.getCheckOutSerialNumber();
645
			// write the document to local database
646
			DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
647
			//try this independently so we can set access even if the update action is invalid (i.e docid has not changed)
648
			try {
649
				wrapper.writeReplication(dbConn, xmldoc, null, null,
650
						dbaction, docid, null, null, homeServer, server, createdDate,
651
						updatedDate);
652
			} finally {
653

    
654
				//process extra access rules before dealing with the write exception (doc exist already)			
655
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
656
		        if (accessControlList != null) {
657
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
658
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
659
		        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
660
		        			acfsf.insertPermissions(xmlAccessDAO);
661
							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
662
									+ " permissions added to DB");
663
		        		}
664
		            }
665
		        }
666
		        
667
		        // process the real owner and updater
668
				String user = (String) docinfoHash.get("user_owner");
669
				String updated = (String) docinfoHash.get("user_updated");
670
		        updateUserOwner(dbConn, docid, user, updated);
671

    
672
				logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid + " added to DB with "
673
						+ "action " + dbaction);
674
				
675
				EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), REPLICATIONUSER, docid, dbaction);
676
			}
677
		} catch (SQLException sqle) {
678
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
679
			logReplication.error("ReplicationService.handleForceReplicateRequest - SQL error when adding doc " + docid + 
680
					" to DB with action " + dbaction + ": " + sqle.getMessage());
681
		} catch (MalformedURLException mue) {
682
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
683
			logReplication.error("ReplicationService.handleForceReplicateRequest - URL error when adding doc " + docid + 
684
					" to DB with action " + dbaction + ": " + mue.getMessage());
685
		} catch (SAXException se) {
686
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
687
			logReplication.error("ReplicationService.handleForceReplicateRequest - SAX parsing error when adding doc " + docid + 
688
					" to DB with action " + dbaction + ": " + se.getMessage());
689
		} catch (HandlerException he) {
690
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
691
			logReplication.error("ReplicationService.handleForceReplicateRequest - Handler error when adding doc " + docid + 
692
					" to DB with action " + dbaction + ": " + he.getMessage());
693
		} catch (IOException ioe) {
694
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
695
			logReplication.error("ReplicationService.handleForceReplicateRequest - I/O error when adding doc " + docid + 
696
					" to DB with action " + dbaction + ": " + ioe.getMessage());
697
		} catch (PermOrderException poe) {
698
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
699
			logReplication.error("ReplicationService.handleForceReplicateRequest - Permissions order error when adding doc " + docid + 
700
					" to DB with action " + dbaction + ": " + poe.getMessage());
701
		} catch (AccessControlException ace) {
702
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
703
			logReplication.error("ReplicationService.handleForceReplicateRequest - Permissions order error when adding doc " + docid + 
704
					" to DB with action " + dbaction + ": " + ace.getMessage());
705
		} catch (Exception e) {
706
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
707
			logReplication.error("ReplicationService.handleForceReplicateRequest - General error when adding doc " + docid + 
708
					" to DB with action " + dbaction + ": " + e.getMessage());
709
		} finally {
710
			// Return the checked out DBConnection
711
			DBConnectionPool.returnDBConnection(dbConn, serialNumber);
712
		}//finally
713
	}
714

    
715
	/*
716
	 * when a forcereplication delete request comes in, local host will delete this
717
	 * document
718
	 */
719
	protected static void handleForceReplicateDeleteRequest(
720
			Hashtable<String, String[]> params, HttpServletResponse response,
721
			HttpServletRequest request) {
722
		String server = ((String[]) params.get("server"))[0]; // the server that
723
		String docid = ((String[]) params.get("docid"))[0]; // sent the document
724
		try {
725
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete request from " + server);
726
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete docid " + docid);
727
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete request from: " + server);
728
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete docid: " + docid);
729
			DocumentImpl.delete(docid, null, null, server);
730
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
731
			EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), REPLICATIONUSER, docid,
732
					"delete");
733
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
734
		} catch (McdbDocNotFoundException e) {
735
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
736
			logReplication.error("document " + docid
737
					+ " failed to delete because " + e.getMessage());
738
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
739
		} catch (InsufficientKarmaException e) {
740
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
741
			logReplication.error("document " + docid
742
					+ " failed to delete because " + e.getMessage());
743
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
744
		} catch (SQLException e) {
745
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
746
			logReplication.error("document " + docid
747
					+ " failed to delete because " + e.getMessage());
748
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
749
		} catch (Exception e) {
750
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
751
			logReplication.error("document " + docid
752
					+ " failed to delete because " + e.getMessage());
753
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
754

    
755
		}//catch
756

    
757
	}
758

    
759
	/**
760
	 * when a forcereplication data file request comes in, local host sends a
761
	 * readdata request to the requesting server (remote server) for the specified
762
	 * docid. Then store it in local database and file system
763
	 */
764
	protected static void handleForceReplicateDataFileRequest(Hashtable<String, String[]> params,
765
			HttpServletRequest request) {
766

    
767
		//make sure there is some parameters
768
		if (params.isEmpty()) {
769
			return;
770
		}
771
		// Get remote server
772
		String server = ((String[]) params.get("server"))[0];
773
		// the docid should include rev number
774
		String docid = ((String[]) params.get("docid"))[0];
775
		// Make sure there is a docid and server
776
		if (docid == null || server == null || server.equals("")) {
777
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
778
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Didn't specify docid or server for replication");
779
			return;
780
		}
781

    
782
		// Overide or not
783
		//    boolean override = false;
784
		// dbaction - update or insert
785
		String dbaction = null;
786

    
787
		try {
788
			//docid was switch to two parts uinque code and rev
789
			//String uniqueCode=MetacatUtil.getDocIdFromString(docid);
790
			//int rev=MetacatUtil.getVersionFromString(docid);
791
			if (params.containsKey("dbaction")) {
792
				dbaction = ((String[]) params.get("dbaction"))[0];
793
			} else//default value is update
794
			{
795
				dbaction = "update";
796
			}
797

    
798
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication request from: " + server);
799
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication docid: " + docid);
800
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication action: " + dbaction);
801
			// get the document info from server
802
			URL docinfourl = new URL("https://" + server + "?server="
803
					+ MetacatUtil.getLocalReplicationServerName()
804
					+ "&action=getdocumentinfo&docid=" + docid);
805

    
806
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
807
			
808
			// strip out the system metadata portion
809
		    String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
810
		   	docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);
811

    
812
			//dih is the parser for the docinfo xml format
813
			DocInfoHandler dih = new DocInfoHandler();
814
			XMLReader docinfoParser = ReplicationHandler.initParser(dih);
815
			docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
816
			Hashtable<String, String> docinfoHash = dih.getDocInfo();
817
			
818
			String docName = (String) docinfoHash.get("docname");
819

    
820
			String docType = (String) docinfoHash.get("doctype");
821

    
822
			String docHomeServer = (String) docinfoHash.get("home_server");
823
			
824
			String createdDateString = docinfoHash.get("date_created");
825
			String updatedDateString = docinfoHash.get("date_updated");
826
			
827
			Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
828
			Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
829
			
830
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - docHomeServer of datafile: " + docHomeServer);
831

    
832
			if (dbaction.equals("insert") || dbaction.equals("update")) {
833
				//Get data file and store it into local file system.
834
				// sending back readdata request to server
835
				URL url = new URL("https://" + server + "?server="
836
						+ MetacatUtil.getLocalReplicationServerName()
837
						+ "&action=readdata&docid=" + docid);
838
				String datafilePath = PropertyService
839
						.getProperty("application.datafilepath");
840

    
841
				InputStream inputStream = getURLStream(url);
842
				
843
				Exception writeException = null;
844
				//register data file into xml_documents table and wite data file
845
				//into file system
846
				try {
847
					DocumentImpl.writeDataFileInReplication(inputStream,
848
							datafilePath, docName, docType, docid, null, docHomeServer,
849
							server, DocumentImpl.DOCUMENTTABLE, false, createdDate,
850
							updatedDate);
851
				} catch (Exception e) {
852
					writeException = e;
853
				}
854
				
855
				// process the real owner and updater
856
				DBConnection dbConn = DBConnectionPool.getDBConnection("ReplicationService.handleForceDataFileRequest");
857
		        int serialNumber = dbConn.getCheckOutSerialNumber();
858
		        dbConn.setAutoCommit(false);
859
				String user = (String) docinfoHash.get("user_owner");
860
				String updated = (String) docinfoHash.get("user_updated");
861
		        updateUserOwner(dbConn, docid, user, updated);
862
		        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
863
		        
864
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
865
		        if (accessControlList != null) {
866
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
867
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
868
		        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
869
		        			acfsf.insertPermissions(xmlAccessDAO);
870
							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
871
									+ " permissions added to DB");
872
		        		}
873
		            }
874
		        }
875
		        
876
		        // process system metadata
877
		        if (systemMetadataXML != null) {
878
		      	  SystemMetadata sysMeta = 
879
		      		TypeMarshaller.unmarshalTypeFromStream(
880
		      				  SystemMetadata.class, 
881
		      				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
882
		      	  // need the guid-to-docid mapping
883
		      	  IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), docid);
884
		      	  // save the system metadata
885
		      	  HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
886
		        }
887

    
888
				if (writeException != null) {
889
					throw writeException;
890
				}
891

    
892
				logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - datafile " + docid + " added to DB with "
893
						+ "action " + dbaction);
894
				EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), REPLICATIONUSER,
895
						docid, dbaction);
896
			}
897

    
898
		} catch (Exception e) {
899
			e.printStackTrace();
900
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG, e);                         
901
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Datafile " + docid
902
					+ " failed to added to DB with " + "action " + dbaction + " because "
903
					+ e.getMessage());
904
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - ERROR in MetacatReplication.handleForceDataFileReplicate"
905
					+ "Request(): " + e.getMessage());
906
		}
907
	}
908

    
909
	/**
910
	 * Grants or denies a lock to a requesting host.
911
	 * The servlet parameters of interrest are:
912
	 * docid: the docid of the file the lock is being requested for
913
	 * currentdate: the timestamp of the document on the remote server
914
	 *
915
	 */
916
	protected static void handleGetLockRequest(
917
			Hashtable<String, String[]> params, HttpServletResponse response) {
918

    
919
		try {
920

    
921
			String docid = ((String[]) params.get("docid"))[0];
922
			String remoteRev = ((String[]) params.get("updaterev"))[0];
923
			DocumentImpl requestDoc = new DocumentImpl(docid);
924
			logReplication.info("ReplicationService.handleGetLockRequest - lock request for " + docid);
925
			int localRevInt = requestDoc.getRev();
926
			int remoteRevInt = Integer.parseInt(remoteRev);
927

    
928
			// get a writer for sending back to response
929
			response.setContentType("text/xml");
930
			Writer out = response.getWriter();
931
			
932
			if (remoteRevInt >= localRevInt) {
933
				if (!fileLocks.contains(docid)) { //grant the lock if it is not already locked
934
					fileLocks.add(0, docid); //insert at the beginning of the queue Vector
935
					//send a message back to the the remote host authorizing the insert
936
					out.write("<lockgranted><docid>" + docid
937
									+ "</docid></lockgranted>");
938
					//          lockThread = new Thread(this);
939
					//          lockThread.setPriority(Thread.MIN_PRIORITY);
940
					//          lockThread.start();
941
					logReplication.info("ReplicationService.handleGetLockRequest - lock granted for " + docid);
942
				} else { //deny the lock
943
					out.write("<filelocked><docid>" + docid + "</docid></filelocked>");
944
					logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
945
							+ "reason: file already locked");
946
				}
947
			} else {//deny the lock.
948
				out.write("<outdatedfile><docid>" + docid + "</docid></filelocked>");
949
				logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
950
						+ "reason: client has outdated file");
951
			}
952
			out.close();
953
			//conn.close();
954
		} catch (Exception e) {
955
			logMetacat.error("ReplicationService.handleGetLockRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
956
			logReplication.error("ReplicationService.handleGetLockRequest - error requesting file lock from MetacatReplication."
957
					+ "handleGetLockRequest: " + e.getMessage());
958
			e.printStackTrace(System.out);
959
		}
960
	}
961

    
962
	/**
963
	 * Sends all of the xml_documents information encoded in xml to a requestor
964
	 * the format is:
965
	 * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
966
	 *                  user_updated, home_server, public_access, rev)/>
967
	 * all of the subelements of document info are #PCDATA
968
	 */
969
	protected static void handleGetDocumentInfoRequest(
970
			Hashtable<String, String[]> params, HttpServletResponse response) {
971
		String docid = ((String[]) (params.get("docid")))[0];
972
		StringBuffer sb = new StringBuffer();
973

    
974
		try {
975
			DocumentImpl doc = new DocumentImpl(docid);
976
			sb.append("<documentinfo><docid>").append(docid);
977
			sb.append("</docid>");
978
			
979
			try {
980
				// serialize the System Metadata as XML for docinfo
981
				String guid = IdentifierManager.getInstance().getGUID(doc.getDocID(), doc.getRev());
982
				SystemMetadata systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
983
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
984
				TypeMarshaller.marshalTypeToOutputStream(systemMetadata, baos);
985
				String systemMetadataXML = baos.toString("UTF-8");
986
				sb.append("<systemMetadata>");
987
				sb.append(systemMetadataXML);
988
				sb.append("</systemMetadata>");
989
			} catch(McdbDocNotFoundException e) {
990
			  logMetacat.warn("No SystemMetadata found for: " + docid);
991
			}
992
			
993
			Calendar created = Calendar.getInstance();
994
			created.setTime(doc.getCreateDate());
995
			Calendar updated = Calendar.getInstance();
996
			updated.setTime(doc.getUpdateDate());
997
			
998
			sb.append("<docname>").append(doc.getDocname());
999
			sb.append("</docname><doctype>").append(doc.getDoctype());
1000
			sb.append("</doctype>");
1001
			sb.append("<user_owner>").append(doc.getUserowner());
1002
			sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
1003
			sb.append("</user_updated>");
1004
			sb.append("<date_created>");
1005
			sb.append(DateTimeMarshaller.serializeDateToUTC(doc.getCreateDate()));
1006
			sb.append("</date_created>");
1007
			sb.append("<date_updated>");
1008
			sb.append(DateTimeMarshaller.serializeDateToUTC(doc.getUpdateDate()));
1009
			sb.append("</date_updated>");
1010
			sb.append("<home_server>");
1011
			sb.append(doc.getDocHomeServer());
1012
			sb.append("</home_server>");
1013
			sb.append("<public_access>").append(doc.getPublicaccess());
1014
			sb.append("</public_access><rev>").append(doc.getRev());
1015
			sb.append("</rev>");
1016

    
1017
			sb.append("<accessControl>");
1018

    
1019
			AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid); 
1020
			sb.append(acfsf.getAccessString());
1021
			
1022
			sb.append("</accessControl>");
1023

    
1024
			sb.append("</documentinfo>");
1025
			// get a writer for sending back to response
1026
			response.setContentType("text/xml");
1027
			Writer out = response.getWriter();
1028
			out.write(sb.toString());
1029
			out.close();
1030

    
1031
		} catch (Exception e) {
1032
			logMetacat.error("ReplicationService.handleGetDocumentInfoRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1033
			logReplication.error("ReplicationService.handleGetDocumentInfoRequest - error in metacatReplication.handlegetdocumentinforequest "
1034
					+ "for doc: " + docid + " : " + e.getMessage());
1035
		}
1036

    
1037
	}
1038
	
1039
	/**
1040
	 * Sends System Metadata as XML
1041
	 */
1042
	protected static void handleGetSystemMetadataRequest(
1043
			Hashtable<String, String[]> params, HttpServletResponse response) {
1044
		String guid = ((String[]) (params.get("guid")))[0];
1045
		String systemMetadataXML = null;
1046
		try {
1047
			
1048
			// serialize the System Metadata as XML 
1049
			SystemMetadata systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
1050
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
1051
			TypeMarshaller.marshalTypeToOutputStream(systemMetadata, baos);
1052
			systemMetadataXML = baos.toString("UTF-8");
1053
				
1054
			// get a writer for sending back to response
1055
			response.setContentType("text/xml");
1056
			Writer out = response.getWriter();
1057
			out.write(systemMetadataXML);
1058
			out.close();
1059

    
1060
		} catch (Exception e) {
1061
			String msg = "ReplicationService.handleGetSystemMetadataRequest for guid: " + guid + " : " + e.getMessage();
1062
			logMetacat.error(msg);                         
1063
			logReplication.error(msg);
1064
		}
1065

    
1066
	}
1067
	
1068
	/**
1069
	 * when a forcereplication request comes in, local host sends a read request
1070
	 * to the requesting server (remote server) for the specified docid. Then
1071
	 * store it in local database.
1072
	 */
1073
	protected static void handleForceReplicateSystemMetadataRequest(
1074
			Hashtable<String, String[]> params, HttpServletResponse response,
1075
			HttpServletRequest request) {
1076
		String server = ((String[]) params.get("server"))[0]; // the server that
1077
		String guid = ((String[]) params.get("guid"))[0]; // sent the document
1078
		
1079
		try {
1080
			logReplication.info("ReplicationService.handleForceReplicateSystemMetadataRequest - Force replication system metadata request from: " + server);
1081
			// get the system metadata from server
1082
			URL docinfourl = new URL("https://" + server + "?server="
1083
					+ MetacatUtil.getLocalReplicationServerName()
1084
					+ "&action=getsystemmetadata&guid=" + guid);
1085
			
1086
			String systemMetadataXML = ReplicationService.getURLContent(docinfourl);
1087
						
1088
			// process system metadata
1089
			if (systemMetadataXML != null) {
1090
				SystemMetadata sysMeta = 
1091
					TypeMarshaller.unmarshalTypeFromStream(
1092
							SystemMetadata.class,
1093
							new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
1094
				HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1095
			}
1096
      
1097
			logReplication.info("ReplicationService.handleForceReplicateSystemMetadataRequest - processed guid: " + guid);
1098
			EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), REPLICATIONUSER, guid, "systemMetadata");
1099

    
1100
		} catch (Exception e) {
1101
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG, e);                         
1102
			logReplication.error("ReplicationService.handleForceReplicateRequest - General error when processing guid: " + guid, e);
1103
		}
1104
	}
1105

    
1106
	/**
1107
	 * Sends a datafile to a remote host
1108
	 */
1109
	protected static void handleGetDataFileRequest(OutputStream outPut,
1110
			Hashtable<String, String[]> params, HttpServletResponse response)
1111

    
1112
	{
1113
		// File path for data file
1114
		String filepath;
1115
		// Request docid
1116
		String docId = ((String[]) (params.get("docid")))[0];
1117
		//check if the doicd is null
1118
		if (docId == null) {
1119
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1120
			logReplication.error("ReplicationService.handleGetDataFileRequest - Didn't specify docid for replication");
1121
			return;
1122
		}
1123

    
1124
		//try to open a https stream to test if the request server's public key
1125
		//in the key store, this is security issue
1126
		try {
1127
			filepath = PropertyService.getProperty("application.datafilepath");
1128
			String server = params.get("server")[0];
1129
			URL u = new URL("https://" + server + "?server="
1130
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test");
1131
			String test = ReplicationService.getURLContent(u);
1132
			//couldn't pass the test
1133
			if (test.indexOf("successfully") == -1) {
1134
				//response.setContentType("text/xml");
1135
				//outPut.println("<error>Couldn't pass the trust test</error>");
1136
				logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1137
				logReplication.error("ReplicationService.handleGetDataFileRequest - Couldn't pass the trust test");
1138
				return;
1139
			}
1140
		}//try
1141
		catch (Exception ee) {
1142
			return;
1143
		}//catch
1144

    
1145
		if (!filepath.endsWith("/")) {
1146
			filepath += "/";
1147
		}
1148
		// Get file aboslute file name
1149
		String filename = filepath + docId;
1150

    
1151
		//MIME type
1152
		String contentType = null;
1153
		if (filename.endsWith(".xml")) {
1154
			contentType = "text/xml";
1155
		} else if (filename.endsWith(".css")) {
1156
			contentType = "text/css";
1157
		} else if (filename.endsWith(".dtd")) {
1158
			contentType = "text/plain";
1159
		} else if (filename.endsWith(".xsd")) {
1160
			contentType = "text/xml";
1161
		} else if (filename.endsWith("/")) {
1162
			contentType = "text/html";
1163
		} else {
1164
			File f = new File(filename);
1165
			if (f.isDirectory()) {
1166
				contentType = "text/html";
1167
			} else {
1168
				contentType = "application/octet-stream";
1169
			}
1170
		}
1171

    
1172
		// Set the mime type
1173
		response.setContentType(contentType);
1174

    
1175
		// Get the content of the file
1176
		FileInputStream fin = null;
1177
		try {
1178
			// FileInputStream to metacat
1179
			fin = new FileInputStream(filename);
1180
			// 4K buffer
1181
			byte[] buf = new byte[4 * 1024];
1182
			// Read data from file input stream to byte array
1183
			int b = fin.read(buf);
1184
			// Write to outStream from byte array
1185
			while (b != -1) {
1186
				outPut.write(buf, 0, b);
1187
				b = fin.read(buf);
1188
			}
1189
			// close file input stream
1190
			fin.close();
1191

    
1192
		}//try
1193
		catch (Exception e) {
1194
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1195
			logReplication.error("ReplicationService.handleGetDataFileRequest - error getting data file from MetacatReplication."
1196
					+ "handlGetDataFileRequest " + e.getMessage());
1197
			e.printStackTrace(System.out);
1198
		}//catch
1199

    
1200
	}
1201

    
1202
	/**
1203
	 * Sends a document to a remote host
1204
	 */
1205
	protected static void handleGetDocumentRequest(
1206
			Hashtable<String, String[]> params, HttpServletResponse response) {
1207

    
1208
		String urlString = null;
1209
		String documentPath = null;
1210
		String errorMsg = null;
1211
		try {
1212
			// try to open a https stream to test if the request server's public
1213
			// key
1214
			// in the key store, this is security issue
1215
			String server = params.get("server")[0];
1216
			urlString = "https://" + server + "?server="
1217
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test";
1218
			URL u = new URL(urlString);
1219
			String test = ReplicationService.getURLContent(u);
1220
			// couldn't pass the test
1221
			if (test.indexOf("successfully") == -1) {
1222
				response.setContentType("text/xml");
1223
				Writer out = response.getWriter();
1224
				out.write("<error>Couldn't pass the trust test " + test + " </error>");
1225
				out.close();
1226
				return;
1227
			}
1228

    
1229
			String docid = params.get("docid")[0];
1230
			logReplication.debug("ReplicationService.handleGetDocumentRequest - MetacatReplication.handleGetDocumentRequest for docid: "
1231
					+ docid);
1232
			DocumentImpl di = new DocumentImpl(docid);
1233

    
1234
			String documentDir = PropertyService
1235
					.getProperty("application.documentfilepath");
1236
			documentPath = documentDir + FileUtil.getFS() + docid;
1237

    
1238
			// if the document does not exist on disk, read it from db and write
1239
			// it to disk.
1240
			if (FileUtil.getFileStatus(documentPath) == FileUtil.DOES_NOT_EXIST
1241
					|| FileUtil.getFileSize(documentPath) == 0) {
1242
				FileOutputStream fos = new FileOutputStream(documentPath);
1243
				di.toXml(fos, null, null, true);
1244
			}
1245

    
1246
			// read the file from disk and send it to outputstream
1247
			OutputStream outputStream = response.getOutputStream();
1248
			di.readFromFileSystem(outputStream, null, null, documentPath);
1249

    
1250
			logReplication.info("ReplicationService.handleGetDocumentRequest - document " + docid + " sent");
1251

    
1252
			// return to avoid continuing to the error reporting section at the end
1253
			return;
1254
			
1255
		} catch (MalformedURLException mue) {
1256
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1257
			logReplication.error("ReplicationService.handleGetDocumentRequest - Url error when getting document from MetacatReplication."
1258
					+ "handlGetDocumentRequest for url: " + urlString + " : "
1259
					+ mue.getMessage());
1260
			// e.printStackTrace(System.out);
1261
			
1262
		} catch (IOException ioe) {
1263
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1264
			logReplication.error("ReplicationService.handleGetDocumentRequest - I/O error when getting document from MetacatReplication."
1265
					+ "handlGetDocumentRequest for file: " + documentPath + " : "
1266
					+ ioe.getMessage());
1267
			errorMsg = ioe.getMessage();
1268
		} catch (PropertyNotFoundException pnfe) {
1269
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1270
			logReplication
1271
					.error("ReplicationService.handleGetDocumentRequest - Error getting property when getting document from MetacatReplication."
1272
							+ "handlGetDocumentRequest for file: "
1273
							+ documentPath
1274
							+ " : "
1275
							+ pnfe.getMessage());
1276
			// e.printStackTrace(System.out);
1277
			errorMsg = pnfe.getMessage();
1278
		} catch (McdbException me) {
1279
			logReplication
1280
					.error("ReplicationService.handleGetDocumentRequest - Document implementation error  getting property when getting document from MetacatReplication."
1281
							+ "handlGetDocumentRequest for file: "
1282
							+ documentPath
1283
							+ " : "
1284
							+ me.getMessage());
1285
			// e.printStackTrace(System.out);
1286
			errorMsg = me.getMessage();
1287
		}
1288
		
1289
		// report any errors if we got here
1290
		response.setContentType("text/xml");
1291
		Writer out = null;
1292
		try {
1293
			response.getWriter();
1294
			out = response.getWriter();
1295
			out.write("<error>" + errorMsg + "</error>");
1296
		} catch (Exception e) {
1297
			logMetacat.error(e.getMessage(), e);
1298
		} finally {
1299
			try {
1300
				out.close();
1301
			} catch (IOException e) {
1302
				logMetacat.error(e.getMessage(), e);
1303
			}
1304
		}
1305
		
1306

    
1307
	}
1308

    
1309
	/**
1310
	 * Sends a list of all of the documents on this sever along with their
1311
	 * revision numbers. The format is: <!ELEMENT replication (server, updates)>
1312
	 * <!ELEMENT server (#PCDATA)> <!ELEMENT updates ((updatedDocument |
1313
	 * deleteDocument | revisionDocument)*)> <!ELEMENT updatedDocument (docid,
1314
	 * rev, datafile*)> <!ELEMENT deletedDocument (docid, rev)> <!ELEMENT
1315
	 * revisionDocument (docid, rev, datafile*)> <!ELEMENT docid (#PCDATA)>
1316
	 * <!ELEMENT rev (#PCDATA)> <!ELEMENT datafile (#PCDATA)> note that the rev
1317
	 * in deletedDocument is always empty. I just left it in there to make the
1318
	 * parser implementation easier.
1319
	 */
1320
	protected static void handleUpdateRequest(Hashtable<String, String[]> params,
1321
			HttpServletResponse response) {
1322
		// Checked out DBConnection
1323
		DBConnection dbConn = null;
1324
		// DBConenction serial number when checked it out
1325
		int serialNumber = -1;
1326
		PreparedStatement pstmt = null;
1327
		// Server list to store server info of xml_replication table
1328
		ReplicationServerList serverList = null;
1329
		
1330
		// a writer for response
1331
		Writer out = null;
1332

    
1333
		try {
1334
			// get writer, TODO: encoding?
1335
			response.setContentType("text/xml");
1336
			out = response.getWriter();
1337
			
1338
			// Check out a DBConnection from pool
1339
			dbConn = DBConnectionPool
1340
					.getDBConnection("MetacatReplication.handleUpdateRequest");
1341
			serialNumber = dbConn.getCheckOutSerialNumber();
1342
			// Create a server list from xml_replication table
1343
			serverList = new ReplicationServerList();
1344

    
1345
			// Get remote server name from param
1346
			String server = ((String[]) params.get("server"))[0];
1347
			// If no servr name in param, return a error
1348
			if (server == null || server.equals("")) {
1349
				out.write("<error>Request didn't specify server name</error>");
1350
				out.close();
1351
				return;
1352
			}//if
1353

    
1354
			//try to open a https stream to test if the request server's public key
1355
			//in the key store, this is security issue
1356
			String testUrl = "https://" + server + "?server="
1357
            + MetacatUtil.getLocalReplicationServerName() + "&action=test";
1358
			logReplication.info("Running trust test: " + testUrl);
1359
			URL u = new URL(testUrl);
1360
			String test = ReplicationService.getURLContent(u);
1361
			logReplication.info("Ouput from test is '" + test + "'");
1362
			//couldn't pass the test
1363
			if (test.indexOf("successfully") == -1) {
1364
			    logReplication.error("Trust test failed.");
1365
				out.write("<error>Couldn't pass the trust test</error>");
1366
				out.close();
1367
				return;
1368
			}
1369
			logReplication.info("Trust test succeeded.");
1370

    
1371
			// Check if local host configure to replicate xml documents to remote
1372
			// server. If not send back a error message
1373
			if (!serverList.getReplicationValue(server)) {
1374
				out.write("<error>Configuration not allow to replicate document to you</error>");
1375
				out.close();
1376
				return;
1377
			}//if
1378

    
1379
			// Store the sql command
1380
			StringBuffer docsql = new StringBuffer();
1381
			StringBuffer revisionSql = new StringBuffer();
1382
			// Stroe the docid list
1383
			StringBuffer doclist = new StringBuffer();
1384
			// Store the deleted docid list
1385
			StringBuffer delsql = new StringBuffer();
1386
			// Store the data set file
1387
			Vector<Vector<String>> packageFiles = new Vector<Vector<String>>();
1388

    
1389
			// Append local server's name and replication servlet to doclist
1390
			doclist.append("<?xml version=\"1.0\"?><replication>");
1391
			doclist.append("<server>")
1392
					.append(MetacatUtil.getLocalReplicationServerName());
1393
			//doclist.append(util.getProperty("replicationpath"));
1394
			doclist.append("</server><updates>");
1395

    
1396
			// Get correct docid that reside on this server according the requesting
1397
			// server's replicate and data replicate value in xml_replication table
1398
			docsql.append(DatabaseService.getInstance().getDBAdapter().getReplicationDocumentListSQL());
1399
			//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)) ");
1400
			revisionSql.append("select docid, rev, doctype from xml_revisions ");
1401
			// If the localhost is not a hub to the remote server, only replicate
1402
			// the docid' which home server is local host (server_location =1)
1403
			if (!serverList.getHubValue(server)) {
1404
				String serverLocationDoc = " and a.server_location = 1";
1405
				String serverLocationRev = "where server_location = 1";
1406
				docsql.append(serverLocationDoc);
1407
				revisionSql.append(serverLocationRev);
1408
			}
1409
			logReplication.info("ReplicationService.handleUpdateRequest - Doc sql: " + docsql.toString());
1410

    
1411
			// Get any deleted documents
1412
			delsql.append("select distinct docid from ");
1413
			delsql.append("xml_revisions where docid not in (select docid from ");
1414
			delsql.append("xml_documents) ");
1415
			// If the localhost is not a hub to the remote server, only replicate
1416
			// the docid' which home server is local host (server_location =1)
1417
			if (!serverList.getHubValue(server)) {
1418
				delsql.append("and server_location = 1");
1419
			}
1420
			logReplication.info("ReplicationService.handleUpdateRequest - Deleted sql: " + delsql.toString());
1421

    
1422
			// Get docid list of local host
1423
			pstmt = dbConn.prepareStatement(docsql.toString());
1424
			pstmt.execute();
1425
			ResultSet rs = pstmt.getResultSet();
1426
			boolean tablehasrows = rs.next();
1427
			//If metacat configed to replicate data file
1428
			//if ((util.getProperty("replicationsenddata")).equals("on"))
1429
			boolean replicateData = serverList.getDataReplicationValue(server);
1430
			if (replicateData) {
1431
				while (tablehasrows) {
1432
					String recordDoctype = rs.getString(3);
1433
					Vector<String> packagedoctypes = MetacatUtil
1434
							.getOptionList(PropertyService
1435
									.getProperty("xml.packagedoctype"));
1436
					//if this is a package file, put it at the end
1437
					//because if a package file is read before all of the files it
1438
					//refers to are loaded then there is an error
1439
					if (recordDoctype != null && !packagedoctypes.contains(recordDoctype)) {
1440
						//If this is not data file
1441
						if (!recordDoctype.equals("BIN")) {
1442
							//for non-data file document
1443
							doclist.append("<updatedDocument>");
1444
							doclist.append("<docid>").append(rs.getString(1));
1445
							doclist.append("</docid><rev>").append(rs.getInt(2));
1446
							doclist.append("</rev>");
1447
							doclist.append("</updatedDocument>");
1448
						}//if
1449
						else {
1450
							//for data file document, in datafile attributes
1451
							//we put "datafile" value there
1452
							doclist.append("<updatedDocument>");
1453
							doclist.append("<docid>").append(rs.getString(1));
1454
							doclist.append("</docid><rev>").append(rs.getInt(2));
1455
							doclist.append("</rev>");
1456
							doclist.append("<datafile>");
1457
							doclist.append(PropertyService
1458
									.getProperty("replication.datafileflag"));
1459
							doclist.append("</datafile>");
1460
							doclist.append("</updatedDocument>");
1461
						}//else
1462
					}//if packagedoctpes
1463
					else { //the package files are saved to be put into the xml later.
1464
						Vector<String> v = new Vector<String>();
1465
						v.add(rs.getString(1));
1466
						v.add(String.valueOf(rs.getInt(2)));
1467
						packageFiles.add(v);
1468
					}//esle
1469
					tablehasrows = rs.next();
1470
				}//while
1471
			}//if
1472
			else //metacat was configured not to send data file
1473
			{
1474
				while (tablehasrows) {
1475
					String recordDoctype = rs.getString(3);
1476
					if (!recordDoctype.equals("BIN")) { //don't replicate data files
1477
						Vector<String> packagedoctypes = MetacatUtil
1478
								.getOptionList(PropertyService
1479
										.getProperty("xml.packagedoctype"));
1480
						if (recordDoctype != null
1481
								&& !packagedoctypes.contains(recordDoctype)) { //if this is a package file, put it at the end
1482
							//because if a package file is read before all of the files it
1483
							//refers to are loaded then there is an error
1484
							doclist.append("<updatedDocument>");
1485
							doclist.append("<docid>").append(rs.getString(1));
1486
							doclist.append("</docid><rev>").append(rs.getInt(2));
1487
							doclist.append("</rev>");
1488
							doclist.append("</updatedDocument>");
1489
						} else { //the package files are saved to be put into the xml later.
1490
							Vector<String> v = new Vector<String>();
1491
							v.add(rs.getString(1));
1492
							v.add(String.valueOf(rs.getInt(2)));
1493
							packageFiles.add(v);
1494
						}
1495
					}//if
1496
					tablehasrows = rs.next();
1497
				}//while
1498
			}//else
1499

    
1500
			pstmt = dbConn.prepareStatement(delsql.toString());
1501
			//usage count should increas 1
1502
			dbConn.increaseUsageCount(1);
1503

    
1504
			pstmt.execute();
1505
			rs = pstmt.getResultSet();
1506
			tablehasrows = rs.next();
1507
			while (tablehasrows) { //handle the deleted documents
1508
				doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1509
				doclist.append("</docid><rev></rev></deletedDocument>");
1510
				//note that rev is always empty for deleted docs
1511
				tablehasrows = rs.next();
1512
			}
1513

    
1514
			//now we can put the package files into the xml results
1515
			for (int i = 0; i < packageFiles.size(); i++) {
1516
				Vector<String> v = packageFiles.elementAt(i);
1517
				doclist.append("<updatedDocument>");
1518
				doclist.append("<docid>").append(v.elementAt(0));
1519
				doclist.append("</docid><rev>");
1520
				doclist.append(v.elementAt(1));
1521
				doclist.append("</rev>");
1522
				doclist.append("</updatedDocument>");
1523
			}
1524
			// add revision doc list  
1525
			doclist.append(prepareRevisionDoc(dbConn, revisionSql.toString(),
1526
					replicateData));
1527
			
1528
			// add the system metadata entries if configured to replicate them
1529
			boolean replicateSystemMetadata = serverList.getSystemMetadataReplicationValue(server);
1530
			if (replicateSystemMetadata) {
1531
				Date since = new Date(System.currentTimeMillis());
1532
				since = serverList.getLastCheckedDate(server);
1533
				List<String> systemMetadataEntries = 
1534
					IdentifierManager.getInstance().getUpdatedSystemMetadataIds(since);
1535
				for (int i = 0; i < systemMetadataEntries.size(); i++) {
1536
					String guid = systemMetadataEntries.get(i);
1537
					doclist.append("<updatedSystemMetadata>");
1538
					doclist.append("<guid>");
1539
					doclist.append(guid);
1540
					doclist.append("</guid>");
1541
					doclist.append("</updatedSystemMetadata>");
1542
				}
1543
			}
1544

    
1545
			doclist.append("</updates></replication>");
1546
			logReplication.info("ReplicationService.handleUpdateRequest - doclist: " + doclist.toString());
1547
			pstmt.close();
1548
			//conn.close();
1549
			out.write(doclist.toString());
1550

    
1551
		} catch (Exception e) {
1552
			logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1553
			logReplication.error("ReplicationService.handleUpdateRequest - error in MetacatReplication." + "handleupdaterequest: "
1554
					+ e.getMessage());
1555
			//e.printStackTrace(System.out);
1556
			try {
1557
				out.write("<error>" + e.getMessage() + "</error>");
1558
			} catch (IOException e1) {
1559
				logMetacat.error(e1.getMessage(), e1);
1560
			}
1561
		} finally {
1562
			try {
1563
				pstmt.close();
1564
			}//try
1565
			catch (SQLException ee) {
1566
				logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1567
				logReplication.error("ReplicationService.handleUpdateRequest - Error in MetacatReplication."
1568
						+ "handleUpdaterequest to close pstmt: " + ee.getMessage());
1569
			}//catch
1570
			finally {
1571
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1572
			}//finally
1573
			try {
1574
				out.close();
1575
			} catch (IOException e) {
1576
				logMetacat.error(e.getMessage(), e);
1577
			}
1578
		}//finally
1579

    
1580
	}//handlUpdateRequest
1581

    
1582
	/**
1583
	 * 
1584
	 * @param dbConn connection for doing the update
1585
	 * @param docid the document id to update
1586
	 * @param owner the user_owner
1587
	 * @param updater the user_updated
1588
	 * @throws SQLException
1589
	 */
1590
	public static void updateUserOwner(DBConnection dbConn, String docid, String owner, String updater) throws SQLException {
1591
	
1592
		String sql = 
1593
			"UPDATE xml_documents " +
1594
			"SET user_owner = ?, " +
1595
			"user_updated = ? " +
1596
			"WHERE docid = ?;";
1597
		PreparedStatement pstmt = dbConn.prepareStatement(sql);
1598
		//usage count should increas 1
1599
		dbConn.increaseUsageCount(1);
1600

    
1601
		docid = DocumentUtil.getSmartDocId(docid);
1602
		pstmt.setString(1, owner);
1603
		pstmt.setString(2, updater);
1604
		pstmt.setString(3, docid);
1605
		pstmt.execute();
1606
		pstmt.close();
1607
		
1608
		dbConn.commit();
1609
	}
1610
	
1611
	/*
1612
	 * This method will get the xml string for document in xml_revision
1613
	 * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1614
	 */
1615
	private static String prepareRevisionDoc(DBConnection dbConn, String revSql,
1616
			boolean replicateData) throws Exception {
1617
		logReplication.warn("ReplicationService.prepareRevisionDoc - The revision document sql is " + revSql);
1618
		StringBuffer revDocList = new StringBuffer();
1619
		PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1620
		//usage count should increas 1
1621
		dbConn.increaseUsageCount(1);
1622

    
1623
		pstmt.execute();
1624
		ResultSet rs = pstmt.getResultSet();
1625
		boolean tablehasrows = rs.next();
1626
		while (tablehasrows) {
1627
			String recordDoctype = rs.getString(3);
1628

    
1629
			//If this is data file and it isn't configured to replicate data
1630
			if (recordDoctype.equals("BIN") && !replicateData) {
1631
				// do nothing
1632
				continue;
1633
			} else {
1634

    
1635
				revDocList.append("<revisionDocument>");
1636
				revDocList.append("<docid>").append(rs.getString(1));
1637
				revDocList.append("</docid><rev>").append(rs.getInt(2));
1638
				revDocList.append("</rev>");
1639
				// data file
1640
				if (recordDoctype.equals("BIN")) {
1641
					revDocList.append("<datafile>");
1642
					revDocList.append(PropertyService
1643
							.getProperty("replication.datafileflag"));
1644
					revDocList.append("</datafile>");
1645
				}
1646
				revDocList.append("</revisionDocument>");
1647

    
1648
			}//else
1649
			tablehasrows = rs.next();
1650
		}
1651
		//System.out.println("The revision list is"+ revDocList.toString());
1652
		return revDocList.toString();
1653
	}
1654

    
1655
	/**
1656
	 * Returns the xml_catalog table encoded in xml
1657
	 */
1658
	public static String getCatalogXML() {
1659
		return handleGetCatalogRequest(null, null, false);
1660
	}
1661

    
1662
	/**
1663
	 * Sends the contents of the xml_catalog table encoded in xml
1664
	 * The xml format is:
1665
	 * <!ELEMENT xml_catalog (row*)>
1666
	 * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1667
	 *                system_id)>
1668
	 * All of the sub elements of row are #PCDATA
1669

    
1670
	 * If printFlag == false then do not print to out.
1671
	 */
1672
	protected static String handleGetCatalogRequest(
1673
			Hashtable<String, String[]> params, HttpServletResponse response,
1674
			boolean printFlag) {
1675
		DBConnection dbConn = null;
1676
		int serialNumber = -1;
1677
		PreparedStatement pstmt = null;
1678
		Writer out = null;
1679
		try {
1680
			// get writer, TODO: encoding?
1681
		    if(printFlag)
1682
		    {
1683
		        response.setContentType("text/xml");
1684
		        out = response.getWriter();
1685
		    }
1686
			/*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1687
			                                          "handleGetCatalogRequest");*/
1688
			dbConn = DBConnectionPool
1689
					.getDBConnection("MetacatReplication.handleGetCatalogRequest");
1690
			serialNumber = dbConn.getCheckOutSerialNumber();
1691
			pstmt = dbConn.prepareStatement("select entry_type, "
1692
					+ "source_doctype, target_doctype, public_id, "
1693
					+ "system_id from xml_catalog");
1694
			pstmt.execute();
1695
			ResultSet rs = pstmt.getResultSet();
1696
			boolean tablehasrows = rs.next();
1697
			StringBuffer sb = new StringBuffer();
1698
			sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1699
			while (tablehasrows) {
1700
				sb.append("<row><entry_type>").append(rs.getString(1));
1701
				sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1702
				sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1703
				sb.append("</target_doctype><public_id>").append(rs.getString(4));
1704
				// system id may not have server url on front.  Add it if not.
1705
				String systemID = rs.getString(5);
1706
				if (!systemID.startsWith("http://")) {
1707
					systemID = SystemUtil.getContextURL() + systemID;
1708
				}
1709
				sb.append("</public_id><system_id>").append(systemID);
1710
				sb.append("</system_id></row>");
1711

    
1712
				tablehasrows = rs.next();
1713
			}
1714
			sb.append("</xml_catalog>");
1715
			//conn.close();
1716
			if (printFlag) {
1717
				response.setContentType("text/xml");
1718
				out.write(sb.toString());
1719
			}
1720
			pstmt.close();
1721
			return sb.toString();
1722
		} catch (Exception e) {
1723
			logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1724
			logReplication.error("ReplicationService.handleGetCatalogRequest - error in MetacatReplication.handleGetCatalogRequest:"
1725
					+ e.getMessage());
1726
			e.printStackTrace(System.out);
1727
			if (printFlag) {
1728
				try {
1729
					out.write("<error>" + e.getMessage() + "</error>");
1730
				} catch (IOException e1) {
1731
					logMetacat.error(e1.getMessage(), e1);
1732
				}
1733
			}
1734
		} finally {
1735
			try {
1736
				pstmt.close();
1737
			}//try
1738
			catch (SQLException ee) {
1739
				logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1740
				logReplication.error("ReplicationService.handleGetCatalogRequest - Error in MetacatReplication.handleGetCatalogRequest: "
1741
						+ ee.getMessage());
1742
			}//catch
1743
			finally {
1744
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1745
			}//finally
1746
			if (out != null) {
1747
				try {
1748
					out.close();
1749
				} catch (IOException e1) {
1750
					logMetacat.error(e1.getMessage(), e1);
1751
				}
1752
			}
1753
		}//finally
1754

    
1755
		return null;
1756
	}
1757

    
1758
	/**
1759
	 * Sends the current system date to the remote server.  Using this action
1760
	 * for replication gets rid of any problems with syncronizing clocks
1761
	 * because a time specific to a document is always kept on its home server.
1762
	 */
1763
	protected static void handleGetTimeRequest(
1764
			Hashtable<String, String[]> params, HttpServletResponse response) {
1765
		
1766
		// use standard format -- the receiving end wants this too
1767
		String dateString = DateTimeMarshaller.serializeDateToUTC(Calendar.getInstance().getTime());
1768
		
1769
		// get a writer for sending back to response
1770
		response.setContentType("text/xml");
1771
		Writer out = null;
1772
		try {
1773
			out = response.getWriter();
1774
			out.write("<timestamp>" + dateString + "</timestamp>");
1775
			out.close();
1776
		} catch (IOException e) {
1777
			logMetacat.error(e.getMessage(), e);
1778
		}
1779
		
1780
	}
1781

    
1782
	/**
1783
	 * this method handles the timeout for a file lock.  when a lock is
1784
	 * granted it is granted for 30 seconds.  When this thread runs out
1785
	 * it deletes the docid from the queue, thus eliminating the lock.
1786
	 */
1787
	public void run() {
1788
		try {
1789
			logReplication.info("ReplicationService.run - thread started for docid: "
1790
					+ (String) fileLocks.elementAt(0));
1791

    
1792
			Thread.sleep(30000); //the lock will expire in 30 seconds
1793
			logReplication.info("thread for docid: "
1794
					+ (String) fileLocks.elementAt(fileLocks.size() - 1) + " exiting.");
1795

    
1796
			fileLocks.remove(fileLocks.size() - 1);
1797
			//fileLocks is treated as a FIFO queue.  If there are more than one lock
1798
			//in the vector, the first one inserted will be removed.
1799
		} catch (Exception e) {
1800
			logMetacat.error("ReplicationService.run - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1801
			logReplication.error("ReplicationService.run - error in file lock thread from "
1802
					+ "MetacatReplication.run: " + e.getMessage());
1803
		}
1804
	}
1805

    
1806
	/**
1807
	 * Returns the name of a server given a serverCode
1808
	 * @param serverCode the serverid of the server
1809
	 * @return the servername or null if the specified serverCode does not
1810
	 *         exist.
1811
	 */
1812
	public static String getServerNameForServerCode(int serverCode) {
1813
		//System.out.println("serverid: " + serverCode);
1814
		DBConnection dbConn = null;
1815
		int serialNumber = -1;
1816
		PreparedStatement pstmt = null;
1817
		try {
1818
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServer");
1819
			serialNumber = dbConn.getCheckOutSerialNumber();
1820
			String sql = new String("select server from "
1821
					+ "xml_replication where serverid = ?");
1822
			pstmt = dbConn.prepareStatement(sql);
1823
			pstmt.setInt(1, serverCode);
1824
			//System.out.println("getserver sql: " + sql);
1825
			pstmt.execute();
1826
			ResultSet rs = pstmt.getResultSet();
1827
			boolean tablehasrows = rs.next();
1828
			if (tablehasrows) {
1829
				//System.out.println("server: " + rs.getString(1));
1830
				return rs.getString(1);
1831
			}
1832

    
1833
			//conn.close();
1834
		} catch (Exception e) {
1835
			logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1836
			logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplication.getServer: " + e.getMessage());
1837
		} finally {
1838
			try {
1839
				pstmt.close();
1840
			}//try
1841
			catch (SQLException ee) {
1842
				logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1843
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacactReplication.getserver: "
1844
						+ ee.getMessage());
1845
			}//catch
1846
			finally {
1847
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1848
			}//fianlly
1849
		}//finally
1850

    
1851
		return null;
1852
		//return null if the server does not exist
1853
	}
1854

    
1855
	/**
1856
	 * Returns a server code given a server name
1857
	 * @param server the name of the server
1858
	 * @return integer > 0 representing the code of the server, 0 if the server
1859
	 *  does not exist.
1860
	 */
1861
	public static int getServerCodeForServerName(String server) throws ServiceException {
1862
		DBConnection dbConn = null;
1863
		int serialNumber = -1;
1864
		PreparedStatement pstmt = null;
1865
		int serverCode = 0;
1866

    
1867
		try {
1868

    
1869
			//conn = util.openDBConnection();
1870
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServerCode");
1871
			serialNumber = dbConn.getCheckOutSerialNumber();
1872
			pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication "
1873
					+ "WHERE server LIKE ?");
1874
			pstmt.setString(1, server);
1875
			pstmt.execute();
1876
			ResultSet rs = pstmt.getResultSet();
1877
			boolean tablehasrows = rs.next();
1878
			if (tablehasrows) {
1879
				serverCode = rs.getInt(1);
1880
				pstmt.close();
1881
				//conn.close();
1882
				return serverCode;
1883
			}
1884

    
1885
		} catch (SQLException sqle) {
1886
			throw new ServiceException("ReplicationService.getServerCodeForServerName - " 
1887
					+ "SQL error when getting server code: " + sqle.getMessage());
1888

    
1889
		} finally {
1890
			try {
1891
				pstmt.close();
1892
				//conn.close();
1893
			}//try
1894
			catch (Exception ee) {
1895
				logMetacat.error("ReplicationService.getServerCodeForServerName - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1896
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplicatio.getServerCode: "
1897
						+ ee.getMessage());
1898

    
1899
			}//catch
1900
			finally {
1901
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1902
			}//finally
1903
		}//finally
1904

    
1905
		return serverCode;
1906
	}
1907

    
1908
	/**
1909
	 * Method to get a host server information for given docid
1910
	 * @param conn a connection to the database
1911
	 */
1912
	public static Hashtable<String, String> getHomeServerInfoForDocId(String docId) {
1913
		Hashtable<String, String> sl = new Hashtable<String, String>();
1914
		DBConnection dbConn = null;
1915
		int serialNumber = -1;
1916
		docId = DocumentUtil.getDocIdFromString(docId);
1917
		PreparedStatement pstmt = null;
1918
		int serverLocation;
1919
		try {
1920
			//get conection
1921
			dbConn = DBConnectionPool.getDBConnection("ReplicationHandler.getHomeServer");
1922
			serialNumber = dbConn.getCheckOutSerialNumber();
1923
			//get a server location from xml_document table
1924
			pstmt = dbConn.prepareStatement("select server_location from xml_documents "
1925
					+ "where docid = ?");
1926
			pstmt.setString(1, docId);
1927
			pstmt.execute();
1928
			ResultSet serverName = pstmt.getResultSet();
1929
			//get a server location
1930
			if (serverName.next()) {
1931
				serverLocation = serverName.getInt(1);
1932
				pstmt.close();
1933
			} else {
1934
				pstmt.close();
1935
				//ut.returnConnection(conn);
1936
				return null;
1937
			}
1938
			pstmt = dbConn.prepareStatement("select server, last_checked, replicate "
1939
					+ "from xml_replication where serverid = ?");
1940
			//increase usage count
1941
			dbConn.increaseUsageCount(1);
1942
			pstmt.setInt(1, serverLocation);
1943
			pstmt.execute();
1944
			ResultSet rs = pstmt.getResultSet();
1945
			boolean tableHasRows = rs.next();
1946
			if (tableHasRows) {
1947

    
1948
				String server = rs.getString(1);
1949
				String last_checked = rs.getString(2);
1950
				if (!server.equals("localhost")) {
1951
					sl.put(server, last_checked);
1952
				}
1953

    
1954
			} else {
1955
				pstmt.close();
1956
				//ut.returnConnection(conn);
1957
				return null;
1958
			}
1959
			pstmt.close();
1960
		} catch (Exception e) {
1961
			logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1962
			logReplication.error("ReplicationService.getHomeServerInfoForDocId - error in replicationHandler.getHomeServer(): "
1963
					+ e.getMessage());
1964
		} finally {
1965
			try {
1966
				pstmt.close();
1967
				//ut.returnConnection(conn);
1968
			} catch (Exception ee) {
1969
				logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1970
				logReplication.error("ReplicationService.getHomeServerInfoForDocId - Eror irn rplicationHandler.getHomeServer() "
1971
						+ "to close pstmt: " + ee.getMessage());
1972
			} finally {
1973
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1974
			}
1975

    
1976
		}//finally
1977
		return sl;
1978
	}
1979

    
1980
	/**
1981
	 * Returns a home server location  given a accnum
1982
	 * @param accNum , given accNum for a document
1983
	 *
1984
	 */
1985
	public static int getHomeServerCodeForDocId(String accNum) throws ServiceException {
1986
		DBConnection dbConn = null;
1987
		int serialNumber = -1;
1988
		PreparedStatement pstmt = null;
1989
		int serverCode = 1;
1990
		String docId = DocumentUtil.getDocIdFromString(accNum);
1991

    
1992
		try {
1993

    
1994
			// Get DBConnection
1995
			dbConn = DBConnectionPool
1996
					.getDBConnection("ReplicationHandler.getServerLocation");
1997
			serialNumber = dbConn.getCheckOutSerialNumber();
1998
			pstmt = dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1999
					+ "WHERE docid LIKE ? ");
2000
			pstmt.setString(1, docId);
2001
			pstmt.execute();
2002
			ResultSet rs = pstmt.getResultSet();
2003
			boolean tablehasrows = rs.next();
2004
			//If a document is find, return the server location for it
2005
			if (tablehasrows) {
2006
				serverCode = rs.getInt(1);
2007
				pstmt.close();
2008
				//conn.close();
2009
				return serverCode;
2010
			}
2011
			//if couldn't find in xml_documents table, we think server code is 1
2012
			//(this is new document)
2013
			else {
2014
				pstmt.close();
2015
				//conn.close();
2016
				return serverCode;
2017
			}
2018

    
2019
		} catch (SQLException sqle) {
2020
			throw new ServiceException("ReplicationService.getHomeServerCodeForDocId - " 
2021
					+ "SQL error when getting home server code for docid: " + docId + " : " 
2022
					+ sqle.getMessage());
2023

    
2024
		} finally {
2025
			try {
2026
				pstmt.close();
2027
				//conn.close();
2028

    
2029
			} catch (SQLException sqle) {
2030
				logMetacat.error("ReplicationService.getHomeServerCodeForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2031
				logReplication.error("ReplicationService.getHomeServerCodeForDocId - ReplicationService.getHomeServerCodeForDocId - " 
2032
						+ "SQL error when getting home server code for docid: " + docId + " : " 
2033
						+ sqle.getMessage());
2034
			} finally {
2035
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2036
			}//finally
2037
		}//finally
2038
		//return serverCode;
2039
	}
2040

    
2041
	/**
2042
	 * This method returns the content of a url
2043
	 * @param u the url to return the content from
2044
	 * @return a string representing the content of the url
2045
	 * @throws java.io.IOException
2046
	 */
2047
	public static String getURLContent(URL u) throws java.io.IOException {
2048
		char istreamChar;
2049
		int istreamInt;
2050
		// get the response content
2051
		InputStream input = getURLStream(u);
2052
		logReplication.info("ReplicationService.getURLContent - After getting response from: " + u.toString());
2053
		InputStreamReader istream = new InputStreamReader(input);
2054
		StringBuffer serverResponse = new StringBuffer();
2055
		while ((istreamInt = istream.read()) != -1) {
2056
			istreamChar = (char) istreamInt;
2057
			serverResponse.append(istreamChar);
2058
		}
2059
		istream.close();
2060
		input.close();
2061

    
2062
		return serverResponse.toString();
2063
	}
2064
	
2065
	/**
2066
	 * This method returns the InputStream after opening a url
2067
	 * @param u the url to return the content from
2068
	 * @return a InputStream representing the content of the url
2069
	 * @throws java.io.IOException
2070
	 */
2071
	public static InputStream getURLStream(URL u) throws java.io.IOException {
2072
	    logReplication.info("Getting url stream from " + u.toString());
2073
		logReplication.info("ReplicationService.getURLStream - Before sending request to: " + u.toString());
2074
		// use httpclient to set up SSL
2075
		RestClient client = getSSLClient();
2076
		HttpResponse response = client.doGetRequest(u.toString());
2077
		// get the response content
2078
		InputStream input = response.getEntity().getContent();
2079
		logReplication.info("ReplicationService.getURLStream - After getting response from: " + u.toString());
2080
		
2081
		return input;		
2082
	}
2083
	
2084
	/**
2085
	 * Sets up an HttpClient with SSL connection.
2086
	 * Sends client certificate to the server when doing the request.
2087
	 * @return
2088
	 */
2089
	private static RestClient getSSLClient() {
2090
		RestClient client = new RestClient();
2091
		
2092
		// set up this server's client identity
2093
		String subject = null;
2094
		try {
2095
			// TODO: should there be alternative ways to get the key and certificate?
2096
			String certificateFile = PropertyService.getProperty("replication.certificate.file");
2097
	    	String keyFile = PropertyService.getProperty("replication.privatekey.file");
2098
			String keyPassword = PropertyService.getProperty("replication.privatekey.password");
2099
			X509Certificate certificate = CertificateManager.getInstance().loadCertificateFromFile(certificateFile);
2100
			PrivateKey privateKey = CertificateManager.getInstance().loadPrivateKeyFromFile(keyFile, keyPassword);
2101
			subject = CertificateManager.getInstance().getSubjectDN(certificate);
2102
			CertificateManager.getInstance().registerCertificate(subject, certificate, privateKey);
2103
		} catch (Exception e) {
2104
			// this is pretty much required for replication communication
2105
			logReplication.warn("Could not find server's client certificate/private key: " + e.getMessage());
2106
		}
2107
		SSLSocketFactory socketFactory = null;
2108
		try {
2109
			socketFactory = CertificateManager.getInstance().getSSLSocketFactory(subject);
2110
		} catch (FileNotFoundException e) {
2111
			// these are somewhat expected for anonymous client use
2112
			logReplication.warn("Could not set up SSL connection for client - likely because the certificate could not be located: " + e.getMessage());
2113
		} catch (Exception e) {
2114
			// this is likely more severe
2115
			logReplication.warn("Funky SSL going on: " + e.getClass() + ":: " + e.getMessage());
2116
		}
2117
		try {
2118
			//443 is the default port, this value is overridden if explicitly set in the URL
2119
			Scheme sch = new Scheme("https", 443, socketFactory);
2120
			client.getHttpClient().getConnectionManager().getSchemeRegistry().register(sch);
2121
		} catch (Exception e) {
2122
			// this is likely more severe
2123
			logReplication.error("Failed to set up SSL connection for client. Continuing. " + e.getClass() + ":: " + e.getMessage(), e);
2124
		}
2125
		return client;
2126
	}
2127
	
2128

    
2129
//	/**
2130
//	 * Method for writing replication messages to a log file specified in
2131
//	 * metacat.properties
2132
//	 */
2133
//	public static void replLog(String message) {
2134
//		try {
2135
//			FileOutputStream fos = new FileOutputStream(PropertyService
2136
//					.getProperty("replication.logdir")
2137
//					+ "/metacatreplication.log", true);
2138
//			PrintWriter pw = new PrintWriter(fos);
2139
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
2140
//			java.util.Date localtime = new java.util.Date();
2141
//			String dateString = formatter.format(localtime);
2142
//			dateString += " :: " + message;
2143
//			// time stamp each entry
2144
//			pw.println(dateString);
2145
//			pw.flush();
2146
//		} catch (Exception e) {
2147
//			logReplication.error("error writing to replication log from "
2148
//					+ "MetacatReplication.replLog: " + e.getMessage());
2149
//			// e.printStackTrace(System.out);
2150
//		}
2151
//	}
2152

    
2153
//	/**
2154
//	 * Method for writing replication messages to a log file specified in
2155
//	 * metacat.properties
2156
//	 */
2157
//	public static void replErrorLog(String message) {
2158
//		try {
2159
//			FileOutputStream fos = new FileOutputStream(PropertyService
2160
//					.getProperty("replication.logdir")
2161
//					+ "/metacatreplicationerror.log", true);
2162
//			PrintWriter pw = new PrintWriter(fos);
2163
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
2164
//			java.util.Date localtime = new java.util.Date();
2165
//			String dateString = formatter.format(localtime);
2166
//			dateString += " :: " + message;
2167
//			//time stamp each entry
2168
//			pw.println(dateString);
2169
//			pw.flush();
2170
//		} catch (Exception e) {
2171
//			logReplication.error("error writing to replication error log from "
2172
//					+ "MetacatReplication.replErrorLog: " + e.getMessage());
2173
//			//e.printStackTrace(System.out);
2174
//		}
2175
//	}
2176

    
2177
	/**
2178
	 * Returns true if the replicate field for server in xml_replication is 1.
2179
	 * Returns false otherwise
2180
	 */
2181
	public static boolean replToServer(String server) {
2182
		DBConnection dbConn = null;
2183
		int serialNumber = -1;
2184
		PreparedStatement pstmt = null;
2185
		try {
2186
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.repltoServer");
2187
			serialNumber = dbConn.getCheckOutSerialNumber();
2188
			pstmt = dbConn.prepareStatement("select replicate from "
2189
					+ "xml_replication where server like ? ");
2190
			pstmt.setString(1, server);
2191
			pstmt.execute();
2192
			ResultSet rs = pstmt.getResultSet();
2193
			boolean tablehasrows = rs.next();
2194
			if (tablehasrows) {
2195
				int i = rs.getInt(1);
2196
				if (i == 1) {
2197
					pstmt.close();
2198
					//conn.close();
2199
					return true;
2200
				} else {
2201
					pstmt.close();
2202
					//conn.close();
2203
					return false;
2204
				}
2205
			}
2206
		} catch (SQLException sqle) {
2207
			logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2208
			logReplication.error("ReplicationService.replToServer - SQL error in MetacatReplication.replToServer: "
2209
					+ sqle.getMessage());
2210
		} finally {
2211
			try {
2212
				pstmt.close();
2213
				//conn.close();
2214
			}//try
2215
			catch (Exception ee) {
2216
				logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2217
				logReplication.error("ReplicationService.replToServer - Error in MetacatReplication.replToServer: "
2218
						+ ee.getMessage());
2219
			}//catch
2220
			finally {
2221
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2222
			}//finally
2223
		}//finally
2224
		return false;
2225
		//the default if this server does not exist is to not replicate to it.
2226
	}
2227

    
2228
}
(7-7/8)