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

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

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

    
55
import javax.servlet.http.HttpServletRequest;
56
import javax.servlet.http.HttpServletResponse;
57

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

    
73
import edu.ucsb.nceas.metacat.DocumentImpl;
74
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
75
import edu.ucsb.nceas.metacat.EventLog;
76
import edu.ucsb.nceas.metacat.IdentifierManager;
77
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
78
import edu.ucsb.nceas.metacat.McdbException;
79
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlException;
80
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
81
import edu.ucsb.nceas.metacat.accesscontrol.PermOrderException;
82
import edu.ucsb.nceas.metacat.admin.upgrade.RemoveInvalidReplicas;
83
import edu.ucsb.nceas.metacat.admin.upgrade.dataone.GenerateORE;
84
import edu.ucsb.nceas.metacat.admin.upgrade.dataone.GenerateSystemMetadata;
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
import edu.ucsb.nceas.utilities.access.DocInfoHandler;
102
import edu.ucsb.nceas.utilities.access.XMLAccessDAO;
103

    
104
public class ReplicationService extends BaseService {
105

    
106
	private static ReplicationService replicationService = null;
107

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

    
124
	public static final String REPLICATION_LOG_FILE_NAME = "metacatreplication.log";
125

    
126
	private static String DATA_FILE_FLAG = null;
127
	public static String METACAT_REPL_ERROR_MSG = null;
128
	private static Logger logReplication = Logger.getLogger("ReplicationLogging");
129
	private static Logger logMetacat = Logger.getLogger(ReplicationService.class);
130

    
131
	static {
132
		// lookup the client timeout
133
		String clientTimeout = null;
134
		try {
135
			clientTimeout = PropertyService.getProperty("replication.client.timeout");
136
			CLIENTTIMEOUT = Integer.parseInt(clientTimeout);
137
		} catch (Exception e) {
138
			// just use default
139
			logReplication.warn("No custom client timeout specified in configuration, using default." + e.getMessage());
140
		}
141
		try {
142
			DATA_FILE_FLAG = PropertyService.getProperty("replication.datafileflag");
143
		} catch (PropertyNotFoundException e) {
144
			logReplication.error("No 'replication.datafileflag' specified in configuration." + e.getMessage());
145
		}
146

    
147
	}
148
	
149
	private ReplicationService() throws ServiceException {
150
		_serviceName = "ReplicationService";
151
		
152
		initialize();
153
	}
154
	
155
	private void initialize() throws ServiceException {
156
				
157
		// initialize db connections to handle any update requests
158
		// deltaT = util.getProperty("replication.deltaT");
159
		// the default deltaT can be set from metacat.properties
160
		// create a thread to do the delta-T check but don't execute it yet
161
		replicationDaemon = new Timer(true);
162
		try {
163
			String replLogFile = PropertyService.getProperty("replication.logdir")
164
				+ FileUtil.getFS() + REPLICATION_LOG_FILE_NAME;
165
			METACAT_REPL_ERROR_MSG = "An error occurred in replication.  Please see the " +
166
				"replication log at: " + replLogFile;
167
			
168
			String timedRepIsOnStr = 
169
				PropertyService.getProperty("replication.timedreplication");
170
			timedReplicationIsOn = (new Boolean(timedRepIsOnStr)).booleanValue();
171
			logReplication.info("ReplicationService.initialize - The timed replication on is" + timedReplicationIsOn);
172

    
173
			String timeIntervalStr = 
174
				PropertyService.getProperty("replication.timedreplicationinterval");
175
			timeInterval = (new Long(timeIntervalStr)).longValue();
176
			logReplication.info("ReplicationService.initialize - The timed replication time Interval is " + timeInterval);
177

    
178
			String firstTimeStr = 
179
				PropertyService.getProperty("replication.firsttimedreplication");
180
			logReplication.info("ReplicationService.initialize - first replication time form property is " + firstTimeStr);
181
			firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
182

    
183
			logReplication.info("ReplicationService.initialize - After combine current time, the real first time is "
184
					+ firstTime.toString() + " minisec");
185

    
186
			// set up time replication if it is on
187
			if (timedReplicationIsOn) {
188
				replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(),
189
						firstTime, timeInterval);
190
				logReplication.info("ReplicationService.initialize - deltaT handler started with rate="
191
						+ timeInterval + " mini seconds at " + firstTime.toString());
192
			}
193

    
194
		} catch (PropertyNotFoundException pnfe) {
195
			throw new ServiceException(
196
					"ReplicationService.initialize - Property error while instantiating "
197
							+ "replication service: " + pnfe.getMessage());
198
		} catch (HandlerException he) {
199
			throw new ServiceException(
200
					"ReplicationService.initialize - Handler error while instantiating "
201
							+ "replication service" + he.getMessage());
202
		} 
203
	}
204

    
205
	/**
206
	 * Get the single instance of SessionService.
207
	 * 
208
	 * @return the single instance of SessionService
209
	 */
210
	public static ReplicationService getInstance() throws ServiceException {
211
		if (replicationService == null) {
212
			replicationService = new ReplicationService();
213
		}
214
		return replicationService;
215
	}
216

    
217
	public boolean refreshable() {
218
		return true;
219
	}
220

    
221
	protected void doRefresh() throws ServiceException {
222
		return;
223
	}
224
	
225
	public void stop() throws ServiceException{
226
		
227
	}
228

    
229
	public void stopReplication() throws ServiceException {
230
	      //stop the replication server
231
	      replicationDaemon.cancel();
232
	      replicationDaemon = new Timer(true);
233
	      timedReplicationIsOn = false;
234
	      try {
235
	    	  PropertyService.setProperty("replication.timedreplication", (new Boolean(timedReplicationIsOn)).toString());
236
	      } catch (GeneralPropertyException gpe) {
237
	    	  logReplication.warn("ReplicationService.stopReplication - Could not set replication.timedreplication property: " + gpe.getMessage());
238
	      }
239

    
240
	      logReplication.info("ReplicationService.stopReplication - deltaT handler stopped");
241
		return;
242
	}
243
	
244
	public void startReplication(Hashtable<String, String[]> params) throws ServiceException {
245

    
246
	       String firstTimeStr = "";
247
	      //start the replication server
248
	       if ( params.containsKey("rate") ) {
249
	        timeInterval = new Long(
250
	               new String(((String[])params.get("rate"))[0])).longValue();
251
	        if(timeInterval < TIMEINTERVALLIMIT) {
252
	            //deltaT<30 is a timing mess!
253
	            timeInterval = TIMEINTERVALLIMIT;
254
	            throw new ServiceException("Replication deltaT rate cannot be less than "+
255
	                    TIMEINTERVALLIMIT + " millisecs and system automatically setup the rate to "+TIMEINTERVALLIMIT);
256
	        }
257
	      } else {
258
	        timeInterval = TIMEINTERVALLIMIT ;
259
	      }
260
	      logReplication.info("ReplicationService.startReplication - New rate is: " + timeInterval + " mini seconds.");
261
	      if ( params.containsKey("firsttime"))
262
	      {
263
	         firstTimeStr = ((String[])params.get("firsttime"))[0];
264
	         try
265
	         {
266
	           firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
267
	           logReplication.info("ReplicationService.startReplication - The first time setting is "+firstTime.toString());
268
	         }
269
	         catch (HandlerException e)
270
	         {
271
	            throw new ServiceException(e.getMessage());
272
	         }
273
	         logReplication.warn("After combine current time, the real first time is "
274
	                                  +firstTime.toString()+" minisec");
275
	      }
276
	      else
277
	      {
278
	    	  logMetacat.error("ReplicationService.startReplication - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
279
	          logReplication.error("ReplicationService.startReplication - You should specify the first time " +
280
	                                  "to start a time replication");
281
	          return;
282
	      }
283
	      
284
	      timedReplicationIsOn = true;
285
	      try {
286
	      // save settings to property file
287
	      PropertyService.setProperty(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
288
	      // note we couldn't use firstTime object because it has date info
289
	      // we only need time info such as 10:00 PM
290
	      PropertyService.setProperty(FIRSTTIME, firstTimeStr);
291
	      PropertyService.setProperty(TIMEREPLICATIONINTERVAl, (new Long(timeInterval)).toString());
292
	      } catch (GeneralPropertyException gpe) {
293
	    	  logReplication.warn("ReplicationService.startReplication - Could not set property: " + gpe.getMessage());
294
	      }
295
	      replicationDaemon.cancel();
296
	      replicationDaemon = new Timer(true);
297
	      replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime,
298
	                                            timeInterval);
299
	      
300
	      logReplication.info("ReplicationService.startReplication - deltaT handler started with rate=" +
301
	                                    timeInterval + " milliseconds at " +firstTime.toString());
302

    
303
	}
304
	
305
	public void runOnce() throws ServiceException {
306
	      //updates this server exactly once
307
	      replicationDaemon.schedule(new ReplicationHandler(), 0);
308
	}
309
	
310
	/**
311
	 * This method can add, delete and list the servers currently included in
312
	 * xml_replication.
313
	 * action           subaction            other needed params
314
	 * ---------------------------------------------------------
315
	 * servercontrol    add                  server
316
	 * servercontrol    delete               server
317
	 * servercontrol    list
318
	 */
319
	public static void handleServerControlRequest(
320
			Hashtable<String, String[]> params, HttpServletRequest request, HttpServletResponse response) {
321
		String subaction = ((String[]) params.get("subaction"))[0];
322
		DBConnection dbConn = null;
323
		int serialNumber = -1;
324
		PreparedStatement pstmt = null;
325
		String replicate = null;
326
		String server = null;
327
		String dataReplicate = null;
328
		String hub = null;
329
		Writer out = null;
330
		boolean showGenerateSystemMetadata = false;
331
		try {
332
			response.setContentType("text/xml");
333
			out = response.getWriter();
334
			
335
			//conn = util.openDBConnection();
336
			dbConn = DBConnectionPool
337
					.getDBConnection("MetacatReplication.handleServerControlRequest");
338
			serialNumber = dbConn.getCheckOutSerialNumber();
339

    
340
			// add server to server list
341
			if (subaction.equals("add")) {
342
				replicate = ((String[]) params.get("replicate"))[0];
343
				server = ((String[]) params.get("server"))[0];
344

    
345
				//Get data replication value
346
				dataReplicate = ((String[]) params.get("datareplicate"))[0];
347
				
348
				//Get hub value
349
				hub = ((String[]) params.get("hub"))[0];
350

    
351
				Calendar cal = Calendar.getInstance();
352
                cal.set(1980, 1, 1);
353
				String sql = "INSERT INTO xml_replication "
354
						+ "(server, last_checked, replicate, datareplicate, hub) "
355
						+ "VALUES (?,?,?,?,?)";
356
				
357
				pstmt = dbConn.prepareStatement(sql);
358
						
359
				pstmt.setString(1, server);
360
				pstmt.setTimestamp(2, new Timestamp(cal.getTimeInMillis()));
361
				pstmt.setInt(3, Integer.parseInt(replicate));
362
				pstmt.setInt(4, Integer.parseInt(dataReplicate));
363
				pstmt.setInt(5, Integer.parseInt(hub));
364
				
365
				String sqlReport = "XMLAccessAccess.getXMLAccessForDoc - SQL: " + sql;
366
				sqlReport += " [" + server + "," + replicate + 
367
					"," + dataReplicate + "," + hub + "]";
368
				
369
				logMetacat.info(sqlReport);
370
				
371
				pstmt.execute();
372
				pstmt.close();
373
				dbConn.commit();
374
				out.write("Server " + server + " added");
375
				
376
				
377
				// delete server from server list
378
			} else if (subaction.equals("delete")) {
379
				server = ((String[]) params.get("server"))[0];
380
				pstmt = dbConn.prepareStatement("DELETE FROM xml_replication "
381
						+ "WHERE server LIKE ?");
382
				pstmt.setString(1, server);
383
				pstmt.execute();
384
				pstmt.close();
385
				dbConn.commit();
386
				out.write("Server " + server + " deleted");
387
			} else if (subaction.equals("list")) {
388
				// nothing special - it's the default behavior
389

    
390
			} else if (subaction.equals("generatesystemmetadata")) {
391
				GenerateSystemMetadata gsm = new GenerateSystemMetadata();
392
				int serverLocation = -1;
393
				String serverid = ((String[]) params.get("serverid"))[0];
394
				serverLocation = Integer.parseInt(serverid);
395
				gsm.setServerLocation(serverLocation );
396
				gsm.multiThreadUpgrade();
397
				out.write("System Metadata generated for server " + serverid);
398
				
399
			} else if (subaction.equals("generateore")) {
400
				GenerateORE gore = new GenerateORE();
401
				int serverLocation = -1;
402
				String serverid = ((String[]) params.get("serverid"))[0];
403
				serverLocation = Integer.parseInt(serverid);
404
				gore.setServerLocation(serverLocation );
405
				gore.upgrade();
406
				out.write("Generated ORE maps for server " + serverid);
407
				
408
			} else if (subaction.equals("removeinvalidreplicas")) {
409
				RemoveInvalidReplicas rir = new RemoveInvalidReplicas();
410
				int serverLocation = -1;
411
				String serverid = ((String[]) params.get("serverid"))[0];
412
				serverLocation = Integer.parseInt(serverid);
413
				rir.setServerLocation(serverLocation );
414
				rir.upgrade();
415
				out.write("Removed invalid replicas for server " + serverid);
416
				
417
			} else {
418
			
419
				out.write("<error>Unkonwn subaction</error>");
420
				return;
421
			}
422
			
423
			// show SM generate button?
424
			String dataoneConfigured = PropertyService.getProperty("configutil.dataoneConfigured");
425
			if (dataoneConfigured != null) {
426
				showGenerateSystemMetadata = Boolean.parseBoolean(dataoneConfigured);
427
			}
428
			
429
			// always list them after processing
430
			response.setContentType("text/html");
431
			out.write("<html><body><table border=\"1\">");
432
			out.write("<tr><td><b>server</b></td>");
433
			out.write("<td><b>last_checked</b></td>");
434
			out.write("<td><b>replicate</b></td>");
435
			out.write("<td><b>datareplicate</b></td>");
436
			out.write("<td><b>hub</b></td>");
437
			if (showGenerateSystemMetadata) {
438
				out.write("<td><b>System Metadata</b></td>");
439
				out.write("<td><b>ORE Maps</b></td>");
440
				out.write("<td><b>Invalid Replicas</b></td>");
441
			}
442
			out.write("</tr>");
443

    
444
			pstmt = dbConn.prepareStatement("SELECT serverid, server, last_checked, replicate, datareplicate, hub FROM xml_replication");
445
			pstmt.execute();
446
			ResultSet rs = pstmt.getResultSet();
447
			boolean tablehasrows = rs.next();
448
			while (tablehasrows) {
449
				String serverId = rs.getString(1);
450
				out.write("<tr><td>" + rs.getString(2) + "</td><td>");
451
				out.write(rs.getString(3) + "</td><td>");
452
				out.write(rs.getString(4) + "</td><td>");
453
				out.write(rs.getString(5) + "</td><td>");
454
				out.write(rs.getString(6) + "</td>");
455
				if (showGenerateSystemMetadata) {
456
					// for SM
457
					out.write("<td><form action='" + request.getContextPath() + "/admin'>");
458
					out.write("<input name='serverid' type='hidden' value='" + serverId  + "'/>");
459
					out.write("<input name='configureType' type='hidden' value='replication'/>");
460
					out.write("<input name='action' type='hidden' value='servercontrol'/>");
461
					out.write("<input name='subaction' type='hidden' value='generatesystemmetadata'/>");
462
					out.write("<input type='submit' value='Generate System Metadata'/>");
463
					out.write("</form></td>");
464
					
465
					// for ORE maps
466
					out.write("<td><form action='" + request.getContextPath() + "/admin'>");
467
					out.write("<input name='serverid' type='hidden' value='" + serverId + "'/>");
468
					out.write("<input name='configureType' type='hidden' value='replication'/>");
469
					out.write("<input name='action' type='hidden' value='servercontrol'/>");
470
					out.write("<input name='subaction' type='hidden' value='generateore'/>");
471
					out.write("<input type='submit' value='Generate ORE'/>");
472
					out.write("</form></td>");
473
					
474
					// for invalid replicas
475
					out.write("<td><form action='" + request.getContextPath() + "/admin'>");
476
					out.write("<input name='serverid' type='hidden' value='" + serverId + "'/>");
477
					out.write("<input name='configureType' type='hidden' value='replication'/>");
478
					out.write("<input name='action' type='hidden' value='servercontrol'/>");
479
					out.write("<input name='subaction' type='hidden' value='removeinvalidreplicas'/>");
480
					String disabled = "";
481
					if (Integer.valueOf(serverId) == 1) {
482
						disabled = "disabled='true'";
483
					}
484
					out.write("<input type='submit' value='Remove Invalid Replicas' " + disabled + " />");
485
					out.write("</form></td>");
486
				}
487
				out.write("</tr>");
488

    
489
				tablehasrows = rs.next();
490
			}
491
			out.write("</table></body></html>");
492
			
493
			
494
			pstmt.close();
495
			//conn.close();
496

    
497
		} catch (Exception e) {
498
			logMetacat.error("ReplicationService.handleServerControlRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
499
			logReplication.error("ReplicationService.handleServerControlRequest - Error in "
500
					+ "MetacatReplication.handleServerControlRequest " + e.getMessage());
501
			e.printStackTrace(System.out);
502
		} finally {
503
			try {
504
				pstmt.close();
505
			}//try
506
			catch (SQLException ee) {
507
				logMetacat.error("ReplicationService.handleServerControlRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
508
				logReplication.error("ReplicationService.handleServerControlRequest - Error in MetacatReplication.handleServerControlRequest to close pstmt "
509
						+ ee.getMessage());
510
			}//catch
511
			finally {
512
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
513
			}//finally
514
			if (out != null) {
515
				try {
516
					out.close();
517
				} catch (IOException e) {
518
					logMetacat.error(e.getMessage(), e);
519
				}
520
			}
521
		}//finally
522

    
523
	}
524

    
525
	/**
526
	 * when a forcereplication request comes in, local host sends a read request
527
	 * to the requesting server (remote server) for the specified docid. Then
528
	 * store it in local database.
529
	 */
530
	protected static void handleForceReplicateRequest(
531
			Hashtable<String, String[]> params, HttpServletResponse response,
532
			HttpServletRequest request) {
533
		String server = ((String[]) params.get("server"))[0]; // the server that
534
		String docid = ((String[]) params.get("docid"))[0]; // sent the document
535
		String dbaction = "UPDATE"; // the default action is UPDATE
536
		//    boolean override = false;
537
		//    int serverCode = 1;
538
		DBConnection dbConn = null;
539
		int serialNumber = -1;
540
		String docName = null;
541

    
542
		try {
543
			//if the url contains a dbaction then the default action is overridden
544
			if (params.containsKey("dbaction")) {
545
				dbaction = ((String[]) params.get("dbaction"))[0];
546
				//serverCode = MetacatReplication.getServerCode(server);
547
				//override = true; //we are now overriding the default action
548
			}
549
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication request from: " + server);
550
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication docid: " + docid);
551
			logReplication.info("ReplicationService.handleForceReplicateRequest - Force replication action: " + dbaction);
552
			// sending back read request to remote server
553
			URL u = new URL("https://" + server + "?server="
554
					+ MetacatUtil.getLocalReplicationServerName() + "&action=read&docid="
555
					+ docid);
556
			String xmldoc = ReplicationService.getURLContent(u);
557

    
558
			// get the document info from server
559
			URL docinfourl = new URL("https://" + server + "?server="
560
					+ MetacatUtil.getLocalReplicationServerName()
561
					+ "&action=getdocumentinfo&docid=" + docid);
562
			
563

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

    
628
			// Get DBConnection from pool
629
			dbConn = DBConnectionPool
630
					.getDBConnection("MetacatReplication.handleForceReplicateRequest");
631
			serialNumber = dbConn.getCheckOutSerialNumber();
632
			// write the document to local database
633
			DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false, false);
634
			//try this independently so we can set access even if the update action is invalid (i.e docid has not changed)
635
			try {
636
				wrapper.writeReplication(dbConn, xmldoc, null, null,
637
						dbaction, docid, null, null, homeServer, server, createdDate,
638
						updatedDate);
639
			} finally {
640

    
641
				//process extra access rules before dealing with the write exception (doc exist already)
642
				try {
643
		        	// check if we had a guid -> docid mapping
644
		        	String docidNoRev = DocumentUtil.getDocIdFromAccessionNumber(docid);
645
		        	int rev = DocumentUtil.getRevisionFromAccessionNumber(docid);
646
		        	IdentifierManager.getInstance().getGUID(docidNoRev, rev);
647
		        	// no need to create the mapping if we have it
648
		        } catch (McdbDocNotFoundException mcdbe) {
649
		        	// create mapping if we don't
650
		        	IdentifierManager.getInstance().createMapping(docid, docid);
651
		        }
652
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
653
		        if (accessControlList != null) {
654
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
655
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
656
		        		try {
657
			        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
658
			        			acfsf.insertPermissions(xmlAccessDAO);
659
								logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
660
										+ " permissions added to DB");
661
			        		}
662
		        		} catch (PermOrderException poe) {
663
		        			// this is problematic, but should not prevent us from replicating
664
		        			// see https://redmine.dataone.org/issues/2583
665
		        			String msg = "Could not insert access control for: " + docid + " Message: " + poe.getMessage();
666
		        			logMetacat.error(msg, poe);
667
		        			logReplication.error(msg, poe);
668
		        		}
669
		            }
670
		        }
671
		        
672
		        // process the real owner and updater
673
				String user = (String) docinfoHash.get("user_owner");
674
				String updated = (String) docinfoHash.get("user_updated");
675
		        updateUserOwner(dbConn, docid, user, updated);
676

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

    
720
	/*
721
	 * when a forcereplication delete request comes in, local host will delete this
722
	 * document
723
	 */
724
	protected static void handleForceReplicateDeleteRequest(
725
			Hashtable<String, String[]> params, HttpServletResponse response,
726
			HttpServletRequest request, boolean removeAll) {
727
		String server = ((String[]) params.get("server"))[0]; // the server that
728
		String docid = ((String[]) params.get("docid"))[0]; // sent the document
729
		try {
730
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete request from " + server);
731
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete docid " + docid);
732
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete request from: " + server);
733
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete docid: " + docid);
734
			DocumentImpl.delete(docid, null, null, server, removeAll);
735
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
736
			EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), REPLICATIONUSER, docid,
737
					"delete");
738
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
739
		} catch (McdbDocNotFoundException 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 (InsufficientKarmaException 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 (SQLException 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
		} catch (Exception e) {
755
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
756
			logReplication.error("document " + docid
757
					+ " failed to delete because " + e.getMessage());
758
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
759

    
760
		}//catch
761

    
762
	}
763

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

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

    
787
		// Overide or not
788
		//    boolean override = false;
789
		// dbaction - update or insert
790
		String dbaction = null;
791

    
792
		try {
793
			//docid was switch to two parts uinque code and rev
794
			//String uniqueCode=MetacatUtil.getDocIdFromString(docid);
795
			//int rev=MetacatUtil.getVersionFromString(docid);
796
			if (params.containsKey("dbaction")) {
797
				dbaction = ((String[]) params.get("dbaction"))[0];
798
			} else//default value is update
799
			{
800
//				dbaction = "update";
801
				dbaction = null;
802
			}
803

    
804
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication request from: " + server);
805
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication docid: " + docid);
806
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication action: " + dbaction);
807
			// get the document info from server
808
			URL docinfourl = new URL("https://" + server + "?server="
809
					+ MetacatUtil.getLocalReplicationServerName()
810
					+ "&action=getdocumentinfo&docid=" + docid);
811

    
812
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
813
			
814
			// strip out the system metadata portion
815
		    String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
816
		   	docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);
817

    
818
			//dih is the parser for the docinfo xml format
819
			DocInfoHandler dih = new DocInfoHandler();
820
			XMLReader docinfoParser = ReplicationHandler.initParser(dih);
821
			docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
822
			Hashtable<String, String> docinfoHash = dih.getDocInfo();
823
			
824
			String docName = (String) docinfoHash.get("docname");
825

    
826
			String docType = (String) docinfoHash.get("doctype");
827

    
828
			String docHomeServer = (String) docinfoHash.get("home_server");
829
			
830
			String createdDateString = docinfoHash.get("date_created");
831
			String updatedDateString = docinfoHash.get("date_updated");
832
			
833
			Date createdDate = DateTimeMarshaller.deserializeDateToUTC(createdDateString);
834
			Date updatedDate = DateTimeMarshaller.deserializeDateToUTC(updatedDateString);
835
			
836
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - docHomeServer of datafile: " + docHomeServer);
837

    
838
			// in case we have a write exception, we still want to track access and sysmeta
839
			Exception writeException = null;
840

    
841
			// do we need the object content?
842
			if (dbaction != null && (dbaction.equals("insert") || dbaction.equals("update"))) {
843
				//Get data file and store it into local file system.
844
				// sending back readdata request to server
845
				URL url = new URL("https://" + server + "?server="
846
						+ MetacatUtil.getLocalReplicationServerName()
847
						+ "&action=readdata&docid=" + docid);
848
				String datafilePath = PropertyService
849
						.getProperty("application.datafilepath");
850

    
851
				InputStream inputStream = getURLStream(url);
852
				
853
				//register data file into xml_documents table and write data file
854
				//into file system
855
				try {
856
					DocumentImpl.writeDataFileInReplication(inputStream,
857
							datafilePath, docName, docType, docid, null, docHomeServer,
858
							server, DocumentImpl.DOCUMENTTABLE, false, createdDate,
859
							updatedDate);
860
				} catch (Exception e) {
861
					writeException = e;
862
				}
863

    
864
			}
865
			
866
			// process the real owner and updater
867
			DBConnection dbConn = DBConnectionPool.getDBConnection("ReplicationService.handleForceDataFileRequest");
868
	        int serialNumber = dbConn.getCheckOutSerialNumber();
869
	        dbConn.setAutoCommit(false);
870
			String user = (String) docinfoHash.get("user_owner");
871
			String updated = (String) docinfoHash.get("user_updated");
872
	        updateUserOwner(dbConn, docid, user, updated);
873
	        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
874
	        
875
			// process system metadata
876
	        if (systemMetadataXML != null) {
877
	      	  SystemMetadata sysMeta = 
878
	      		TypeMarshaller.unmarshalTypeFromStream(
879
	      				  SystemMetadata.class, 
880
	      				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
881
	      	  
882
	      	  // need the guid-to-docid mapping
883
	      	  boolean mappingExists = true;
884
	      	  mappingExists = IdentifierManager.getInstance().mappingExists(sysMeta.getIdentifier().getValue());
885
	      	  if (!mappingExists) {
886
	      		  IdentifierManager.getInstance().createMapping(sysMeta.getIdentifier().getValue(), docid);
887
	      	  }
888
	      	  // save the system metadata
889
	      	  HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
890
	      	  // submit for indexing
891
              HazelcastService.getInstance().getIndexQueue().add(sysMeta);
892
	        }
893
	        
894
	        // process the access control
895
	        try {
896
	        	// check if we had a guid -> docid mapping
897
	        	String docidNoRev = DocumentUtil.getDocIdFromAccessionNumber(docid);
898
	        	int rev = DocumentUtil.getRevisionFromAccessionNumber(docid);
899
	        	IdentifierManager.getInstance().getGUID(docidNoRev, rev);
900
	        	// no need to create the mapping if we have it
901
	        } catch (McdbDocNotFoundException mcdbe) {
902
	        	// create mapping if we don't
903
	        	IdentifierManager.getInstance().createMapping(docid, docid);
904
	        }
905
	        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
906
	        if (accessControlList != null) {
907
	        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
908
	        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
909
	        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
910
	        			acfsf.insertPermissions(xmlAccessDAO);
911
						logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
912
								+ " permissions added to DB");
913
	        		}
914
	            }
915
	        }
916
	        
917
	        // throw the write exception now -- this happens when access changes on an object
918
			if (writeException != null) {
919
				throw writeException;
920
			}
921

    
922
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - datafile " + docid + " added to DB with "
923
					+ "action " + dbaction);
924
			EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), REPLICATIONUSER,
925
					docid, dbaction);
926

    
927
		} catch (Exception e) {
928
			e.printStackTrace();
929
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG, e);                         
930
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Datafile " + docid
931
					+ " failed to added to DB with " + "action " + dbaction + " because "
932
					+ e.getMessage());
933
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - ERROR in MetacatReplication.handleForceDataFileReplicate"
934
					+ "Request(): " + e.getMessage());
935
		}
936
	}
937

    
938
	/**
939
	 * Grants or denies a lock to a requesting host.
940
	 * The servlet parameters of interrest are:
941
	 * docid: the docid of the file the lock is being requested for
942
	 * currentdate: the timestamp of the document on the remote server
943
	 *
944
	 */
945
	protected static void handleGetLockRequest(
946
			Hashtable<String, String[]> params, HttpServletResponse response) {
947

    
948
		try {
949

    
950
			String docid = ((String[]) params.get("docid"))[0];
951
			String remoteRev = ((String[]) params.get("updaterev"))[0];
952
			DocumentImpl requestDoc = new DocumentImpl(docid);
953
			logReplication.info("ReplicationService.handleGetLockRequest - lock request for " + docid);
954
			int localRevInt = requestDoc.getRev();
955
			int remoteRevInt = Integer.parseInt(remoteRev);
956

    
957
			// get a writer for sending back to response
958
			response.setContentType("text/xml");
959
			Writer out = response.getWriter();
960
			
961
			if (remoteRevInt >= localRevInt) {
962
				if (!fileLocks.contains(docid)) { //grant the lock if it is not already locked
963
					fileLocks.add(0, docid); //insert at the beginning of the queue Vector
964
					//send a message back to the the remote host authorizing the insert
965
					out.write("<lockgranted><docid>" + docid
966
									+ "</docid></lockgranted>");
967
					//          lockThread = new Thread(this);
968
					//          lockThread.setPriority(Thread.MIN_PRIORITY);
969
					//          lockThread.start();
970
					logReplication.info("ReplicationService.handleGetLockRequest - lock granted for " + docid);
971
				} else { //deny the lock
972
					out.write("<filelocked><docid>" + docid + "</docid></filelocked>");
973
					logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
974
							+ "reason: file already locked");
975
				}
976
			} else {//deny the lock.
977
				out.write("<outdatedfile><docid>" + docid + "</docid></filelocked>");
978
				logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
979
						+ "reason: client has outdated file");
980
			}
981
			out.close();
982
			//conn.close();
983
		} catch (Exception e) {
984
			logMetacat.error("ReplicationService.handleGetLockRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
985
			logReplication.error("ReplicationService.handleGetLockRequest - error requesting file lock from MetacatReplication."
986
					+ "handleGetLockRequest: " + e.getMessage());
987
			e.printStackTrace(System.out);
988
		}
989
	}
990

    
991
	/**
992
	 * Sends all of the xml_documents information encoded in xml to a requestor
993
	 * the format is:
994
	 * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
995
	 *                  user_updated, home_server, public_access, rev)/>
996
	 * all of the subelements of document info are #PCDATA
997
	 */
998
	protected static void handleGetDocumentInfoRequest(
999
			Hashtable<String, String[]> params, HttpServletResponse response) {
1000
		String docid = ((String[]) (params.get("docid")))[0];
1001

    
1002
		try {
1003
			// get docinfo as XML string
1004
			String docinfoXML = getDocumentInfo(docid);
1005
			
1006
			// get a writer for sending back to response
1007
			response.setContentType("text/xml");
1008
			Writer out = response.getWriter();
1009
			out.write(docinfoXML);
1010
			out.close();
1011

    
1012
		} catch (Exception e) {
1013
			logMetacat.error("ReplicationService.handleGetDocumentInfoRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1014
			logReplication.error("ReplicationService.handleGetDocumentInfoRequest - error in metacatReplication.handlegetdocumentinforequest "
1015
					+ "for doc: " + docid + " : " + e.getMessage());
1016
		}
1017

    
1018
	}
1019
	
1020
	public static Hashtable<String, String> getDocumentInfoMap(String docid)
1021
			throws HandlerException, AccessControlException, JiBXException,
1022
			IOException, McdbException, SAXException {
1023
		
1024
		// Try get docid info from remote server
1025
		DocInfoHandler dih = new DocInfoHandler();
1026
		XMLReader docinfoParser = ReplicationHandler.initParser(dih);
1027

    
1028
		String docInfoStr = getDocumentInfo(docid);
1029

    
1030
		// strip out the system metadata portion
1031
		String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
1032
		docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);
1033

    
1034
		docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
1035
		Hashtable<String, String> docinfoHash = dih.getDocInfo();
1036

    
1037
		return docinfoHash;
1038
	}
1039
	
1040
	/**
1041
	 * Gets a docInfo XML snippet for the replication API
1042
	 * @param docid
1043
	 * @return
1044
	 * @throws AccessControlException
1045
	 * @throws JiBXException
1046
	 * @throws IOException
1047
	 * @throws McdbException
1048
	 */
1049
	public static String getDocumentInfo(String docid) throws AccessControlException, JiBXException, IOException, McdbException {
1050
		StringBuffer sb = new StringBuffer();
1051

    
1052
		DocumentImpl doc = new DocumentImpl(docid);
1053
		sb.append("<documentinfo><docid>").append(docid);
1054
		sb.append("</docid>");
1055
		
1056
		try {
1057
			// serialize the System Metadata as XML for docinfo
1058
			String guid = IdentifierManager.getInstance().getGUID(doc.getDocID(), doc.getRev());
1059
			SystemMetadata systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
1060
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
1061
			TypeMarshaller.marshalTypeToOutputStream(systemMetadata, baos);
1062
			String systemMetadataXML = baos.toString("UTF-8");
1063
			sb.append("<systemMetadata>");
1064
			sb.append(systemMetadataXML);
1065
			sb.append("</systemMetadata>");
1066
		} catch(McdbDocNotFoundException e) {
1067
		  logMetacat.warn("No SystemMetadata found for: " + docid);
1068
		}
1069
		
1070
		Calendar created = Calendar.getInstance();
1071
		created.setTime(doc.getCreateDate());
1072
		Calendar updated = Calendar.getInstance();
1073
		updated.setTime(doc.getUpdateDate());
1074
		
1075
		sb.append("<docname><![CDATA[").append(doc.getDocname());
1076
		sb.append("]]></docname><doctype>").append(doc.getDoctype());
1077
		sb.append("</doctype>");
1078
		sb.append("<user_owner>").append(doc.getUserowner());
1079
		sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
1080
		sb.append("</user_updated>");
1081
		sb.append("<date_created>");
1082
		sb.append(DateTimeMarshaller.serializeDateToUTC(doc.getCreateDate()));
1083
		sb.append("</date_created>");
1084
		sb.append("<date_updated>");
1085
		sb.append(DateTimeMarshaller.serializeDateToUTC(doc.getUpdateDate()));
1086
		sb.append("</date_updated>");
1087
		sb.append("<home_server>");
1088
		sb.append(doc.getDocHomeServer());
1089
		sb.append("</home_server>");
1090
		sb.append("<public_access>").append(doc.getPublicaccess());
1091
		sb.append("</public_access><rev>").append(doc.getRev());
1092
		sb.append("</rev>");
1093

    
1094
		sb.append("<accessControl>");
1095

    
1096
		AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid); 
1097
		sb.append(acfsf.getAccessString());
1098
		
1099
		sb.append("</accessControl>");
1100

    
1101
		sb.append("</documentinfo>");
1102
			
1103
		return sb.toString();
1104
	}
1105
	
1106
	/**
1107
	 * Sends System Metadata as XML
1108
	 */
1109
	protected static void handleGetSystemMetadataRequest(
1110
			Hashtable<String, String[]> params, HttpServletResponse response) {
1111
		String guid = ((String[]) (params.get("guid")))[0];
1112
		String systemMetadataXML = null;
1113
		try {
1114
			
1115
			// serialize the System Metadata as XML 
1116
			SystemMetadata systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
1117
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
1118
			TypeMarshaller.marshalTypeToOutputStream(systemMetadata, baos);
1119
			systemMetadataXML = baos.toString("UTF-8");
1120
				
1121
			// get a writer for sending back to response
1122
			response.setContentType("text/xml");
1123
			Writer out = response.getWriter();
1124
			out.write(systemMetadataXML);
1125
			out.close();
1126

    
1127
		} catch (Exception e) {
1128
			String msg = "ReplicationService.handleGetSystemMetadataRequest for guid: " + guid + " : " + e.getMessage();
1129
			logMetacat.error(msg);                         
1130
			logReplication.error(msg);
1131
		}
1132

    
1133
	}
1134
	
1135
	/**
1136
	 * when a forcereplication request comes in, local host sends a read request
1137
	 * to the requesting server (remote server) for the specified docid. Then
1138
	 * store it in local database.
1139
	 */
1140
	protected static void handleForceReplicateSystemMetadataRequest(
1141
			Hashtable<String, String[]> params, HttpServletResponse response,
1142
			HttpServletRequest request) {
1143
		String server = ((String[]) params.get("server"))[0]; // the server that
1144
		String guid = ((String[]) params.get("guid"))[0]; // sent the document
1145
		
1146
		try {
1147
			logReplication.info("ReplicationService.handleForceReplicateSystemMetadataRequest - Force replication system metadata request from: " + server);
1148
			// get the system metadata from server
1149
			URL docinfourl = new URL("https://" + server + "?server="
1150
					+ MetacatUtil.getLocalReplicationServerName()
1151
					+ "&action=getsystemmetadata&guid=" + guid);
1152
			
1153
			String systemMetadataXML = ReplicationService.getURLContent(docinfourl);
1154
						
1155
			// process system metadata
1156
			if (systemMetadataXML != null) {
1157
				SystemMetadata sysMeta = 
1158
					TypeMarshaller.unmarshalTypeFromStream(
1159
							SystemMetadata.class,
1160
							new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
1161
				HazelcastService.getInstance().getSystemMetadataMap().put(sysMeta.getIdentifier(), sysMeta);
1162
				// submit for indexing
1163
                HazelcastService.getInstance().getIndexQueue().add(sysMeta);
1164
			}
1165
      
1166
			logReplication.info("ReplicationService.handleForceReplicateSystemMetadataRequest - processed guid: " + guid);
1167
			EventLog.getInstance().log(request.getRemoteAddr(), request.getHeader("User-Agent"), REPLICATIONUSER, guid, "systemMetadata");
1168

    
1169
		} catch (Exception e) {
1170
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG, e);                         
1171
			logReplication.error("ReplicationService.handleForceReplicateRequest - General error when processing guid: " + guid, e);
1172
		}
1173
	}
1174

    
1175
	/**
1176
	 * Sends a datafile to a remote host
1177
	 */
1178
	protected static void handleGetDataFileRequest(OutputStream outPut,
1179
			Hashtable<String, String[]> params, HttpServletResponse response)
1180

    
1181
	{
1182
		// File path for data file
1183
		String filepath;
1184
		// Request docid
1185
		String docId = ((String[]) (params.get("docid")))[0];
1186
		//check if the doicd is null
1187
		if (docId == null) {
1188
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1189
			logReplication.error("ReplicationService.handleGetDataFileRequest - Didn't specify docid for replication");
1190
			return;
1191
		}
1192

    
1193
		//try to open a https stream to test if the request server's public key
1194
		//in the key store, this is security issue
1195
		try {
1196
			filepath = PropertyService.getProperty("application.datafilepath");
1197
			String server = params.get("server")[0];
1198
			URL u = new URL("https://" + server + "?server="
1199
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test");
1200
			String test = ReplicationService.getURLContent(u);
1201
			//couldn't pass the test
1202
			if (test.indexOf("successfully") == -1) {
1203
				//response.setContentType("text/xml");
1204
				//outPut.println("<error>Couldn't pass the trust test</error>");
1205
				logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1206
				logReplication.error("ReplicationService.handleGetDataFileRequest - Couldn't pass the trust test");
1207
				return;
1208
			}
1209
		}//try
1210
		catch (Exception ee) {
1211
			return;
1212
		}//catch
1213

    
1214
		if (!filepath.endsWith("/")) {
1215
			filepath += "/";
1216
		}
1217
		// Get file aboslute file name
1218
		String filename = filepath + docId;
1219

    
1220
		//MIME type
1221
		String contentType = null;
1222
		if (filename.endsWith(".xml")) {
1223
			contentType = "text/xml";
1224
		} else if (filename.endsWith(".css")) {
1225
			contentType = "text/css";
1226
		} else if (filename.endsWith(".dtd")) {
1227
			contentType = "text/plain";
1228
		} else if (filename.endsWith(".xsd")) {
1229
			contentType = "text/xml";
1230
		} else if (filename.endsWith("/")) {
1231
			contentType = "text/html";
1232
		} else {
1233
			File f = new File(filename);
1234
			if (f.isDirectory()) {
1235
				contentType = "text/html";
1236
			} else {
1237
				contentType = "application/octet-stream";
1238
			}
1239
		}
1240

    
1241
		// Set the mime type
1242
		response.setContentType(contentType);
1243

    
1244
		// Get the content of the file
1245
		FileInputStream fin = null;
1246
		try {
1247
			// FileInputStream to metacat
1248
			fin = new FileInputStream(filename);
1249
			// 4K buffer
1250
			byte[] buf = new byte[4 * 1024];
1251
			// Read data from file input stream to byte array
1252
			int b = fin.read(buf);
1253
			// Write to outStream from byte array
1254
			while (b != -1) {
1255
				outPut.write(buf, 0, b);
1256
				b = fin.read(buf);
1257
			}
1258
			// close file input stream
1259
			fin.close();
1260

    
1261
		}//try
1262
		catch (Exception e) {
1263
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1264
			logReplication.error("ReplicationService.handleGetDataFileRequest - error getting data file from MetacatReplication."
1265
					+ "handlGetDataFileRequest " + e.getMessage());
1266
			e.printStackTrace(System.out);
1267
		}//catch
1268

    
1269
	}
1270

    
1271
	/**
1272
	 * Sends a document to a remote host
1273
	 */
1274
	protected static void handleGetDocumentRequest(
1275
			Hashtable<String, String[]> params, HttpServletResponse response) {
1276

    
1277
		String urlString = null;
1278
		String documentPath = null;
1279
		String errorMsg = null;
1280
		FileOutputStream fos = null;
1281
		InputStream is = null;
1282
		OutputStream outputStream = null;
1283
		try {
1284
			// try to open a https stream to test if the request server's public
1285
			// key
1286
			// in the key store, this is security issue
1287
			String server = params.get("server")[0];
1288
			urlString = "https://" + server + "?server="
1289
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test";
1290
			URL u = new URL(urlString);
1291
			String test = ReplicationService.getURLContent(u);
1292
			// couldn't pass the test
1293
			if (test.indexOf("successfully") == -1) {
1294
				response.setContentType("text/xml");
1295
				Writer out = response.getWriter();
1296
				out.write("<error>Couldn't pass the trust test " + test + " </error>");
1297
				out.close();
1298
				return;
1299
			}
1300

    
1301
			String docid = params.get("docid")[0];
1302
			logReplication.debug("ReplicationService.handleGetDocumentRequest - MetacatReplication.handleGetDocumentRequest for docid: "
1303
					+ docid);
1304
			DocumentImpl di = new DocumentImpl(docid);
1305

    
1306
			String documentDir = PropertyService
1307
					.getProperty("application.documentfilepath");
1308
			documentPath = documentDir + FileUtil.getFS() + docid;
1309

    
1310
			// if the document does not exist on disk, read it from db and write
1311
			// it to disk.
1312
			if (FileUtil.getFileStatus(documentPath) == FileUtil.DOES_NOT_EXIST
1313
					|| FileUtil.getFileSize(documentPath) == 0) {
1314
				fos = new FileOutputStream(documentPath);
1315
				is = di.toXml(fos, null, null, true);
1316
				fos.close();
1317
				is.close();
1318
			}
1319

    
1320
			// read the file from disk and send it to outputstream
1321
			outputStream = response.getOutputStream();
1322
			is = di.readFromFileSystem(outputStream, null, null, documentPath);
1323
			is.close();
1324
			outputStream.close();
1325

    
1326
			logReplication.info("ReplicationService.handleGetDocumentRequest - document " + docid + " sent");
1327

    
1328
			// return to avoid continuing to the error reporting section at the end
1329
			return;
1330
			
1331
		} catch (MalformedURLException mue) {
1332
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1333
			logReplication.error("ReplicationService.handleGetDocumentRequest - Url error when getting document from MetacatReplication."
1334
					+ "handlGetDocumentRequest for url: " + urlString + " : "
1335
					+ mue.getMessage());
1336
			// e.printStackTrace(System.out);
1337
			
1338
		} catch (IOException ioe) {
1339
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1340
			logReplication.error("ReplicationService.handleGetDocumentRequest - I/O error when getting document from MetacatReplication."
1341
					+ "handlGetDocumentRequest for file: " + documentPath + " : "
1342
					+ ioe.getMessage());
1343
			errorMsg = ioe.getMessage();
1344
		} catch (PropertyNotFoundException pnfe) {
1345
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1346
			logReplication
1347
					.error("ReplicationService.handleGetDocumentRequest - Error getting property when getting document from MetacatReplication."
1348
							+ "handlGetDocumentRequest for file: "
1349
							+ documentPath
1350
							+ " : "
1351
							+ pnfe.getMessage());
1352
			// e.printStackTrace(System.out);
1353
			errorMsg = pnfe.getMessage();
1354
		} catch (McdbException me) {
1355
			logReplication
1356
					.error("ReplicationService.handleGetDocumentRequest - Document implementation error  getting property when getting document from MetacatReplication."
1357
							+ "handlGetDocumentRequest for file: "
1358
							+ documentPath
1359
							+ " : "
1360
							+ me.getMessage());
1361
			// e.printStackTrace(System.out);
1362
			errorMsg = me.getMessage();
1363
		} finally {
1364
            IOUtils.closeQuietly(fos);
1365
            IOUtils.closeQuietly(is);
1366
            IOUtils.closeQuietly(outputStream);
1367
		}
1368
		
1369
		// report any errors if we got here
1370
		response.setContentType("text/xml");
1371
		Writer out = null;
1372
		try {
1373
			response.getWriter();
1374
			out = response.getWriter();
1375
			out.write("<error>" + errorMsg + "</error>");
1376
		} catch (Exception e) {
1377
			logMetacat.error(e.getMessage(), e);
1378
		} finally {
1379
			try {
1380
				out.close();
1381
			} catch (IOException e) {
1382
				logMetacat.error(e.getMessage(), e);
1383
			}
1384
		}
1385
		
1386

    
1387
	}
1388

    
1389
	/**
1390
	 * Sends a list of all of the documents on this sever along with their
1391
	 * revision numbers. The format is: <!ELEMENT replication (server, updates)>
1392
	 * <!ELEMENT server (#PCDATA)> <!ELEMENT updates ((updatedDocument |
1393
	 * deleteDocument | revisionDocument)*)> <!ELEMENT updatedDocument (docid,
1394
	 * rev, datafile*)> <!ELEMENT deletedDocument (docid, rev)> <!ELEMENT
1395
	 * revisionDocument (docid, rev, datafile*)> <!ELEMENT docid (#PCDATA)>
1396
	 * <!ELEMENT rev (#PCDATA)> <!ELEMENT datafile (#PCDATA)> note that the rev
1397
	 * in deletedDocument is always empty. I just left it in there to make the
1398
	 * parser implementation easier.
1399
	 */
1400
	protected static void handleUpdateRequest(Hashtable<String, String[]> params,
1401
			HttpServletResponse response) {
1402
		// Checked out DBConnection
1403
		DBConnection dbConn = null;
1404
		// DBConenction serial number when checked it out
1405
		int serialNumber = -1;
1406
		PreparedStatement pstmt = null;
1407
		// Server list to store server info of xml_replication table
1408
		ReplicationServerList serverList = null;
1409
		
1410
		// a writer for response
1411
		Writer out = null;
1412

    
1413
		try {
1414
			// get writer, TODO: encoding?
1415
			response.setContentType("text/xml");
1416
			out = response.getWriter();
1417
			
1418
			// Check out a DBConnection from pool
1419
			dbConn = DBConnectionPool
1420
					.getDBConnection("MetacatReplication.handleUpdateRequest");
1421
			serialNumber = dbConn.getCheckOutSerialNumber();
1422
			// Create a server list from xml_replication table
1423
			serverList = new ReplicationServerList();
1424

    
1425
			// Get remote server name from param
1426
			String server = ((String[]) params.get("server"))[0];
1427
			// If no servr name in param, return a error
1428
			if (server == null || server.equals("")) {
1429
				out.write("<error>Request didn't specify server name</error>");
1430
				out.close();
1431
				return;
1432
			}//if
1433

    
1434
			//try to open a https stream to test if the request server's public key
1435
			//in the key store, this is security issue
1436
			String testUrl = "https://" + server + "?server="
1437
            + MetacatUtil.getLocalReplicationServerName() + "&action=test";
1438
			logReplication.info("Running trust test: " + testUrl);
1439
			URL u = new URL(testUrl);
1440
			String test = ReplicationService.getURLContent(u);
1441
			logReplication.info("Ouput from test is '" + test + "'");
1442
			//couldn't pass the test
1443
			if (test.indexOf("successfully") == -1) {
1444
			    logReplication.error("Trust test failed.");
1445
				out.write("<error>Couldn't pass the trust test</error>");
1446
				out.close();
1447
				return;
1448
			}
1449
			logReplication.info("Trust test succeeded.");
1450

    
1451
			// Check if local host configure to replicate xml documents to remote
1452
			// server. If not send back a error message
1453
			if (!serverList.getReplicationValue(server)) {
1454
				out.write("<error>Configuration not allow to replicate document to you</error>");
1455
				out.close();
1456
				return;
1457
			}//if
1458

    
1459
			// Store the sql command
1460
			StringBuffer docsql = new StringBuffer();
1461
			StringBuffer revisionSql = new StringBuffer();
1462
			
1463
			// Store the data set file
1464
			Vector<Vector<String>> packageFiles = new Vector<Vector<String>>();
1465

    
1466
			// Append local server's name and replication servlet to doclist
1467
			out.append("<?xml version=\"1.0\"?><replication>");
1468
			out.append("<server>")
1469
					.append(MetacatUtil.getLocalReplicationServerName());
1470
			//doclist.append(util.getProperty("replicationpath"));
1471
			out.append("</server><updates>");
1472

    
1473
			// Get correct docid that reside on this server according the requesting
1474
			// server's replicate and data replicate value in xml_replication table
1475
			docsql.append(DatabaseService.getInstance().getDBAdapter().getReplicationDocumentListSQL());
1476
			//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)) ");
1477
			revisionSql.append("select docid, rev, doctype from xml_revisions ");
1478
			// If the localhost is not a hub to the remote server, only replicate
1479
			// the docid' which home server is local host (server_location =1)
1480
			if (!serverList.getHubValue(server)) {
1481
				String serverLocationDoc = " and a.server_location = 1";
1482
				String serverLocationRev = "where server_location = 1";
1483
				docsql.append(serverLocationDoc);
1484
				revisionSql.append(serverLocationRev);
1485
			}
1486
			logReplication.info("ReplicationService.handleUpdateRequest - Doc sql: " + docsql.toString());
1487

    
1488
			// Get any deleted documents
1489
			StringBuffer delsql = new StringBuffer();
1490
			delsql.append("SELECT t1.docid FROM xml_revisions t1 LEFT JOIN xml_documents t2 on t1.docid = t2.docid WHERE t2.docid IS NULL "); 
1491
			
1492
			// If the localhost is not a hub to the remote server, only replicate
1493
			// the docid' which home server is local host (server_location =1)
1494
			if (!serverList.getHubValue(server)) {
1495
				delsql.append("and t1.server_location = 1");
1496
			}
1497
			logReplication.info("ReplicationService.handleUpdateRequest - Deleted sql: " + delsql.toString());
1498

    
1499
			// Get docid list of local host
1500
			pstmt = dbConn.prepareStatement(docsql.toString());
1501
			pstmt.execute();
1502
			ResultSet rs = pstmt.getResultSet();
1503
			boolean tablehasrows = rs.next();
1504
			//If metacat configed to replicate data file
1505
			//if ((util.getProperty("replicationsenddata")).equals("on"))
1506
			boolean replicateData = serverList.getDataReplicationValue(server);
1507
			if (replicateData) {
1508
				while (tablehasrows) {
1509
					String recordDoctype = rs.getString(3);
1510
					Vector<String> packagedoctypes = MetacatUtil
1511
							.getOptionList(PropertyService
1512
									.getProperty("xml.packagedoctype"));
1513
					//if this is a package file, put it at the end
1514
					//because if a package file is read before all of the files it
1515
					//refers to are loaded then there is an error
1516
					if (recordDoctype != null && !packagedoctypes.contains(recordDoctype)) {
1517
						//If this is not data file
1518
						if (!recordDoctype.equals("BIN")) {
1519
							//for non-data file document
1520
							out.append("<updatedDocument>");
1521
							out.append("<docid>").append(rs.getString(1));
1522
							out.append("</docid><rev>" + rs.getInt(2));
1523
							out.append("</rev>");
1524
							out.append("</updatedDocument>");
1525
						}//if
1526
						else {
1527
							//for data file document, in datafile attributes
1528
							//we put "datafile" value there
1529
							out.append("<updatedDocument>");
1530
							out.append("<docid>").append(rs.getString(1));
1531
							out.append("</docid><rev>" + rs.getInt(2));
1532
							out.append("</rev>");
1533
							out.append("<datafile>");
1534
							out.append(DATA_FILE_FLAG);
1535
							out.append("</datafile>");
1536
							out.append("</updatedDocument>");
1537
						}//else
1538
					}//if packagedoctpes
1539
					else { //the package files are saved to be put into the xml later.
1540
						Vector<String> v = new Vector<String>();
1541
						v.add(rs.getString(1));
1542
						v.add(String.valueOf(rs.getInt(2)));
1543
						packageFiles.add(v);
1544
					}//esle
1545
					tablehasrows = rs.next();
1546
				}//while
1547
			}//if
1548
			else //metacat was configured not to send data file
1549
			{
1550
				while (tablehasrows) {
1551
					String recordDoctype = rs.getString(3);
1552
					if (!recordDoctype.equals("BIN")) { //don't replicate data files
1553
						Vector<String> packagedoctypes = MetacatUtil
1554
								.getOptionList(PropertyService
1555
										.getProperty("xml.packagedoctype"));
1556
						if (recordDoctype != null
1557
								&& !packagedoctypes.contains(recordDoctype)) { //if this is a package file, put it at the end
1558
							//because if a package file is read before all of the files it
1559
							//refers to are loaded then there is an error
1560
							out.append("<updatedDocument>");
1561
							out.append("<docid>" + rs.getString(1));
1562
							out.append("</docid><rev>" + rs.getInt(2));
1563
							out.append("</rev>");
1564
							out.append("</updatedDocument>");
1565
						} else { //the package files are saved to be put into the xml later.
1566
							Vector<String> v = new Vector<String>();
1567
							v.add(rs.getString(1));
1568
							v.add(String.valueOf(rs.getInt(2)));
1569
							packageFiles.add(v);
1570
						}
1571
					}//if
1572
					tablehasrows = rs.next();
1573
				}//while
1574
			}//else
1575

    
1576
			pstmt = dbConn.prepareStatement(delsql.toString());
1577
			//usage count should increas 1
1578
			dbConn.increaseUsageCount(1);
1579

    
1580
			pstmt.execute();
1581
			rs = pstmt.getResultSet();
1582
			tablehasrows = rs.next();
1583
			while (tablehasrows) { //handle the deleted documents
1584
				out.append("<deletedDocument><docid>").append(rs.getString(1));
1585
				out.append("</docid><rev></rev></deletedDocument>");
1586
				//note that rev is always empty for deleted docs
1587
				tablehasrows = rs.next();
1588
			}
1589

    
1590
			//now we can put the package files into the xml results
1591
			for (int i = 0; i < packageFiles.size(); i++) {
1592
				Vector<String> v = packageFiles.elementAt(i);
1593
				out.append("<updatedDocument>");
1594
				out.append("<docid>").append(v.elementAt(0));
1595
				out.append("</docid><rev>");
1596
				out.append(v.elementAt(1));
1597
				out.append("</rev>");
1598
				out.append("</updatedDocument>");
1599
			}
1600
			// add revision doc list  
1601
			out.append(prepareRevisionDoc(dbConn, revisionSql.toString(),
1602
					replicateData));
1603

    
1604
			out.append("</updates></replication>");
1605
			logReplication.info("ReplicationService.handleUpdateRequest - done writing to output stream.");
1606
			pstmt.close();
1607
			//conn.close();
1608

    
1609
		} catch (Exception e) {
1610
			logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1611
			logReplication.error("ReplicationService.handleUpdateRequest - error in MetacatReplication." + "handleupdaterequest: "
1612
					+ e.getMessage());
1613
			//e.printStackTrace(System.out);
1614
			try {
1615
				out.write("<error>" + e.getMessage() + "</error>");
1616
			} catch (IOException e1) {
1617
				logMetacat.error(e1.getMessage(), e1);
1618
			}
1619
		} finally {
1620
			try {
1621
				pstmt.close();
1622
			}//try
1623
			catch (SQLException ee) {
1624
				logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1625
				logReplication.error("ReplicationService.handleUpdateRequest - Error in MetacatReplication."
1626
						+ "handleUpdaterequest to close pstmt: " + ee.getMessage());
1627
			}//catch
1628
			finally {
1629
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1630
			}//finally
1631
			try {
1632
				out.close();
1633
			} catch (IOException e) {
1634
				logMetacat.error(e.getMessage(), e);
1635
			}
1636
		}//finally
1637

    
1638
	}//handlUpdateRequest
1639

    
1640
	/**
1641
	 * 
1642
	 * @param dbConn connection for doing the update
1643
	 * @param docid the document id to update
1644
	 * @param owner the user_owner
1645
	 * @param updater the user_updated
1646
	 * @throws SQLException
1647
	 */
1648
	public static void updateUserOwner(DBConnection dbConn, String docid, String owner, String updater) throws SQLException {
1649
	
1650
		String sql = 
1651
			"UPDATE xml_documents " +
1652
			"SET user_owner = ?, " +
1653
			"user_updated = ? " +
1654
			"WHERE docid = ?;";
1655
		PreparedStatement pstmt = dbConn.prepareStatement(sql);
1656
		//usage count should increas 1
1657
		dbConn.increaseUsageCount(1);
1658

    
1659
		docid = DocumentUtil.getSmartDocId(docid);
1660
		pstmt.setString(1, owner);
1661
		pstmt.setString(2, updater);
1662
		pstmt.setString(3, docid);
1663
		pstmt.execute();
1664
		pstmt.close();
1665
		
1666
		dbConn.commit();
1667
	}
1668
	
1669
	/*
1670
	 * This method will get the xml string for document in xml_revision
1671
	 * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1672
	 */
1673
	private static String prepareRevisionDoc(DBConnection dbConn, String revSql,
1674
			boolean replicateData) throws Exception {
1675
		logReplication.warn("ReplicationService.prepareRevisionDoc - The revision document sql is " + revSql);
1676
		StringBuffer revDocList = new StringBuffer();
1677
		PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1678
		//usage count should increas 1
1679
		dbConn.increaseUsageCount(1);
1680

    
1681
		pstmt.execute();
1682
		ResultSet rs = pstmt.getResultSet();
1683
		logReplication.warn("Processing replication revision for documents");
1684
		while (rs.next()) {
1685
			String recordDoctype = rs.getString(3);
1686

    
1687
			//If this is data file and it isn't configured to replicate data
1688
			if (recordDoctype.equals("BIN") && !replicateData) {
1689
				logMetacat.debug("SKipping data file because data replication is not configured");
1690

    
1691
				// do nothing
1692
			} else {
1693
				String docid = rs.getString(1);
1694
				int rev = rs.getInt(2);
1695
				logMetacat.debug("Processing replication revision for docid: " + docid + "." + rev);
1696

    
1697
				revDocList.append("<revisionDocument>");
1698
				revDocList.append("<docid>").append(docid);
1699
				revDocList.append("</docid><rev>").append(rev);
1700
				revDocList.append("</rev>");
1701
				// data file
1702
				if (recordDoctype.equals("BIN")) {
1703
					revDocList.append("<datafile>");
1704
					revDocList.append(DATA_FILE_FLAG);
1705
					revDocList.append("</datafile>");
1706
				}
1707
				revDocList.append("</revisionDocument>");
1708

    
1709
			}//else
1710
		}
1711
		//System.out.println("The revision list is"+ revDocList.toString());
1712
		return revDocList.toString();
1713
	}
1714

    
1715
	/**
1716
	 * Returns the xml_catalog table encoded in xml
1717
	 */
1718
	public static String getCatalogXML() {
1719
		return handleGetCatalogRequest(null, null, false);
1720
	}
1721

    
1722
	/**
1723
	 * Sends the contents of the xml_catalog table encoded in xml
1724
	 * The xml format is:
1725
	 * <!ELEMENT xml_catalog (row*)>
1726
	 * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1727
	 *                system_id)>
1728
	 * All of the sub elements of row are #PCDATA
1729

    
1730
	 * If printFlag == false then do not print to out.
1731
	 */
1732
	protected static String handleGetCatalogRequest(
1733
			Hashtable<String, String[]> params, HttpServletResponse response,
1734
			boolean printFlag) {
1735
		DBConnection dbConn = null;
1736
		int serialNumber = -1;
1737
		PreparedStatement pstmt = null;
1738
		Writer out = null;
1739
		try {
1740
			// get writer, TODO: encoding?
1741
		    if(printFlag)
1742
		    {
1743
		        response.setContentType("text/xml");
1744
		        out = response.getWriter();
1745
		    }
1746
			/*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1747
			                                          "handleGetCatalogRequest");*/
1748
			dbConn = DBConnectionPool
1749
					.getDBConnection("MetacatReplication.handleGetCatalogRequest");
1750
			serialNumber = dbConn.getCheckOutSerialNumber();
1751
			pstmt = dbConn.prepareStatement("select entry_type, "
1752
					+ "source_doctype, target_doctype, public_id, "
1753
					+ "system_id from xml_catalog");
1754
			pstmt.execute();
1755
			ResultSet rs = pstmt.getResultSet();
1756
			boolean tablehasrows = rs.next();
1757
			StringBuffer sb = new StringBuffer();
1758
			sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1759
			while (tablehasrows) {
1760
				sb.append("<row><entry_type>").append(rs.getString(1));
1761
				sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1762
				sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1763
				sb.append("</target_doctype><public_id>").append(rs.getString(4));
1764
				// system id may not have server url on front.  Add it if not.
1765
				String systemID = rs.getString(5);
1766
				if (!systemID.startsWith("http://")) {
1767
					systemID = SystemUtil.getContextURL() + systemID;
1768
				}
1769
				sb.append("</public_id><system_id>").append(systemID);
1770
				sb.append("</system_id></row>");
1771

    
1772
				tablehasrows = rs.next();
1773
			}
1774
			sb.append("</xml_catalog>");
1775
			//conn.close();
1776
			if (printFlag) {
1777
				response.setContentType("text/xml");
1778
				out.write(sb.toString());
1779
			}
1780
			pstmt.close();
1781
			return sb.toString();
1782
		} catch (Exception e) {
1783
			logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1784
			logReplication.error("ReplicationService.handleGetCatalogRequest - error in MetacatReplication.handleGetCatalogRequest:"
1785
					+ e.getMessage());
1786
			e.printStackTrace(System.out);
1787
			if (printFlag) {
1788
				try {
1789
					out.write("<error>" + e.getMessage() + "</error>");
1790
				} catch (IOException e1) {
1791
					logMetacat.error(e1.getMessage(), e1);
1792
				}
1793
			}
1794
		} finally {
1795
			try {
1796
				pstmt.close();
1797
			}//try
1798
			catch (SQLException ee) {
1799
				logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1800
				logReplication.error("ReplicationService.handleGetCatalogRequest - Error in MetacatReplication.handleGetCatalogRequest: "
1801
						+ ee.getMessage());
1802
			}//catch
1803
			finally {
1804
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1805
			}//finally
1806
			if (out != null) {
1807
				try {
1808
					out.close();
1809
				} catch (IOException e1) {
1810
					logMetacat.error(e1.getMessage(), e1);
1811
				}
1812
			}
1813
		}//finally
1814

    
1815
		return null;
1816
	}
1817

    
1818
	/**
1819
	 * Sends the current system date to the remote server.  Using this action
1820
	 * for replication gets rid of any problems with syncronizing clocks
1821
	 * because a time specific to a document is always kept on its home server.
1822
	 */
1823
	protected static void handleGetTimeRequest(
1824
			Hashtable<String, String[]> params, HttpServletResponse response) {
1825
		
1826
		// use standard format -- the receiving end wants this too
1827
		String dateString = DateTimeMarshaller.serializeDateToUTC(Calendar.getInstance().getTime());
1828
		
1829
		// get a writer for sending back to response
1830
		response.setContentType("text/xml");
1831
		Writer out = null;
1832
		try {
1833
			out = response.getWriter();
1834
			out.write("<timestamp>" + dateString + "</timestamp>");
1835
			out.close();
1836
		} catch (IOException e) {
1837
			logMetacat.error(e.getMessage(), e);
1838
		}
1839
		
1840
	}
1841

    
1842
	/**
1843
	 * this method handles the timeout for a file lock.  when a lock is
1844
	 * granted it is granted for 30 seconds.  When this thread runs out
1845
	 * it deletes the docid from the queue, thus eliminating the lock.
1846
	 */
1847
	public void run() {
1848
		try {
1849
			logReplication.info("ReplicationService.run - thread started for docid: "
1850
					+ (String) fileLocks.elementAt(0));
1851

    
1852
			Thread.sleep(30000); //the lock will expire in 30 seconds
1853
			logReplication.info("thread for docid: "
1854
					+ (String) fileLocks.elementAt(fileLocks.size() - 1) + " exiting.");
1855

    
1856
			fileLocks.remove(fileLocks.size() - 1);
1857
			//fileLocks is treated as a FIFO queue.  If there are more than one lock
1858
			//in the vector, the first one inserted will be removed.
1859
		} catch (Exception e) {
1860
			logMetacat.error("ReplicationService.run - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1861
			logReplication.error("ReplicationService.run - error in file lock thread from "
1862
					+ "MetacatReplication.run: " + e.getMessage());
1863
		}
1864
	}
1865

    
1866
	/**
1867
	 * Returns the name of a server given a serverCode
1868
	 * @param serverCode the serverid of the server
1869
	 * @return the servername or null if the specified serverCode does not
1870
	 *         exist.
1871
	 */
1872
	public static String getServerNameForServerCode(int serverCode) {
1873
		//System.out.println("serverid: " + serverCode);
1874
		DBConnection dbConn = null;
1875
		int serialNumber = -1;
1876
		PreparedStatement pstmt = null;
1877
		try {
1878
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServer");
1879
			serialNumber = dbConn.getCheckOutSerialNumber();
1880
			String sql = new String("select server from "
1881
					+ "xml_replication where serverid = ?");
1882
			pstmt = dbConn.prepareStatement(sql);
1883
			pstmt.setInt(1, serverCode);
1884
			//System.out.println("getserver sql: " + sql);
1885
			pstmt.execute();
1886
			ResultSet rs = pstmt.getResultSet();
1887
			boolean tablehasrows = rs.next();
1888
			if (tablehasrows) {
1889
				//System.out.println("server: " + rs.getString(1));
1890
				return rs.getString(1);
1891
			}
1892

    
1893
			//conn.close();
1894
		} catch (Exception e) {
1895
			logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1896
			logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplication.getServer: " + e.getMessage());
1897
		} finally {
1898
			try {
1899
				pstmt.close();
1900
			}//try
1901
			catch (SQLException ee) {
1902
				logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1903
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacactReplication.getserver: "
1904
						+ ee.getMessage());
1905
			}//catch
1906
			finally {
1907
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1908
			}//fianlly
1909
		}//finally
1910

    
1911
		return null;
1912
		//return null if the server does not exist
1913
	}
1914

    
1915
	/**
1916
	 * Returns a server code given a server name
1917
	 * @param server the name of the server
1918
	 * @return integer > 0 representing the code of the server, 0 if the server
1919
	 *  does not exist.
1920
	 */
1921
	public static int getServerCodeForServerName(String server) throws ServiceException {
1922
		DBConnection dbConn = null;
1923
		int serialNumber = -1;
1924
		PreparedStatement pstmt = null;
1925
		int serverCode = 0;
1926

    
1927
		try {
1928

    
1929
			//conn = util.openDBConnection();
1930
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServerCode");
1931
			serialNumber = dbConn.getCheckOutSerialNumber();
1932
			pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication "
1933
					+ "WHERE server LIKE ?");
1934
			pstmt.setString(1, server);
1935
			pstmt.execute();
1936
			ResultSet rs = pstmt.getResultSet();
1937
			boolean tablehasrows = rs.next();
1938
			if (tablehasrows) {
1939
				serverCode = rs.getInt(1);
1940
				pstmt.close();
1941
				//conn.close();
1942
				return serverCode;
1943
			}
1944

    
1945
		} catch (SQLException sqle) {
1946
			throw new ServiceException("ReplicationService.getServerCodeForServerName - " 
1947
					+ "SQL error when getting server code: " + sqle.getMessage());
1948

    
1949
		} finally {
1950
			try {
1951
				pstmt.close();
1952
				//conn.close();
1953
			}//try
1954
			catch (Exception ee) {
1955
				logMetacat.error("ReplicationService.getServerCodeForServerName - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1956
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplicatio.getServerCode: "
1957
						+ ee.getMessage());
1958

    
1959
			}//catch
1960
			finally {
1961
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1962
			}//finally
1963
		}//finally
1964

    
1965
		return serverCode;
1966
	}
1967

    
1968
	/**
1969
	 * Method to get a host server information for given docid
1970
	 * @param conn a connection to the database
1971
	 */
1972
	public static Hashtable<String, String> getHomeServerInfoForDocId(String docId) {
1973
		Hashtable<String, String> sl = new Hashtable<String, String>();
1974
		DBConnection dbConn = null;
1975
		int serialNumber = -1;
1976
		docId = DocumentUtil.getDocIdFromString(docId);
1977
		PreparedStatement pstmt = null;
1978
		int serverLocation;
1979
		try {
1980
			//get conection
1981
			dbConn = DBConnectionPool.getDBConnection("ReplicationHandler.getHomeServer");
1982
			serialNumber = dbConn.getCheckOutSerialNumber();
1983
			//get a server location from xml_document table
1984
			pstmt = dbConn.prepareStatement("select server_location from xml_documents "
1985
					+ "where docid = ?");
1986
			pstmt.setString(1, docId);
1987
			pstmt.execute();
1988
			ResultSet serverName = pstmt.getResultSet();
1989
			//get a server location
1990
			if (serverName.next()) {
1991
				serverLocation = serverName.getInt(1);
1992
				pstmt.close();
1993
			} else {
1994
				pstmt.close();
1995
				//ut.returnConnection(conn);
1996
				return null;
1997
			}
1998
			pstmt = dbConn.prepareStatement("select server, last_checked, replicate "
1999
					+ "from xml_replication where serverid = ?");
2000
			//increase usage count
2001
			dbConn.increaseUsageCount(1);
2002
			pstmt.setInt(1, serverLocation);
2003
			pstmt.execute();
2004
			ResultSet rs = pstmt.getResultSet();
2005
			boolean tableHasRows = rs.next();
2006
			if (tableHasRows) {
2007

    
2008
				String server = rs.getString(1);
2009
				String last_checked = rs.getString(2);
2010
				if (!server.equals("localhost")) {
2011
					sl.put(server, last_checked);
2012
				}
2013

    
2014
			} else {
2015
				pstmt.close();
2016
				//ut.returnConnection(conn);
2017
				return null;
2018
			}
2019
			pstmt.close();
2020
		} catch (Exception e) {
2021
			logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2022
			logReplication.error("ReplicationService.getHomeServerInfoForDocId - error in replicationHandler.getHomeServer(): "
2023
					+ e.getMessage());
2024
		} finally {
2025
			try {
2026
				pstmt.close();
2027
				//ut.returnConnection(conn);
2028
			} catch (Exception ee) {
2029
				logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2030
				logReplication.error("ReplicationService.getHomeServerInfoForDocId - Eror irn rplicationHandler.getHomeServer() "
2031
						+ "to close pstmt: " + ee.getMessage());
2032
			} finally {
2033
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2034
			}
2035

    
2036
		}//finally
2037
		return sl;
2038
	}
2039

    
2040
	/**
2041
	 * Returns a home server location  given a accnum
2042
	 * @param accNum , given accNum for a document
2043
	 *
2044
	 */
2045
	public static int getHomeServerCodeForDocId(String accNum) throws ServiceException {
2046
		DBConnection dbConn = null;
2047
		int serialNumber = -1;
2048
		PreparedStatement pstmt = null;
2049
		int serverCode = 1;
2050
		String docId = DocumentUtil.getDocIdFromString(accNum);
2051

    
2052
		try {
2053

    
2054
			// Get DBConnection
2055
			dbConn = DBConnectionPool
2056
					.getDBConnection("ReplicationHandler.getServerLocation");
2057
			serialNumber = dbConn.getCheckOutSerialNumber();
2058
			pstmt = dbConn.prepareStatement("SELECT server_location FROM xml_documents "
2059
					+ "WHERE docid LIKE ? ");
2060
			pstmt.setString(1, docId);
2061
			pstmt.execute();
2062
			ResultSet rs = pstmt.getResultSet();
2063
			boolean tablehasrows = rs.next();
2064
			//If a document is find, return the server location for it
2065
			if (tablehasrows) {
2066
				serverCode = rs.getInt(1);
2067
				pstmt.close();
2068
				//conn.close();
2069
				return serverCode;
2070
			}
2071
			//if couldn't find in xml_documents table, we think server code is 1
2072
			//(this is new document)
2073
			else {
2074
				pstmt.close();
2075
				//conn.close();
2076
				return serverCode;
2077
			}
2078

    
2079
		} catch (SQLException sqle) {
2080
			throw new ServiceException("ReplicationService.getHomeServerCodeForDocId - " 
2081
					+ "SQL error when getting home server code for docid: " + docId + " : " 
2082
					+ sqle.getMessage());
2083

    
2084
		} finally {
2085
			try {
2086
				pstmt.close();
2087
				//conn.close();
2088

    
2089
			} catch (SQLException sqle) {
2090
				logMetacat.error("ReplicationService.getHomeServerCodeForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2091
				logReplication.error("ReplicationService.getHomeServerCodeForDocId - ReplicationService.getHomeServerCodeForDocId - " 
2092
						+ "SQL error when getting home server code for docid: " + docId + " : " 
2093
						+ sqle.getMessage());
2094
			} finally {
2095
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2096
			}//finally
2097
		}//finally
2098
		//return serverCode;
2099
	}
2100

    
2101
	/**
2102
	 * This method returns the content of a url
2103
	 * @param u the url to return the content from
2104
	 * @return a string representing the content of the url
2105
	 * @throws java.io.IOException
2106
	 */
2107
	public static String getURLContent(URL u) throws java.io.IOException {
2108
		char istreamChar;
2109
		int istreamInt;
2110
		// get the response content
2111
		InputStream input = getURLStream(u);
2112
		logReplication.info("ReplicationService.getURLContent - After getting response from: " + u.toString());
2113
		InputStreamReader istream = new InputStreamReader(input);
2114
		StringBuffer serverResponse = new StringBuffer();
2115
		while ((istreamInt = istream.read()) != -1) {
2116
			istreamChar = (char) istreamInt;
2117
			serverResponse.append(istreamChar);
2118
		}
2119
		istream.close();
2120
		input.close();
2121

    
2122
		return serverResponse.toString();
2123
	}
2124
	
2125
	/**
2126
	 * This method returns the InputStream after opening a url
2127
	 * @param u the url to return the content from
2128
	 * @return a InputStream representing the content of the url
2129
	 * @throws java.io.IOException
2130
	 */
2131
	public static InputStream getURLStream(URL u) throws java.io.IOException {
2132
	    logReplication.info("Getting url stream from " + u.toString());
2133
		logReplication.info("ReplicationService.getURLStream - Before sending request to: " + u.toString());
2134
		// use httpclient to set up SSL
2135
		RestClient client = getSSLClient();
2136
		HttpResponse response = client.doGetRequest(u.toString());
2137
		// get the response content
2138
		InputStream input = response.getEntity().getContent();
2139
		logReplication.info("ReplicationService.getURLStream - After getting response from: " + u.toString());
2140
		
2141
		return input;		
2142
	}
2143
	
2144
	/**
2145
	 * Sets up an HttpClient with SSL connection.
2146
	 * Sends client certificate to the server when doing the request.
2147
	 * @return
2148
	 */
2149
	private static RestClient getSSLClient() {
2150
		RestClient client = new RestClient();
2151
		
2152
		// set up this server's client identity
2153
		String subject = null;
2154
		try {
2155
			// TODO: should there be alternative ways to get the key and certificate?
2156
			String certificateFile = PropertyService.getProperty("replication.certificate.file");
2157
	    	String keyFile = PropertyService.getProperty("replication.privatekey.file");
2158
			String keyPassword = PropertyService.getProperty("replication.privatekey.password");
2159
			X509Certificate certificate = CertificateManager.getInstance().loadCertificateFromFile(certificateFile);
2160
			PrivateKey privateKey = CertificateManager.getInstance().loadPrivateKeyFromFile(keyFile, keyPassword);
2161
			subject = CertificateManager.getInstance().getSubjectDN(certificate);
2162
			CertificateManager.getInstance().registerCertificate(subject, certificate, privateKey);
2163
		} catch (Exception e) {
2164
			// this is pretty much required for replication communication
2165
			logReplication.warn("Could not find server's client certificate/private key: " + e.getMessage());
2166
		}
2167
		
2168
		// set the configured timeout
2169
		client.setTimeouts(CLIENTTIMEOUT);
2170

    
2171
		SSLSocketFactory socketFactory = null;
2172
		try {
2173
			socketFactory = CertificateManager.getInstance().getSSLSocketFactory(subject);
2174
		} catch (FileNotFoundException e) {
2175
			// these are somewhat expected for anonymous client use
2176
			logReplication.warn("Could not set up SSL connection for client - likely because the certificate could not be located: " + e.getMessage());
2177
		} catch (Exception e) {
2178
			// this is likely more severe
2179
			logReplication.warn("Funky SSL going on: " + e.getClass() + ":: " + e.getMessage());
2180
		}
2181
		try {
2182
			//443 is the default port, this value is overridden if explicitly set in the URL
2183
			Scheme sch = new Scheme("https", 443, socketFactory);
2184
			client.getHttpClient().getConnectionManager().getSchemeRegistry().register(sch);
2185
		} catch (Exception e) {
2186
			// this is likely more severe
2187
			logReplication.error("Failed to set up SSL connection for client. Continuing. " + e.getClass() + ":: " + e.getMessage(), e);
2188
		}
2189
		return client;
2190
	}
2191
	
2192

    
2193
//	/**
2194
//	 * Method for writing replication messages to a log file specified in
2195
//	 * metacat.properties
2196
//	 */
2197
//	public static void replLog(String message) {
2198
//		try {
2199
//			FileOutputStream fos = new FileOutputStream(PropertyService
2200
//					.getProperty("replication.logdir")
2201
//					+ "/metacatreplication.log", true);
2202
//			PrintWriter pw = new PrintWriter(fos);
2203
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
2204
//			java.util.Date localtime = new java.util.Date();
2205
//			String dateString = formatter.format(localtime);
2206
//			dateString += " :: " + message;
2207
//			// time stamp each entry
2208
//			pw.println(dateString);
2209
//			pw.flush();
2210
//		} catch (Exception e) {
2211
//			logReplication.error("error writing to replication log from "
2212
//					+ "MetacatReplication.replLog: " + e.getMessage());
2213
//			// e.printStackTrace(System.out);
2214
//		}
2215
//	}
2216

    
2217
//	/**
2218
//	 * Method for writing replication messages to a log file specified in
2219
//	 * metacat.properties
2220
//	 */
2221
//	public static void replErrorLog(String message) {
2222
//		try {
2223
//			FileOutputStream fos = new FileOutputStream(PropertyService
2224
//					.getProperty("replication.logdir")
2225
//					+ "/metacatreplicationerror.log", true);
2226
//			PrintWriter pw = new PrintWriter(fos);
2227
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
2228
//			java.util.Date localtime = new java.util.Date();
2229
//			String dateString = formatter.format(localtime);
2230
//			dateString += " :: " + message;
2231
//			//time stamp each entry
2232
//			pw.println(dateString);
2233
//			pw.flush();
2234
//		} catch (Exception e) {
2235
//			logReplication.error("error writing to replication error log from "
2236
//					+ "MetacatReplication.replErrorLog: " + e.getMessage());
2237
//			//e.printStackTrace(System.out);
2238
//		}
2239
//	}
2240

    
2241
	/**
2242
	 * Returns true if the replicate field for server in xml_replication is 1.
2243
	 * Returns false otherwise
2244
	 */
2245
	public static boolean replToServer(String server) {
2246
		DBConnection dbConn = null;
2247
		int serialNumber = -1;
2248
		PreparedStatement pstmt = null;
2249
		try {
2250
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.repltoServer");
2251
			serialNumber = dbConn.getCheckOutSerialNumber();
2252
			pstmt = dbConn.prepareStatement("select replicate from "
2253
					+ "xml_replication where server like ? ");
2254
			pstmt.setString(1, server);
2255
			pstmt.execute();
2256
			ResultSet rs = pstmt.getResultSet();
2257
			boolean tablehasrows = rs.next();
2258
			if (tablehasrows) {
2259
				int i = rs.getInt(1);
2260
				if (i == 1) {
2261
					pstmt.close();
2262
					//conn.close();
2263
					return true;
2264
				} else {
2265
					pstmt.close();
2266
					//conn.close();
2267
					return false;
2268
				}
2269
			}
2270
		} catch (SQLException sqle) {
2271
			logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2272
			logReplication.error("ReplicationService.replToServer - SQL error in MetacatReplication.replToServer: "
2273
					+ sqle.getMessage());
2274
		} finally {
2275
			try {
2276
				pstmt.close();
2277
				//conn.close();
2278
			}//try
2279
			catch (Exception ee) {
2280
				logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2281
				logReplication.error("ReplicationService.replToServer - Error in MetacatReplication.replToServer: "
2282
						+ ee.getMessage());
2283
			}//catch
2284
			finally {
2285
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2286
			}//finally
2287
		}//finally
2288
		return false;
2289
		//the default if this server does not exist is to not replicate to it.
2290
	}
2291

    
2292
}
(6-6/7)