Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements replication for metacat
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Chad Berkley
7
 *
8
 *   '$Author: leinfelder $'
9
 *     '$Date: 2011-06-02 16:40:41 -0700 (Thu, 02 Jun 2011) $'
10
 * '$Revision: 6119 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

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

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

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

    
59
import org.apache.log4j.Logger;
60
import org.dataone.service.types.SystemMetadata;
61
import org.dataone.service.types.util.ServiceTypeUtil;
62
import org.xml.sax.InputSource;
63
import org.xml.sax.SAXException;
64
import org.xml.sax.XMLReader;
65

    
66
import edu.ucsb.nceas.metacat.DocInfoHandler;
67
import edu.ucsb.nceas.metacat.DocumentImpl;
68
import edu.ucsb.nceas.metacat.DocumentImplWrapper;
69
import edu.ucsb.nceas.metacat.EventLog;
70
import edu.ucsb.nceas.metacat.IdentifierManager;
71
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
72
import edu.ucsb.nceas.metacat.McdbException;
73
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlException;
74
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
75
import edu.ucsb.nceas.metacat.accesscontrol.PermOrderException;
76
import edu.ucsb.nceas.metacat.accesscontrol.XMLAccessDAO;
77
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
78
import edu.ucsb.nceas.metacat.database.DBConnection;
79
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
80
import edu.ucsb.nceas.metacat.database.DatabaseService;
81
import edu.ucsb.nceas.metacat.properties.PropertyService;
82
import edu.ucsb.nceas.metacat.shared.BaseService;
83
import edu.ucsb.nceas.metacat.shared.HandlerException;
84
import edu.ucsb.nceas.metacat.shared.ServiceException;
85
import edu.ucsb.nceas.metacat.util.DocumentUtil;
86
import edu.ucsb.nceas.metacat.util.MetacatUtil;
87
import edu.ucsb.nceas.metacat.util.ReplicationUtil;
88
import edu.ucsb.nceas.metacat.util.SystemUtil;
89
import edu.ucsb.nceas.utilities.FileUtil;
90
import edu.ucsb.nceas.utilities.GeneralPropertyException;
91
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
92

    
93
public class ReplicationService extends BaseService {
94

    
95
	private static ReplicationService replicationService = null;
96

    
97
	private long timeInterval;
98
	private Date firstTime;
99
	private boolean timedReplicationIsOn = false;
100
	Timer replicationDaemon;
101
	private static Vector<String> fileLocks = new Vector<String>();
102
//	private Thread lockThread = null;
103
	public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
104
	private static String TIMEREPLICATION = "replication.timedreplication";
105
	private static String TIMEREPLICATIONINTERVAl ="replication.timedreplicationinterval";
106
	private static String FIRSTTIME = "replication.firsttimedreplication";
107
	private static final int TIMEINTERVALLIMIT = 7200000;
108
	public static final String REPLICATIONUSER = "replication";
109

    
110
	public static final String REPLICATION_LOG_FILE_NAME = "metacatreplication.log";
111
	public static String METACAT_REPL_ERROR_MSG = null;
112
	private static Logger logReplication = Logger.getLogger("ReplicationLogging");
113
	private static Logger logMetacat = Logger.getLogger(ReplicationService.class);
114

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

    
139
			String timeIntervalStr = 
140
				PropertyService.getProperty("replication.timedreplicationinterval");
141
			timeInterval = (new Long(timeIntervalStr)).longValue();
142
			logReplication.info("ReplicationService.initialize - The timed replication time Interval is " + timeInterval);
143

    
144
			String firstTimeStr = 
145
				PropertyService.getProperty("replication.firsttimedreplication");
146
			logReplication.info("ReplicationService.initialize - first replication time form property is " + firstTimeStr);
147
			firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
148

    
149
			logReplication.info("ReplicationService.initialize - After combine current time, the real first time is "
150
					+ firstTime.toString() + " minisec");
151

    
152
			// set up time replication if it is on
153
			if (timedReplicationIsOn) {
154
				replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(),
155
						firstTime, timeInterval);
156
				logReplication.info("ReplicationService.initialize - deltaT handler started with rate="
157
						+ timeInterval + " mini seconds at " + firstTime.toString());
158
			}
159

    
160
		} catch (PropertyNotFoundException pnfe) {
161
			throw new ServiceException(
162
					"ReplicationService.initialize - Property error while instantiating "
163
							+ "replication service: " + pnfe.getMessage());
164
		} catch (HandlerException he) {
165
			throw new ServiceException(
166
					"ReplicationService.initialize - Handler error while instantiating "
167
							+ "replication service" + he.getMessage());
168
		} 
169
	}
170

    
171
	/**
172
	 * Get the single instance of SessionService.
173
	 * 
174
	 * @return the single instance of SessionService
175
	 */
176
	public static ReplicationService getInstance() throws ServiceException {
177
		if (replicationService == null) {
178
			replicationService = new ReplicationService();
179
		}
180
		return replicationService;
181
	}
182

    
183
	public boolean refreshable() {
184
		return true;
185
	}
186

    
187
	protected void doRefresh() throws ServiceException {
188
		return;
189
	}
190
	
191
	public void stop() throws ServiceException{
192
		
193
	}
194

    
195
	public void stopReplication() throws ServiceException {
196
	      //stop the replication server
197
	      replicationDaemon.cancel();
198
	      replicationDaemon = new Timer(true);
199
	      timedReplicationIsOn = false;
200
	      try {
201
	    	  PropertyService.setProperty("replication.timedreplication", (new Boolean(timedReplicationIsOn)).toString());
202
	      } catch (GeneralPropertyException gpe) {
203
	    	  logReplication.warn("ReplicationService.stopReplication - Could not set replication.timedreplication property: " + gpe.getMessage());
204
	      }
205

    
206
	      logReplication.info("ReplicationService.stopReplication - deltaT handler stopped");
207
		return;
208
	}
209
	
210
	protected void startReplication(Hashtable<String, String[]> params) throws ServiceException {
211

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

    
269
	}
270
	
271
	public void runOnce() throws ServiceException {
272
	      //updates this server exactly once
273
	      replicationDaemon.schedule(new ReplicationHandler(), 0);
274
	}
275

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

    
305
			// add server to server list
306
			if (subaction.equals("add")) {
307
				replicate = ((String[]) params.get("replicate"))[0];
308
				server = ((String[]) params.get("server"))[0];
309

    
310
				//Get data replication value
311
				dataReplicate = ((String[]) params.get("datareplicate"))[0];
312
				//Get hub value
313
				hub = ((String[]) params.get("hub"))[0];
314

    
315
				String toDateSql = DatabaseService.getInstance().getDBAdapter().toDate("01/01/1980","MM/DD/YYYY");
316
				String sql = "INSERT INTO xml_replication "
317
						+ "(server, last_checked, replicate, datareplicate, hub) "
318
						+ "VALUES (?," + toDateSql + ",?,?,?)";
319
				
320
				pstmt = dbConn.prepareStatement(sql);
321
						
322
				pstmt.setString(1, server);
323
				pstmt.setInt(2, Integer.parseInt(replicate));
324
				pstmt.setInt(3, Integer.parseInt(dataReplicate));
325
				pstmt.setInt(4, Integer.parseInt(hub));
326
				
327
				String sqlReport = "XMLAccessAccess.getXMLAccessForDoc - SQL: " + sql;
328
				sqlReport += " [" + server + "," + replicate + 
329
					"," + dataReplicate + "," + hub + "]";
330
				
331
				logMetacat.info(sqlReport);
332
				
333
				pstmt.execute();
334
				pstmt.close();
335
				dbConn.commit();
336
				out.write("Server " + server + " added");
337
				response.setContentType("text/html");
338
				out.write("<html><body><table border=\"1\">");
339
				out.write("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
340
				out.write("<b>replicate</b></td>");
341
				out.write("<td><b>datareplicate</b></td>");
342
				out.write("<td><b>hub</b></td></tr>");
343
				pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
344
				//increase dbconnection usage
345
				dbConn.increaseUsageCount(1);
346

    
347
				pstmt.execute();
348
				ResultSet rs = pstmt.getResultSet();
349
				boolean tablehasrows = rs.next();
350
				while (tablehasrows) {
351
					out.write("<tr><td>" + rs.getString(2) + "</td><td>");
352
					out.write(rs.getString(3) + "</td><td>");
353
					out.write(rs.getString(4) + "</td><td>");
354
					out.write(rs.getString(5) + "</td><td>");
355
					out.write(rs.getString(6) + "</td></tr>");
356

    
357
					tablehasrows = rs.next();
358
				}
359
				out.write("</table></body></html>");
360

    
361
				// download certificate with the public key on this server
362
				// and import it as a trusted certificate
363
				String certURL = ((String[]) params.get("certificate"))[0];
364
				if (certURL != null && !certURL.equals("")) {
365
					downloadCertificate(certURL);
366
				}
367

    
368
				// delete server from server list
369
			} else if (subaction.equals("delete")) {
370
				server = ((String[]) params.get("server"))[0];
371
				pstmt = dbConn.prepareStatement("DELETE FROM xml_replication "
372
						+ "WHERE server LIKE '" + server + "'");
373
				pstmt.execute();
374
				pstmt.close();
375
				dbConn.commit();
376
				out.write("Server " + server + " deleted");
377
				response.setContentType("text/html");
378
				out.write("<html><body><table border=\"1\">");
379
				out.write("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
380
				out.write("<b>replicate</b></td>");
381
				out.write("<td><b>datareplicate</b></td>");
382
				out.write("<td><b>hub</b></td></tr>");
383

    
384
				pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
385
				//increase dbconnection usage
386
				dbConn.increaseUsageCount(1);
387
				pstmt.execute();
388
				ResultSet rs = pstmt.getResultSet();
389
				boolean tablehasrows = rs.next();
390
				while (tablehasrows) {
391
					out.write("<tr><td>" + rs.getString(2) + "</td><td>");
392
					out.write(rs.getString(3) + "</td><td>");
393
					out.write(rs.getString(4) + "</td><td>");
394
					out.write(rs.getString(5) + "</td><td>");
395
					out.write(rs.getString(6) + "</td></tr>");
396
					tablehasrows = rs.next();
397
				}
398
				out.write("</table></body></html>");
399

    
400
				// list servers in server list
401
			} else if (subaction.equals("list")) {
402
				response.setContentType("text/html");
403
				out.write("<html><body><table border=\"1\">");
404
				out.write("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
405
				out.write("<b>replicate</b></td>");
406
				out.write("<td><b>datareplicate</b></td>");
407
				out.write("<td><b>hub</b></td></tr>");
408
				pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
409
				pstmt.execute();
410
				ResultSet rs = pstmt.getResultSet();
411
				boolean tablehasrows = rs.next();
412
				while (tablehasrows) {
413
					out.write("<tr><td>" + rs.getString(2) + "</td><td>");
414
					out.write(rs.getString(3) + "</td><td>");
415
					out.write(rs.getString(4) + "</td><td>");
416
					out.write(rs.getString(5) + "</td><td>");
417
					out.write(rs.getString(6) + "</td></tr>");
418
					tablehasrows = rs.next();
419
				}
420
				out.write("</table></body></html>");
421
			} else {
422

    
423
				out.write("<error>Unkonwn subaction</error>");
424

    
425
			}
426
			pstmt.close();
427
			//conn.close();
428

    
429
		} catch (Exception e) {
430
			logMetacat.error("ReplicationService.handleServerControlRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
431
			logReplication.error("ReplicationService.handleServerControlRequest - Error in "
432
					+ "MetacatReplication.handleServerControlRequest " + e.getMessage());
433
			e.printStackTrace(System.out);
434
		} finally {
435
			try {
436
				pstmt.close();
437
			}//try
438
			catch (SQLException ee) {
439
				logMetacat.error("ReplicationService.handleServerControlRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
440
				logReplication.error("ReplicationService.handleServerControlRequest - Error in MetacatReplication.handleServerControlRequest to close pstmt "
441
						+ ee.getMessage());
442
			}//catch
443
			finally {
444
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
445
			}//finally
446
			if (out != null) {
447
				try {
448
					out.close();
449
				} catch (IOException e) {
450
					logMetacat.error(e.getMessage(), e);
451
				}
452
			}
453
		}//finally
454

    
455
	}
456

    
457
	// download certificate with the public key from certURL and
458
	// upload it onto this server; it then must be imported as a
459
	// trusted certificate
460
	private static void downloadCertificate(String certURL) throws FileNotFoundException,
461
			IOException, MalformedURLException, PropertyNotFoundException {
462

    
463
		// the path to be uploaded to
464
		String certPath = SystemUtil.getContextDir();
465

    
466
		// get filename from the URL of the certificate
467
		String filename = certURL;
468
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
469
		if (slash > -1) {
470
			filename = filename.substring(slash + 1);
471
		}
472

    
473
		// open file output strem to write the input into it
474
		File f = new File(certPath, filename);
475
		synchronized (f) {
476
			try {
477
				if (f.exists()) {
478
					throw new IOException("File already exist: " + f.getCanonicalFile());
479
					// if ( f.exists() && !f.canWrite() ) {
480
					// throw new IOException("Not writable: " +
481
					// f.getCanonicalFile());
482
				}
483
			} catch (SecurityException se) {
484
				// if a security manager exists,
485
				// its checkRead method is called for f.exist()
486
				// or checkWrite method is called for f.canWrite()
487
				throw se;
488
			}
489

    
490
			// create a buffered byte output stream
491
			// that uses a default-sized output buffer
492
			FileOutputStream fos = new FileOutputStream(f);
493
			BufferedOutputStream out = new BufferedOutputStream(fos);
494

    
495
			// this should be http url
496
			URL url = new URL(certURL);
497
			BufferedInputStream bis = null;
498
			try {
499
				bis = new BufferedInputStream(url.openStream());
500
				byte[] buf = new byte[4 * 1024]; // 4K buffer
501
				int b = bis.read(buf);
502
				while (b != -1) {
503
					out.write(buf, 0, b);
504
					b = bis.read(buf);
505
				}
506
			} finally {
507
				if (bis != null)
508
					bis.close();
509
			}
510
			// the input and the output streams must be closed
511
			bis.close();
512
			out.flush();
513
			out.close();
514
			fos.close();
515
		} // end of synchronized(f)
516
	}
517

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

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

    
551
			// get the document info from server
552
			URL docinfourl = new URL("https://" + server + "?server="
553
					+ MetacatUtil.getLocalReplicationServerName()
554
					+ "&action=getdocumentinfo&docid=" + docid);
555
			
556

    
557
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
558
			// strip out the system metadata portion
559
			String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
560
			docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);
561
		   	  
562
			//dih is the parser for the docinfo xml format
563
			DocInfoHandler dih = new DocInfoHandler();
564
			XMLReader docinfoParser = ReplicationHandler.initParser(dih);
565
			docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
566
			//      Hashtable<String,Vector<AccessControlForSingleFile>> docinfoHash = dih.getDocInfo();
567
			Hashtable<String, String> docinfoHash = dih.getDocInfo();
568
			
569
			// Get home server of this docid
570
			String homeServer = (String) docinfoHash.get("home_server");
571
			
572
			// process system metadata
573
			if (systemMetadataXML != null) {
574
				SystemMetadata sysMeta = 
575
					(SystemMetadata) ServiceTypeUtil.deserializeServiceType(
576
							SystemMetadata.class,
577
							new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
578
				String guid = sysMeta.getIdentifier().getValue();
579
				if (!IdentifierManager.getInstance().identifierExists(guid)) {
580
					logReplication.debug("Creating system metadata and guid/docid mapping for docid "
581
									+ docinfoHash.get("docid")
582
									+ " and guid: "
583
									+ guid);
584
					IdentifierManager.getInstance().createMapping(guid, docinfoHash.get("docid"));
585
					IdentifierManager.getInstance().createSystemMetadata(sysMeta);
586
				} else {
587
					logReplication.debug("Updating guid/docid mapping for docid "
588
									+ docinfoHash.get("docid") + " and guid: "
589
									+ guid);
590
					IdentifierManager.getInstance().updateMapping(guid, docinfoHash.get("docid"));
591
				}
592
				IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
593
			}
594
      
595
        	// replicate doc contents
596
			String createdDate = (String) docinfoHash.get("date_created");
597
			String updatedDate = (String) docinfoHash.get("date_updated");
598
			logReplication.info("ReplicationService.handleForceReplicateRequest - homeServer: " + homeServer);
599
			// Get Document type
600
			String docType = (String) docinfoHash.get("doctype");
601
			logReplication.info("ReplicationService.handleForceReplicateRequest - docType: " + docType);
602
			String parserBase = null;
603
			// this for eml2 and we need user eml2 parser
604
			if (docType != null
605
					&& (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE)) {
606
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml200 document!");
607
				parserBase = DocumentImpl.EML200;
608
			} else if (docType != null
609
					&& (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE)) {
610
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml2.0.1 document!");
611
				parserBase = DocumentImpl.EML200;
612
			} else if (docType != null
613
					&& (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE)) {
614
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml2.1.0 document!");
615
				parserBase = DocumentImpl.EML210;
616
			} else if (docType != null
617
					&& (docType.trim()).equals(DocumentImpl.EML2_1_1NAMESPACE)) {
618
				logReplication.warn("ReplicationService.handleForceReplicateRequest - This is an eml2.1.1 document!");
619
				parserBase = DocumentImpl.EML210;
620
			}
621
			logReplication.warn("ReplicationService.handleForceReplicateRequest - The parserBase is: " + parserBase);
622

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

    
636
				//process extra access rules before dealing with the write exception (doc exist already)			
637
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
638
		        if (accessControlList != null) {
639
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
640
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
641
		        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
642
		        			acfsf.insertPermissions(xmlAccessDAO);
643
							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
644
									+ " permissions added to DB");
645
		        		}
646
		            }
647
		        }
648
		        
649
		        // process the real owner and updater
650
				String user = (String) docinfoHash.get("user_owner");
651
				String updated = (String) docinfoHash.get("user_updated");
652
		        updateUserOwner(dbConn, docid, user, updated);
653

    
654
				logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid + " added to DB with "
655
						+ "action " + dbaction);
656
				
657
				EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, dbaction);
658
			}
659
		} catch (SQLException sqle) {
660
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
661
			logReplication.error("ReplicationService.handleForceReplicateRequest - SQL error when adding doc " + docid + 
662
					" to DB with action " + dbaction + ": " + sqle.getMessage());
663
		} catch (MalformedURLException mue) {
664
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
665
			logReplication.error("ReplicationService.handleForceReplicateRequest - URL error when adding doc " + docid + 
666
					" to DB with action " + dbaction + ": " + mue.getMessage());
667
		} catch (SAXException se) {
668
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
669
			logReplication.error("ReplicationService.handleForceReplicateRequest - SAX parsing error when adding doc " + docid + 
670
					" to DB with action " + dbaction + ": " + se.getMessage());
671
		} catch (HandlerException he) {
672
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
673
			logReplication.error("ReplicationService.handleForceReplicateRequest - Handler error when adding doc " + docid + 
674
					" to DB with action " + dbaction + ": " + he.getMessage());
675
		} catch (IOException ioe) {
676
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
677
			logReplication.error("ReplicationService.handleForceReplicateRequest - I/O error when adding doc " + docid + 
678
					" to DB with action " + dbaction + ": " + ioe.getMessage());
679
		} catch (PermOrderException poe) {
680
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
681
			logReplication.error("ReplicationService.handleForceReplicateRequest - Permissions order error when adding doc " + docid + 
682
					" to DB with action " + dbaction + ": " + poe.getMessage());
683
		} catch (AccessControlException ace) {
684
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
685
			logReplication.error("ReplicationService.handleForceReplicateRequest - Permissions order error when adding doc " + docid + 
686
					" to DB with action " + dbaction + ": " + ace.getMessage());
687
		} catch (Exception e) {
688
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
689
			logReplication.error("ReplicationService.handleForceReplicateRequest - General error when adding doc " + docid + 
690
					" to DB with action " + dbaction + ": " + e.getMessage());
691
		} finally {
692
			// Return the checked out DBConnection
693
			DBConnectionPool.returnDBConnection(dbConn, serialNumber);
694
		}//finally
695
	}
696

    
697
	/*
698
	 * when a forcereplication delete request comes in, local host will delete this
699
	 * document
700
	 */
701
	protected static void handleForceReplicateDeleteRequest(
702
			Hashtable<String, String[]> params, HttpServletResponse response,
703
			HttpServletRequest request) {
704
		String server = ((String[]) params.get("server"))[0]; // the server that
705
		String docid = ((String[]) params.get("docid"))[0]; // sent the document
706
		try {
707
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete request from " + server);
708
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - force replication delete docid " + docid);
709
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete request from: " + server);
710
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - Force replication delete docid: " + docid);
711
			DocumentImpl.delete(docid, null, null, server);
712
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
713
			EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid,
714
					"delete");
715
			logReplication.info("ReplicationService.handleForceReplicateDeleteRequest - document " + docid + " was successfully deleted ");
716
		} catch (McdbDocNotFoundException e) {
717
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
718
			logReplication.error("document " + docid
719
					+ " failed to delete because " + e.getMessage());
720
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
721
		} catch (InsufficientKarmaException e) {
722
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
723
			logReplication.error("document " + docid
724
					+ " failed to delete because " + e.getMessage());
725
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
726
		} catch (SQLException e) {
727
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
728
			logReplication.error("document " + docid
729
					+ " failed to delete because " + e.getMessage());
730
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
731
		} catch (Exception e) {
732
			logMetacat.error("ReplicationService.handleForceReplicateDeleteRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
733
			logReplication.error("document " + docid
734
					+ " failed to delete because " + e.getMessage());
735
			logReplication.error("ReplicationService.handleForceReplicateDeleteRequest - error: " + e.getMessage());
736

    
737
		}//catch
738

    
739
	}
740

    
741
	/**
742
	 * when a forcereplication data file request comes in, local host sends a
743
	 * readdata request to the requesting server (remote server) for the specified
744
	 * docid. Then store it in local database and file system
745
	 */
746
	protected static void handleForceReplicateDataFileRequest(Hashtable<String, String[]> params,
747
			HttpServletRequest request) {
748

    
749
		//make sure there is some parameters
750
		if (params.isEmpty()) {
751
			return;
752
		}
753
		// Get remote server
754
		String server = ((String[]) params.get("server"))[0];
755
		// the docid should include rev number
756
		String docid = ((String[]) params.get("docid"))[0];
757
		// Make sure there is a docid and server
758
		if (docid == null || server == null || server.equals("")) {
759
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
760
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Didn't specify docid or server for replication");
761
			return;
762
		}
763

    
764
		// Overide or not
765
		//    boolean override = false;
766
		// dbaction - update or insert
767
		String dbaction = null;
768

    
769
		try {
770
			//docid was switch to two parts uinque code and rev
771
			//String uniqueCode=MetacatUtil.getDocIdFromString(docid);
772
			//int rev=MetacatUtil.getVersionFromString(docid);
773
			if (params.containsKey("dbaction")) {
774
				dbaction = ((String[]) params.get("dbaction"))[0];
775
			} else//default value is update
776
			{
777
				dbaction = "update";
778
			}
779

    
780
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication request from: " + server);
781
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication docid: " + docid);
782
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - Force replication action: " + dbaction);
783
			// get the document info from server
784
			URL docinfourl = new URL("https://" + server + "?server="
785
					+ MetacatUtil.getLocalReplicationServerName()
786
					+ "&action=getdocumentinfo&docid=" + docid);
787

    
788
			String docInfoStr = ReplicationService.getURLContent(docinfourl);
789
			
790
			// strip out the system metadata portion
791
		    String systemMetadataXML = ReplicationUtil.getSystemMetadataContent(docInfoStr);
792
		   	docInfoStr = ReplicationUtil.getContentWithoutSystemMetadata(docInfoStr);
793

    
794
			//dih is the parser for the docinfo xml format
795
			DocInfoHandler dih = new DocInfoHandler();
796
			XMLReader docinfoParser = ReplicationHandler.initParser(dih);
797
			docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
798
			Hashtable<String, String> docinfoHash = dih.getDocInfo();
799
			
800
			String docName = (String) docinfoHash.get("docname");
801

    
802
			String docType = (String) docinfoHash.get("doctype");
803

    
804
			String docHomeServer = (String) docinfoHash.get("home_server");
805

    
806
			String createdDate = (String) docinfoHash.get("date_created");
807

    
808
			String updatedDate = (String) docinfoHash.get("date_updated");
809
			logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - docHomeServer of datafile: " + docHomeServer);
810

    
811
			if (dbaction.equals("insert") || dbaction.equals("update")) {
812
				//Get data file and store it into local file system.
813
				// sending back readdata request to server
814
				URL url = new URL("https://" + server + "?server="
815
						+ MetacatUtil.getLocalReplicationServerName()
816
						+ "&action=readdata&docid=" + docid);
817
				String datafilePath = PropertyService
818
						.getProperty("application.datafilepath");
819

    
820
				Exception writeException = null;
821
				//register data file into xml_documents table and wite data file
822
				//into file system
823
				try {
824
					DocumentImpl.writeDataFileInReplication(url.openStream(),
825
							datafilePath, docName, docType, docid, null, docHomeServer,
826
							server, DocumentImpl.DOCUMENTTABLE, false, createdDate,
827
							updatedDate);
828
				} catch (Exception e) {
829
					writeException = e;
830
				}
831
				
832
				// process the real owner and updater
833
				DBConnection dbConn = DBConnectionPool.getDBConnection("ReplicationService.handleForceDataFileRequest");
834
		        int serialNumber = dbConn.getCheckOutSerialNumber();
835
		        dbConn.setAutoCommit(false);
836
				String user = (String) docinfoHash.get("user_owner");
837
				String updated = (String) docinfoHash.get("user_updated");
838
		        updateUserOwner(dbConn, docid, user, updated);
839
		        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
840
		        
841
		        Vector<XMLAccessDAO> accessControlList = dih.getAccessControlList();
842
		        if (accessControlList != null) {
843
		        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
844
		        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
845
		        		if (!acfsf.accessControlExists(xmlAccessDAO)) {
846
		        			acfsf.insertPermissions(xmlAccessDAO);
847
							logReplication.info("ReplicationService.handleForceReplicateRequest - document " + docid
848
									+ " permissions added to DB");
849
		        		}
850
		            }
851
		        }
852
		        
853
		        // process system metadata
854
		        if (systemMetadataXML != null) {
855
		      	  SystemMetadata sysMeta = 
856
		      		  (SystemMetadata) ServiceTypeUtil.deserializeServiceType(
857
		      				  SystemMetadata.class, 
858
		      				  new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
859
		      	  String guid = sysMeta.getIdentifier().getValue();
860
		      	  if (!IdentifierManager.getInstance().identifierExists(guid)) {
861
		      		  logReplication.debug("Creating system metadata and guid/docid mapping for docid " + docinfoHash.get("docid") + " and guid: " + guid);
862
		      		  IdentifierManager.getInstance().createMapping(guid, docinfoHash.get("docid"));
863
		      		  IdentifierManager.getInstance().createSystemMetadata(sysMeta);
864
		      	  } else {
865
		      		  logReplication.debug("Updating guid/docid mapping for docid " + docinfoHash.get("docid") + " and guid: " + guid);
866
		      		  IdentifierManager.getInstance().updateMapping(guid, docinfoHash.get("docid"));
867
		      	  }
868
		      	  IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
869
		        }
870

    
871
				if (writeException != null) {
872
					throw writeException;
873
				}
874

    
875
				logReplication.info("ReplicationService.handleForceReplicateDataFileRequest - datafile " + docid + " added to DB with "
876
						+ "action " + dbaction);
877
				EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER,
878
						docid, dbaction);
879
			}
880

    
881
		} catch (Exception e) {
882
			logMetacat.error("ReplicationService.handleForceReplicateDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
883
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - Datafile " + docid
884
					+ " failed to added to DB with " + "action " + dbaction + " because "
885
					+ e.getMessage());
886
			logReplication.error("ReplicationService.handleForceReplicateDataFileRequest - ERROR in MetacatReplication.handleForceDataFileReplicate"
887
					+ "Request(): " + e.getMessage());
888
		}
889
	}
890

    
891
	/**
892
	 * Grants or denies a lock to a requesting host.
893
	 * The servlet parameters of interrest are:
894
	 * docid: the docid of the file the lock is being requested for
895
	 * currentdate: the timestamp of the document on the remote server
896
	 *
897
	 */
898
	protected static void handleGetLockRequest(
899
			Hashtable<String, String[]> params, HttpServletResponse response) {
900

    
901
		try {
902

    
903
			String docid = ((String[]) params.get("docid"))[0];
904
			String remoteRev = ((String[]) params.get("updaterev"))[0];
905
			DocumentImpl requestDoc = new DocumentImpl(docid);
906
			logReplication.info("ReplicationService.handleGetLockRequest - lock request for " + docid);
907
			int localRevInt = requestDoc.getRev();
908
			int remoteRevInt = Integer.parseInt(remoteRev);
909

    
910
			// get a writer for sending back to response
911
			response.setContentType("text/xml");
912
			Writer out = response.getWriter();
913
			
914
			if (remoteRevInt >= localRevInt) {
915
				if (!fileLocks.contains(docid)) { //grant the lock if it is not already locked
916
					fileLocks.add(0, docid); //insert at the beginning of the queue Vector
917
					//send a message back to the the remote host authorizing the insert
918
					out.write("<lockgranted><docid>" + docid
919
									+ "</docid></lockgranted>");
920
					//          lockThread = new Thread(this);
921
					//          lockThread.setPriority(Thread.MIN_PRIORITY);
922
					//          lockThread.start();
923
					logReplication.info("ReplicationService.handleGetLockRequest - lock granted for " + docid);
924
				} else { //deny the lock
925
					out.write("<filelocked><docid>" + docid + "</docid></filelocked>");
926
					logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
927
							+ "reason: file already locked");
928
				}
929
			} else {//deny the lock.
930
				out.write("<outdatedfile><docid>" + docid + "</docid></filelocked>");
931
				logReplication.info("ReplicationService.handleGetLockRequest - lock denied for " + docid
932
						+ "reason: client has outdated file");
933
			}
934
			out.close();
935
			//conn.close();
936
		} catch (Exception e) {
937
			logMetacat.error("ReplicationService.handleGetLockRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
938
			logReplication.error("ReplicationService.handleGetLockRequest - error requesting file lock from MetacatReplication."
939
					+ "handleGetLockRequest: " + e.getMessage());
940
			e.printStackTrace(System.out);
941
		}
942
	}
943

    
944
	/**
945
	 * Sends all of the xml_documents information encoded in xml to a requestor
946
	 * the format is:
947
	 * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
948
	 *                  user_updated, home_server, public_access, rev)/>
949
	 * all of the subelements of document info are #PCDATA
950
	 */
951
	protected static void handleGetDocumentInfoRequest(
952
			Hashtable<String, String[]> params, HttpServletResponse response) {
953
		String docid = ((String[]) (params.get("docid")))[0];
954
		StringBuffer sb = new StringBuffer();
955

    
956
		try {
957
			DocumentImpl doc = new DocumentImpl(docid);
958
			sb.append("<documentinfo><docid>").append(docid);
959
			sb.append("</docid>");
960
			
961
			try {
962
				// serialize the System Metadata as XML for docinfo
963
				String guid = IdentifierManager.getInstance().getGUID(doc.getDocID(), doc.getRev());
964
				SystemMetadata systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
965
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
966
				ServiceTypeUtil.serializeServiceType(SystemMetadata.class, systemMetadata, baos);
967
				String systemMetadataXML = baos.toString("UTF-8");
968
				sb.append("<systemMetadata>");
969
				sb.append(systemMetadataXML);
970
				sb.append("</systemMetadata>");
971
			} catch(McdbDocNotFoundException e) {
972
			  logMetacat.warn("No SystemMetadata found for: " + docid);
973
			}
974
			sb.append("<docname>").append(doc.getDocname());
975
			sb.append("</docname><doctype>").append(doc.getDoctype());
976
			sb.append("</doctype>");
977
			sb.append("<user_owner>").append(doc.getUserowner());
978
			sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
979
			sb.append("</user_updated>");
980
			sb.append("<date_created>");
981
			sb.append(doc.getCreateDate());
982
			sb.append("</date_created>");
983
			sb.append("<date_updated>");
984
			sb.append(doc.getUpdateDate());
985
			sb.append("</date_updated>");
986
			sb.append("<home_server>");
987
			sb.append(doc.getDocHomeServer());
988
			sb.append("</home_server>");
989
			sb.append("<public_access>").append(doc.getPublicaccess());
990
			sb.append("</public_access><rev>").append(doc.getRev());
991
			sb.append("</rev>");
992

    
993
			sb.append("<accessControl>");
994

    
995
			AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid); 
996
			sb.append(acfsf.getAccessString());
997
			
998
			sb.append("</accessControl>");
999

    
1000
			sb.append("</documentinfo>");
1001
			// get a writer for sending back to response
1002
			response.setContentType("text/xml");
1003
			Writer out = response.getWriter();
1004
			out.write(sb.toString());
1005
			out.close();
1006

    
1007
		} catch (Exception e) {
1008
			logMetacat.error("ReplicationService.handleGetDocumentInfoRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1009
			logReplication.error("ReplicationService.handleGetDocumentInfoRequest - error in metacatReplication.handlegetdocumentinforequest "
1010
					+ "for doc: " + docid + " : " + e.getMessage());
1011
		}
1012

    
1013
	}
1014
	
1015
	/**
1016
	 * Sends System Metadata as XML
1017
	 */
1018
	protected static void handleGetSystemMetadataRequest(
1019
			Hashtable<String, String[]> params, HttpServletResponse response) {
1020
		String guid = ((String[]) (params.get("guid")))[0];
1021
		String systemMetadataXML = null;
1022
		try {
1023
			
1024
			// serialize the System Metadata as XML 
1025
			SystemMetadata systemMetadata = IdentifierManager.getInstance().getSystemMetadata(guid);
1026
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
1027
			ServiceTypeUtil.serializeServiceType(SystemMetadata.class, systemMetadata, baos);
1028
			systemMetadataXML = baos.toString("UTF-8");
1029
				
1030
			// get a writer for sending back to response
1031
			response.setContentType("text/xml");
1032
			Writer out = response.getWriter();
1033
			out.write(systemMetadataXML);
1034
			out.close();
1035

    
1036
		} catch (Exception e) {
1037
			String msg = "ReplicationService.handleGetSystemMetadataRequest for guid: " + guid + " : " + e.getMessage();
1038
			logMetacat.error(msg);                         
1039
			logReplication.error(msg);
1040
		}
1041

    
1042
	}
1043
	
1044
	/**
1045
	 * when a forcereplication request comes in, local host sends a read request
1046
	 * to the requesting server (remote server) for the specified docid. Then
1047
	 * store it in local database.
1048
	 */
1049
	protected static void handleForceReplicateSystemMetadataRequest(
1050
			Hashtable<String, String[]> params, HttpServletResponse response,
1051
			HttpServletRequest request) {
1052
		String server = ((String[]) params.get("server"))[0]; // the server that
1053
		String guid = ((String[]) params.get("guid"))[0]; // sent the document
1054
		
1055
		try {
1056
			logReplication.info("ReplicationService.handleForceReplicateSystemMetadataRequest - Force replication system metadata request from: " + server);
1057
			// get the system metadata from server
1058
			URL docinfourl = new URL("https://" + server + "?server="
1059
					+ MetacatUtil.getLocalReplicationServerName()
1060
					+ "&action=getsystemmetadata&guid=" + guid);
1061
			
1062
			String systemMetadataXML = ReplicationService.getURLContent(docinfourl);
1063
						
1064
			// process system metadata
1065
			if (systemMetadataXML != null) {
1066
				SystemMetadata sysMeta = 
1067
					(SystemMetadata) ServiceTypeUtil.deserializeServiceType(
1068
							SystemMetadata.class,
1069
							new ByteArrayInputStream(systemMetadataXML.getBytes("UTF-8")));
1070
				if (!IdentifierManager.getInstance().identifierExists(guid)) {
1071
					logReplication.debug("Creating system metadata for guid: " + guid);
1072
					IdentifierManager.getInstance().createSystemMetadata(sysMeta);
1073
				}
1074
				IdentifierManager.getInstance().updateSystemMetadata(sysMeta);
1075
			}
1076
      
1077
			logReplication.info("ReplicationService.handleForceReplicateSystemMetadataRequest - processed guid: " + guid);
1078
			EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, guid, "systemMetadata");
1079

    
1080
		} catch (Exception e) {
1081
			logMetacat.error("ReplicationService.handleForceReplicateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG, e);                         
1082
			logReplication.error("ReplicationService.handleForceReplicateRequest - General error when processing guid: " + guid, e);
1083
		}
1084
	}
1085

    
1086
	/**
1087
	 * Sends a datafile to a remote host
1088
	 */
1089
	protected static void handleGetDataFileRequest(OutputStream outPut,
1090
			Hashtable<String, String[]> params, HttpServletResponse response)
1091

    
1092
	{
1093
		// File path for data file
1094
		String filepath;
1095
		// Request docid
1096
		String docId = ((String[]) (params.get("docid")))[0];
1097
		//check if the doicd is null
1098
		if (docId == null) {
1099
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1100
			logReplication.error("ReplicationService.handleGetDataFileRequest - Didn't specify docid for replication");
1101
			return;
1102
		}
1103

    
1104
		//try to open a https stream to test if the request server's public key
1105
		//in the key store, this is security issue
1106
		try {
1107
			filepath = PropertyService.getProperty("application.datafilepath");
1108
			String server = params.get("server")[0];
1109
			URL u = new URL("https://" + server + "?server="
1110
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test");
1111
			String test = ReplicationService.getURLContent(u);
1112
			//couldn't pass the test
1113
			if (test.indexOf("successfully") == -1) {
1114
				//response.setContentType("text/xml");
1115
				//outPut.println("<error>Couldn't pass the trust test</error>");
1116
				logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1117
				logReplication.error("ReplicationService.handleGetDataFileRequest - Couldn't pass the trust test");
1118
				return;
1119
			}
1120
		}//try
1121
		catch (Exception ee) {
1122
			return;
1123
		}//catch
1124

    
1125
		if (!filepath.endsWith("/")) {
1126
			filepath += "/";
1127
		}
1128
		// Get file aboslute file name
1129
		String filename = filepath + docId;
1130

    
1131
		//MIME type
1132
		String contentType = null;
1133
		if (filename.endsWith(".xml")) {
1134
			contentType = "text/xml";
1135
		} else if (filename.endsWith(".css")) {
1136
			contentType = "text/css";
1137
		} else if (filename.endsWith(".dtd")) {
1138
			contentType = "text/plain";
1139
		} else if (filename.endsWith(".xsd")) {
1140
			contentType = "text/xml";
1141
		} else if (filename.endsWith("/")) {
1142
			contentType = "text/html";
1143
		} else {
1144
			File f = new File(filename);
1145
			if (f.isDirectory()) {
1146
				contentType = "text/html";
1147
			} else {
1148
				contentType = "application/octet-stream";
1149
			}
1150
		}
1151

    
1152
		// Set the mime type
1153
		response.setContentType(contentType);
1154

    
1155
		// Get the content of the file
1156
		FileInputStream fin = null;
1157
		try {
1158
			// FileInputStream to metacat
1159
			fin = new FileInputStream(filename);
1160
			// 4K buffer
1161
			byte[] buf = new byte[4 * 1024];
1162
			// Read data from file input stream to byte array
1163
			int b = fin.read(buf);
1164
			// Write to outStream from byte array
1165
			while (b != -1) {
1166
				outPut.write(buf, 0, b);
1167
				b = fin.read(buf);
1168
			}
1169
			// close file input stream
1170
			fin.close();
1171

    
1172
		}//try
1173
		catch (Exception e) {
1174
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1175
			logReplication.error("ReplicationService.handleGetDataFileRequest - error getting data file from MetacatReplication."
1176
					+ "handlGetDataFileRequest " + e.getMessage());
1177
			e.printStackTrace(System.out);
1178
		}//catch
1179

    
1180
	}
1181

    
1182
	/**
1183
	 * Sends a document to a remote host
1184
	 */
1185
	protected static void handleGetDocumentRequest(
1186
			Hashtable<String, String[]> params, HttpServletResponse response) {
1187

    
1188
		String urlString = null;
1189
		String documentPath = null;
1190
		String errorMsg = null;
1191
		try {
1192
			// try to open a https stream to test if the request server's public
1193
			// key
1194
			// in the key store, this is security issue
1195
			String server = params.get("server")[0];
1196
			urlString = "https://" + server + "?server="
1197
					+ MetacatUtil.getLocalReplicationServerName() + "&action=test";
1198
			URL u = new URL(urlString);
1199
			String test = ReplicationService.getURLContent(u);
1200
			// couldn't pass the test
1201
			if (test.indexOf("successfully") == -1) {
1202
				response.setContentType("text/xml");
1203
				Writer out = response.getWriter();
1204
				out.write("<error>Couldn't pass the trust test " + test + " </error>");
1205
				out.close();
1206
				return;
1207
			}
1208

    
1209
			String docid = params.get("docid")[0];
1210
			logReplication.debug("ReplicationService.handleGetDocumentRequest - MetacatReplication.handleGetDocumentRequest for docid: "
1211
					+ docid);
1212
			DocumentImpl di = new DocumentImpl(docid);
1213

    
1214
			String documentDir = PropertyService
1215
					.getProperty("application.documentfilepath");
1216
			documentPath = documentDir + FileUtil.getFS() + docid;
1217

    
1218
			// if the document does not exist on disk, read it from db and write
1219
			// it to disk.
1220
			if (FileUtil.getFileStatus(documentPath) == FileUtil.DOES_NOT_EXIST
1221
					|| FileUtil.getFileSize(documentPath) == 0) {
1222
				FileOutputStream fos = new FileOutputStream(documentPath);
1223
				di.toXml(fos, null, null, true);
1224
			}
1225

    
1226
			// read the file from disk and send it to outputstream
1227
			OutputStream outputStream = response.getOutputStream();
1228
			di.readFromFileSystem(outputStream, null, null, documentPath);
1229

    
1230
			logReplication.info("ReplicationService.handleGetDocumentRequest - document " + docid + " sent");
1231

    
1232
			// return to avoid continuing to the error reporting section at the end
1233
			return;
1234
			
1235
		} catch (MalformedURLException mue) {
1236
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1237
			logReplication.error("ReplicationService.handleGetDocumentRequest - Url error when getting document from MetacatReplication."
1238
					+ "handlGetDocumentRequest for url: " + urlString + " : "
1239
					+ mue.getMessage());
1240
			// e.printStackTrace(System.out);
1241
			
1242
		} catch (IOException ioe) {
1243
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1244
			logReplication.error("ReplicationService.handleGetDocumentRequest - I/O error when getting document from MetacatReplication."
1245
					+ "handlGetDocumentRequest for file: " + documentPath + " : "
1246
					+ ioe.getMessage());
1247
			errorMsg = ioe.getMessage();
1248
		} catch (PropertyNotFoundException pnfe) {
1249
			logMetacat.error("ReplicationService.handleGetDocumentRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1250
			logReplication
1251
					.error("ReplicationService.handleGetDocumentRequest - Error getting property when getting document from MetacatReplication."
1252
							+ "handlGetDocumentRequest for file: "
1253
							+ documentPath
1254
							+ " : "
1255
							+ pnfe.getMessage());
1256
			// e.printStackTrace(System.out);
1257
			errorMsg = pnfe.getMessage();
1258
		} catch (McdbException me) {
1259
			logReplication
1260
					.error("ReplicationService.handleGetDocumentRequest - Document implementation error  getting property when getting document from MetacatReplication."
1261
							+ "handlGetDocumentRequest for file: "
1262
							+ documentPath
1263
							+ " : "
1264
							+ me.getMessage());
1265
			// e.printStackTrace(System.out);
1266
			errorMsg = me.getMessage();
1267
		}
1268
		
1269
		// report any errors if we got here
1270
		response.setContentType("text/xml");
1271
		Writer out = null;
1272
		try {
1273
			response.getWriter();
1274
			out = response.getWriter();
1275
			out.write("<error>" + errorMsg + "</error>");
1276
		} catch (Exception e) {
1277
			logMetacat.error(e.getMessage(), e);
1278
		} finally {
1279
			try {
1280
				out.close();
1281
			} catch (IOException e) {
1282
				logMetacat.error(e.getMessage(), e);
1283
			}
1284
		}
1285
		
1286

    
1287
	}
1288

    
1289
	/**
1290
	 * Sends a list of all of the documents on this sever along with their
1291
	 * revision numbers. The format is: <!ELEMENT replication (server, updates)>
1292
	 * <!ELEMENT server (#PCDATA)> <!ELEMENT updates ((updatedDocument |
1293
	 * deleteDocument | revisionDocument)*)> <!ELEMENT updatedDocument (docid,
1294
	 * rev, datafile*)> <!ELEMENT deletedDocument (docid, rev)> <!ELEMENT
1295
	 * revisionDocument (docid, rev, datafile*)> <!ELEMENT docid (#PCDATA)>
1296
	 * <!ELEMENT rev (#PCDATA)> <!ELEMENT datafile (#PCDATA)> note that the rev
1297
	 * in deletedDocument is always empty. I just left it in there to make the
1298
	 * parser implementation easier.
1299
	 */
1300
	protected static void handleUpdateRequest(Hashtable<String, String[]> params,
1301
			HttpServletResponse response) {
1302
		// Checked out DBConnection
1303
		DBConnection dbConn = null;
1304
		// DBConenction serial number when checked it out
1305
		int serialNumber = -1;
1306
		PreparedStatement pstmt = null;
1307
		// Server list to store server info of xml_replication table
1308
		ReplicationServerList serverList = null;
1309
		
1310
		// a writer for response
1311
		Writer out = null;
1312

    
1313
		try {
1314
			// get writer, TODO: encoding?
1315
			response.setContentType("text/xml");
1316
			out = response.getWriter();
1317
			
1318
			// Check out a DBConnection from pool
1319
			dbConn = DBConnectionPool
1320
					.getDBConnection("MetacatReplication.handleUpdateRequest");
1321
			serialNumber = dbConn.getCheckOutSerialNumber();
1322
			// Create a server list from xml_replication table
1323
			serverList = new ReplicationServerList();
1324

    
1325
			// Get remote server name from param
1326
			String server = ((String[]) params.get("server"))[0];
1327
			// If no servr name in param, return a error
1328
			if (server == null || server.equals("")) {
1329
				out.write("<error>Request didn't specify server name</error>");
1330
				out.close();
1331
				return;
1332
			}//if
1333

    
1334
			//try to open a https stream to test if the request server's public key
1335
			//in the key store, this is security issue
1336
			String testUrl = "https://" + server + "?server="
1337
            + MetacatUtil.getLocalReplicationServerName() + "&action=test";
1338
			logReplication.info("Running trust test: " + testUrl);
1339
			URL u = new URL(testUrl);
1340
			String test = ReplicationService.getURLContent(u);
1341
			logReplication.info("Ouput from test is '" + test + "'");
1342
			//couldn't pass the test
1343
			if (test.indexOf("successfully") == -1) {
1344
			    logReplication.error("Trust test failed.");
1345
				out.write("<error>Couldn't pass the trust test</error>");
1346
				out.close();
1347
				return;
1348
			}
1349
			logReplication.info("Trust test succeeded.");
1350

    
1351
			// Check if local host configure to replicate xml documents to remote
1352
			// server. If not send back a error message
1353
			if (!serverList.getReplicationValue(server)) {
1354
				out.write("<error>Configuration not allow to replicate document to you</error>");
1355
				out.close();
1356
				return;
1357
			}//if
1358

    
1359
			// Store the sql command
1360
			StringBuffer docsql = new StringBuffer();
1361
			StringBuffer revisionSql = new StringBuffer();
1362
			// Stroe the docid list
1363
			StringBuffer doclist = new StringBuffer();
1364
			// Store the deleted docid list
1365
			StringBuffer delsql = new StringBuffer();
1366
			// Store the data set file
1367
			Vector<Vector<String>> packageFiles = new Vector<Vector<String>>();
1368

    
1369
			// Append local server's name and replication servlet to doclist
1370
			doclist.append("<?xml version=\"1.0\"?><replication>");
1371
			doclist.append("<server>")
1372
					.append(MetacatUtil.getLocalReplicationServerName());
1373
			//doclist.append(util.getProperty("replicationpath"));
1374
			doclist.append("</server><updates>");
1375

    
1376
			// Get correct docid that reside on this server according the requesting
1377
			// server's replicate and data replicate value in xml_replication table
1378
			docsql.append(DatabaseService.getInstance().getDBAdapter().getReplicationDocumentListSQL());
1379
			//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)) ");
1380
			revisionSql.append("select docid, rev, doctype from xml_revisions ");
1381
			// If the localhost is not a hub to the remote server, only replicate
1382
			// the docid' which home server is local host (server_location =1)
1383
			if (!serverList.getHubValue(server)) {
1384
				String serverLocationDoc = " and a.server_location = 1";
1385
				String serverLocationRev = "where server_location = 1";
1386
				docsql.append(serverLocationDoc);
1387
				revisionSql.append(serverLocationRev);
1388
			}
1389
			logReplication.info("ReplicationService.handleUpdateRequest - Doc sql: " + docsql.toString());
1390

    
1391
			// Get any deleted documents
1392
			delsql.append("select distinct docid from ");
1393
			delsql.append("xml_revisions where docid not in (select docid from ");
1394
			delsql.append("xml_documents) ");
1395
			// If the localhost is not a hub to the remote server, only replicate
1396
			// the docid' which home server is local host (server_location =1)
1397
			if (!serverList.getHubValue(server)) {
1398
				delsql.append("and server_location = 1");
1399
			}
1400
			logReplication.info("ReplicationService.handleUpdateRequest - Deleted sql: " + delsql.toString());
1401

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

    
1480
			pstmt = dbConn.prepareStatement(delsql.toString());
1481
			//usage count should increas 1
1482
			dbConn.increaseUsageCount(1);
1483

    
1484
			pstmt.execute();
1485
			rs = pstmt.getResultSet();
1486
			tablehasrows = rs.next();
1487
			while (tablehasrows) { //handle the deleted documents
1488
				doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1489
				doclist.append("</docid><rev></rev></deletedDocument>");
1490
				//note that rev is always empty for deleted docs
1491
				tablehasrows = rs.next();
1492
			}
1493

    
1494
			//now we can put the package files into the xml results
1495
			for (int i = 0; i < packageFiles.size(); i++) {
1496
				Vector<String> v = packageFiles.elementAt(i);
1497
				doclist.append("<updatedDocument>");
1498
				doclist.append("<docid>").append(v.elementAt(0));
1499
				doclist.append("</docid><rev>");
1500
				doclist.append(v.elementAt(1));
1501
				doclist.append("</rev>");
1502
				doclist.append("</updatedDocument>");
1503
			}
1504
			// add revision doc list  
1505
			doclist.append(prepareRevisionDoc(dbConn, revisionSql.toString(),
1506
					replicateData));
1507
			
1508
			// add the system metadata entries		 
1509
			Date since = new Date(System.currentTimeMillis());
1510
			since = serverList.getLastCheckedDate(server);
1511
			List<String> systemMetadataEntries = 
1512
				IdentifierManager.getInstance().getUpdatedSystemMetadataIds(since);
1513
			for (int i = 0; i < systemMetadataEntries.size(); i++) {
1514
				String guid = systemMetadataEntries.get(i);
1515
				doclist.append("<updatedSystemMetadata>");
1516
				doclist.append("<guid>");
1517
				doclist.append(guid);
1518
				doclist.append("</guid>");
1519
				doclist.append("</updatedSystemMetadata>");
1520
			}
1521

    
1522
			doclist.append("</updates></replication>");
1523
			logReplication.info("ReplicationService.handleUpdateRequest - doclist: " + doclist.toString());
1524
			pstmt.close();
1525
			//conn.close();
1526
			out.write(doclist.toString());
1527

    
1528
		} catch (Exception e) {
1529
			logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1530
			logReplication.error("ReplicationService.handleUpdateRequest - error in MetacatReplication." + "handleupdaterequest: "
1531
					+ e.getMessage());
1532
			//e.printStackTrace(System.out);
1533
			try {
1534
				out.write("<error>" + e.getMessage() + "</error>");
1535
			} catch (IOException e1) {
1536
				logMetacat.error(e1.getMessage(), e1);
1537
			}
1538
		} finally {
1539
			try {
1540
				pstmt.close();
1541
			}//try
1542
			catch (SQLException ee) {
1543
				logMetacat.error("ReplicationService.handleUpdateRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1544
				logReplication.error("ReplicationService.handleUpdateRequest - Error in MetacatReplication."
1545
						+ "handleUpdaterequest to close pstmt: " + ee.getMessage());
1546
			}//catch
1547
			finally {
1548
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1549
			}//finally
1550
			try {
1551
				out.close();
1552
			} catch (IOException e) {
1553
				logMetacat.error(e.getMessage(), e);
1554
			}
1555
		}//finally
1556

    
1557
	}//handlUpdateRequest
1558

    
1559
	/**
1560
	 * 
1561
	 * @param dbConn connection for doing the update
1562
	 * @param docid the document id to update
1563
	 * @param owner the user_owner
1564
	 * @param updater the user_updated
1565
	 * @throws SQLException
1566
	 */
1567
	public static void updateUserOwner(DBConnection dbConn, String docid, String owner, String updater) throws SQLException {
1568
	
1569
		String sql = 
1570
			"UPDATE xml_documents " +
1571
			"SET user_owner = ?, " +
1572
			"user_updated = ? " +
1573
			"WHERE docid = ?;";
1574
		PreparedStatement pstmt = dbConn.prepareStatement(sql);
1575
		//usage count should increas 1
1576
		dbConn.increaseUsageCount(1);
1577

    
1578
		docid = DocumentUtil.getSmartDocId(docid);
1579
		pstmt.setString(1, owner);
1580
		pstmt.setString(2, updater);
1581
		pstmt.setString(3, docid);
1582
		pstmt.execute();
1583
		pstmt.close();
1584
		
1585
		dbConn.commit();
1586
	}
1587
	
1588
	/*
1589
	 * This method will get the xml string for document in xml_revision
1590
	 * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1591
	 */
1592
	private static String prepareRevisionDoc(DBConnection dbConn, String revSql,
1593
			boolean replicateData) throws Exception {
1594
		logReplication.warn("ReplicationService.prepareRevisionDoc - The revision document sql is " + revSql);
1595
		StringBuffer revDocList = new StringBuffer();
1596
		PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1597
		//usage count should increas 1
1598
		dbConn.increaseUsageCount(1);
1599

    
1600
		pstmt.execute();
1601
		ResultSet rs = pstmt.getResultSet();
1602
		boolean tablehasrows = rs.next();
1603
		while (tablehasrows) {
1604
			String recordDoctype = rs.getString(3);
1605

    
1606
			//If this is data file and it isn't configured to replicate data
1607
			if (recordDoctype.equals("BIN") && !replicateData) {
1608
				// do nothing
1609
				continue;
1610
			} else {
1611

    
1612
				revDocList.append("<revisionDocument>");
1613
				revDocList.append("<docid>").append(rs.getString(1));
1614
				revDocList.append("</docid><rev>").append(rs.getInt(2));
1615
				revDocList.append("</rev>");
1616
				// data file
1617
				if (recordDoctype.equals("BIN")) {
1618
					revDocList.append("<datafile>");
1619
					revDocList.append(PropertyService
1620
							.getProperty("replication.datafileflag"));
1621
					revDocList.append("</datafile>");
1622
				}
1623
				revDocList.append("</revisionDocument>");
1624

    
1625
			}//else
1626
			tablehasrows = rs.next();
1627
		}
1628
		//System.out.println("The revision list is"+ revDocList.toString());
1629
		return revDocList.toString();
1630
	}
1631

    
1632
	/**
1633
	 * Returns the xml_catalog table encoded in xml
1634
	 */
1635
	public static String getCatalogXML() {
1636
		return handleGetCatalogRequest(null, null, false);
1637
	}
1638

    
1639
	/**
1640
	 * Sends the contents of the xml_catalog table encoded in xml
1641
	 * The xml format is:
1642
	 * <!ELEMENT xml_catalog (row*)>
1643
	 * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1644
	 *                system_id)>
1645
	 * All of the sub elements of row are #PCDATA
1646

    
1647
	 * If printFlag == false then do not print to out.
1648
	 */
1649
	protected static String handleGetCatalogRequest(
1650
			Hashtable<String, String[]> params, HttpServletResponse response,
1651
			boolean printFlag) {
1652
		DBConnection dbConn = null;
1653
		int serialNumber = -1;
1654
		PreparedStatement pstmt = null;
1655
		Writer out = null;
1656
		try {
1657
			// get writer, TODO: encoding?
1658
		    if(printFlag)
1659
		    {
1660
		        response.setContentType("text/xml");
1661
		        out = response.getWriter();
1662
		    }
1663
			/*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1664
			                                          "handleGetCatalogRequest");*/
1665
			dbConn = DBConnectionPool
1666
					.getDBConnection("MetacatReplication.handleGetCatalogRequest");
1667
			serialNumber = dbConn.getCheckOutSerialNumber();
1668
			pstmt = dbConn.prepareStatement("select entry_type, "
1669
					+ "source_doctype, target_doctype, public_id, "
1670
					+ "system_id from xml_catalog");
1671
			pstmt.execute();
1672
			ResultSet rs = pstmt.getResultSet();
1673
			boolean tablehasrows = rs.next();
1674
			StringBuffer sb = new StringBuffer();
1675
			sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1676
			while (tablehasrows) {
1677
				sb.append("<row><entry_type>").append(rs.getString(1));
1678
				sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1679
				sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1680
				sb.append("</target_doctype><public_id>").append(rs.getString(4));
1681
				// system id may not have server url on front.  Add it if not.
1682
				String systemID = rs.getString(5);
1683
				if (!systemID.startsWith("http://")) {
1684
					systemID = SystemUtil.getContextURL() + systemID;
1685
				}
1686
				sb.append("</public_id><system_id>").append(systemID);
1687
				sb.append("</system_id></row>");
1688

    
1689
				tablehasrows = rs.next();
1690
			}
1691
			sb.append("</xml_catalog>");
1692
			//conn.close();
1693
			if (printFlag) {
1694
				response.setContentType("text/xml");
1695
				out.write(sb.toString());
1696
			}
1697
			pstmt.close();
1698
			return sb.toString();
1699
		} catch (Exception e) {
1700
			logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1701
			logReplication.error("ReplicationService.handleGetCatalogRequest - error in MetacatReplication.handleGetCatalogRequest:"
1702
					+ e.getMessage());
1703
			e.printStackTrace(System.out);
1704
			if (printFlag) {
1705
				try {
1706
					out.write("<error>" + e.getMessage() + "</error>");
1707
				} catch (IOException e1) {
1708
					logMetacat.error(e1.getMessage(), e1);
1709
				}
1710
			}
1711
		} finally {
1712
			try {
1713
				pstmt.close();
1714
			}//try
1715
			catch (SQLException ee) {
1716
				logMetacat.error("ReplicationService.handleGetCatalogRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1717
				logReplication.error("ReplicationService.handleGetCatalogRequest - Error in MetacatReplication.handleGetCatalogRequest: "
1718
						+ ee.getMessage());
1719
			}//catch
1720
			finally {
1721
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1722
			}//finally
1723
			if (out != null) {
1724
				try {
1725
					out.close();
1726
				} catch (IOException e1) {
1727
					logMetacat.error(e1.getMessage(), e1);
1728
				}
1729
			}
1730
		}//finally
1731

    
1732
		return null;
1733
	}
1734

    
1735
	/**
1736
	 * Sends the current system date to the remote server.  Using this action
1737
	 * for replication gets rid of any problems with syncronizing clocks
1738
	 * because a time specific to a document is always kept on its home server.
1739
	 */
1740
	protected static void handleGetTimeRequest(
1741
			Hashtable<String, String[]> params, HttpServletResponse response) {
1742
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
1743
		java.util.Date localtime = new java.util.Date();
1744
		String dateString = formatter.format(localtime);
1745
		
1746
		// get a writer for sending back to response
1747
		response.setContentType("text/xml");
1748
		Writer out = null;
1749
		try {
1750
			out = response.getWriter();
1751
			out.write("<timestamp>" + dateString + "</timestamp>");
1752
			out.close();
1753
		} catch (IOException e) {
1754
			logMetacat.error(e.getMessage(), e);
1755
		}
1756
		
1757
	}
1758

    
1759
	/**
1760
	 * this method handles the timeout for a file lock.  when a lock is
1761
	 * granted it is granted for 30 seconds.  When this thread runs out
1762
	 * it deletes the docid from the queue, thus eliminating the lock.
1763
	 */
1764
	public void run() {
1765
		try {
1766
			logReplication.info("ReplicationService.run - thread started for docid: "
1767
					+ (String) fileLocks.elementAt(0));
1768

    
1769
			Thread.sleep(30000); //the lock will expire in 30 seconds
1770
			logReplication.info("thread for docid: "
1771
					+ (String) fileLocks.elementAt(fileLocks.size() - 1) + " exiting.");
1772

    
1773
			fileLocks.remove(fileLocks.size() - 1);
1774
			//fileLocks is treated as a FIFO queue.  If there are more than one lock
1775
			//in the vector, the first one inserted will be removed.
1776
		} catch (Exception e) {
1777
			logMetacat.error("ReplicationService.run - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1778
			logReplication.error("ReplicationService.run - error in file lock thread from "
1779
					+ "MetacatReplication.run: " + e.getMessage());
1780
		}
1781
	}
1782

    
1783
	/**
1784
	 * Returns the name of a server given a serverCode
1785
	 * @param serverCode the serverid of the server
1786
	 * @return the servername or null if the specified serverCode does not
1787
	 *         exist.
1788
	 */
1789
	public static String getServerNameForServerCode(int serverCode) {
1790
		//System.out.println("serverid: " + serverCode);
1791
		DBConnection dbConn = null;
1792
		int serialNumber = -1;
1793
		PreparedStatement pstmt = null;
1794
		try {
1795
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServer");
1796
			serialNumber = dbConn.getCheckOutSerialNumber();
1797
			String sql = new String("select server from "
1798
					+ "xml_replication where serverid = " + serverCode);
1799
			pstmt = dbConn.prepareStatement(sql);
1800
			//System.out.println("getserver sql: " + sql);
1801
			pstmt.execute();
1802
			ResultSet rs = pstmt.getResultSet();
1803
			boolean tablehasrows = rs.next();
1804
			if (tablehasrows) {
1805
				//System.out.println("server: " + rs.getString(1));
1806
				return rs.getString(1);
1807
			}
1808

    
1809
			//conn.close();
1810
		} catch (Exception e) {
1811
			logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1812
			logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplication.getServer: " + e.getMessage());
1813
		} finally {
1814
			try {
1815
				pstmt.close();
1816
			}//try
1817
			catch (SQLException ee) {
1818
				logMetacat.error("ReplicationService.getServerNameForServerCode - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1819
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacactReplication.getserver: "
1820
						+ ee.getMessage());
1821
			}//catch
1822
			finally {
1823
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1824
			}//fianlly
1825
		}//finally
1826

    
1827
		return null;
1828
		//return null if the server does not exist
1829
	}
1830

    
1831
	/**
1832
	 * Returns a server code given a server name
1833
	 * @param server the name of the server
1834
	 * @return integer > 0 representing the code of the server, 0 if the server
1835
	 *  does not exist.
1836
	 */
1837
	public static int getServerCodeForServerName(String server) throws ServiceException {
1838
		DBConnection dbConn = null;
1839
		int serialNumber = -1;
1840
		PreparedStatement pstmt = null;
1841
		int serverCode = 0;
1842

    
1843
		try {
1844

    
1845
			//conn = util.openDBConnection();
1846
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.getServerCode");
1847
			serialNumber = dbConn.getCheckOutSerialNumber();
1848
			pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication "
1849
					+ "WHERE server LIKE '" + server + "'");
1850
			pstmt.execute();
1851
			ResultSet rs = pstmt.getResultSet();
1852
			boolean tablehasrows = rs.next();
1853
			if (tablehasrows) {
1854
				serverCode = rs.getInt(1);
1855
				pstmt.close();
1856
				//conn.close();
1857
				return serverCode;
1858
			}
1859

    
1860
		} catch (SQLException sqle) {
1861
			throw new ServiceException("ReplicationService.getServerCodeForServerName - " 
1862
					+ "SQL error when getting server code: " + sqle.getMessage());
1863

    
1864
		} finally {
1865
			try {
1866
				pstmt.close();
1867
				//conn.close();
1868
			}//try
1869
			catch (Exception ee) {
1870
				logMetacat.error("ReplicationService.getServerCodeForServerName - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1871
				logReplication.error("ReplicationService.getServerNameForServerCode - Error in MetacatReplicatio.getServerCode: "
1872
						+ ee.getMessage());
1873

    
1874
			}//catch
1875
			finally {
1876
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1877
			}//finally
1878
		}//finally
1879

    
1880
		return serverCode;
1881
	}
1882

    
1883
	/**
1884
	 * Method to get a host server information for given docid
1885
	 * @param conn a connection to the database
1886
	 */
1887
	public static Hashtable<String, String> getHomeServerInfoForDocId(String docId) {
1888
		Hashtable<String, String> sl = new Hashtable<String, String>();
1889
		DBConnection dbConn = null;
1890
		int serialNumber = -1;
1891
		docId = DocumentUtil.getDocIdFromString(docId);
1892
		PreparedStatement pstmt = null;
1893
		int serverLocation;
1894
		try {
1895
			//get conection
1896
			dbConn = DBConnectionPool.getDBConnection("ReplicationHandler.getHomeServer");
1897
			serialNumber = dbConn.getCheckOutSerialNumber();
1898
			//get a server location from xml_document table
1899
			pstmt = dbConn.prepareStatement("select server_location from xml_documents "
1900
					+ "where docid = ?");
1901
			pstmt.setString(1, docId);
1902
			pstmt.execute();
1903
			ResultSet serverName = pstmt.getResultSet();
1904
			//get a server location
1905
			if (serverName.next()) {
1906
				serverLocation = serverName.getInt(1);
1907
				pstmt.close();
1908
			} else {
1909
				pstmt.close();
1910
				//ut.returnConnection(conn);
1911
				return null;
1912
			}
1913
			pstmt = dbConn.prepareStatement("select server, last_checked, replicate "
1914
					+ "from xml_replication where serverid = ?");
1915
			//increase usage count
1916
			dbConn.increaseUsageCount(1);
1917
			pstmt.setInt(1, serverLocation);
1918
			pstmt.execute();
1919
			ResultSet rs = pstmt.getResultSet();
1920
			boolean tableHasRows = rs.next();
1921
			if (tableHasRows) {
1922

    
1923
				String server = rs.getString(1);
1924
				String last_checked = rs.getString(2);
1925
				if (!server.equals("localhost")) {
1926
					sl.put(server, last_checked);
1927
				}
1928

    
1929
			} else {
1930
				pstmt.close();
1931
				//ut.returnConnection(conn);
1932
				return null;
1933
			}
1934
			pstmt.close();
1935
		} catch (Exception e) {
1936
			logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1937
			logReplication.error("ReplicationService.getHomeServerInfoForDocId - error in replicationHandler.getHomeServer(): "
1938
					+ e.getMessage());
1939
		} finally {
1940
			try {
1941
				pstmt.close();
1942
				//ut.returnConnection(conn);
1943
			} catch (Exception ee) {
1944
				logMetacat.error("ReplicationService.getHomeServerInfoForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1945
				logReplication.error("ReplicationService.getHomeServerInfoForDocId - Eror irn rplicationHandler.getHomeServer() "
1946
						+ "to close pstmt: " + ee.getMessage());
1947
			} finally {
1948
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1949
			}
1950

    
1951
		}//finally
1952
		return sl;
1953
	}
1954

    
1955
	/**
1956
	 * Returns a home server location  given a accnum
1957
	 * @param accNum , given accNum for a document
1958
	 *
1959
	 */
1960
	public static int getHomeServerCodeForDocId(String accNum) throws ServiceException {
1961
		DBConnection dbConn = null;
1962
		int serialNumber = -1;
1963
		PreparedStatement pstmt = null;
1964
		int serverCode = 1;
1965
		String docId = DocumentUtil.getDocIdFromString(accNum);
1966

    
1967
		try {
1968

    
1969
			// Get DBConnection
1970
			dbConn = DBConnectionPool
1971
					.getDBConnection("ReplicationHandler.getServerLocation");
1972
			serialNumber = dbConn.getCheckOutSerialNumber();
1973
			pstmt = dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1974
					+ "WHERE docid LIKE '" + docId + "'");
1975
			pstmt.execute();
1976
			ResultSet rs = pstmt.getResultSet();
1977
			boolean tablehasrows = rs.next();
1978
			//If a document is find, return the server location for it
1979
			if (tablehasrows) {
1980
				serverCode = rs.getInt(1);
1981
				pstmt.close();
1982
				//conn.close();
1983
				return serverCode;
1984
			}
1985
			//if couldn't find in xml_documents table, we think server code is 1
1986
			//(this is new document)
1987
			else {
1988
				pstmt.close();
1989
				//conn.close();
1990
				return serverCode;
1991
			}
1992

    
1993
		} catch (SQLException sqle) {
1994
			throw new ServiceException("ReplicationService.getHomeServerCodeForDocId - " 
1995
					+ "SQL error when getting home server code for docid: " + docId + " : " 
1996
					+ sqle.getMessage());
1997

    
1998
		} finally {
1999
			try {
2000
				pstmt.close();
2001
				//conn.close();
2002

    
2003
			} catch (SQLException sqle) {
2004
				logMetacat.error("ReplicationService.getHomeServerCodeForDocId - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2005
				logReplication.error("ReplicationService.getHomeServerCodeForDocId - ReplicationService.getHomeServerCodeForDocId - " 
2006
						+ "SQL error when getting home server code for docid: " + docId + " : " 
2007
						+ sqle.getMessage());
2008
			} finally {
2009
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2010
			}//finally
2011
		}//finally
2012
		//return serverCode;
2013
	}
2014

    
2015
	/**
2016
	 * This method returns the content of a url
2017
	 * @param u the url to return the content from
2018
	 * @return a string representing the content of the url
2019
	 * @throws java.io.IOException
2020
	 */
2021
	public static String getURLContent(URL u) throws java.io.IOException {
2022
	    logReplication.info("Getting url content from " + u.toString());
2023
		char istreamChar;
2024
		int istreamInt;
2025
		logReplication.info("ReplicationService.getURLContent - Before open the stream" + u.toString());
2026
		InputStream input = u.openStream();
2027
		logReplication.info("ReplicationService.getURLContent - After open the stream" + u.toString());
2028
		InputStreamReader istream = new InputStreamReader(input);
2029
		StringBuffer serverResponse = new StringBuffer();
2030
		while ((istreamInt = istream.read()) != -1) {
2031
			istreamChar = (char) istreamInt;
2032
			serverResponse.append(istreamChar);
2033
		}
2034
		istream.close();
2035
		input.close();
2036

    
2037
		return serverResponse.toString();
2038
	}
2039

    
2040
//	/**
2041
//	 * Method for writing replication messages to a log file specified in
2042
//	 * metacat.properties
2043
//	 */
2044
//	public static void replLog(String message) {
2045
//		try {
2046
//			FileOutputStream fos = new FileOutputStream(PropertyService
2047
//					.getProperty("replication.logdir")
2048
//					+ "/metacatreplication.log", true);
2049
//			PrintWriter pw = new PrintWriter(fos);
2050
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
2051
//			java.util.Date localtime = new java.util.Date();
2052
//			String dateString = formatter.format(localtime);
2053
//			dateString += " :: " + message;
2054
//			// time stamp each entry
2055
//			pw.println(dateString);
2056
//			pw.flush();
2057
//		} catch (Exception e) {
2058
//			logReplication.error("error writing to replication log from "
2059
//					+ "MetacatReplication.replLog: " + e.getMessage());
2060
//			// e.printStackTrace(System.out);
2061
//		}
2062
//	}
2063

    
2064
//	/**
2065
//	 * Method for writing replication messages to a log file specified in
2066
//	 * metacat.properties
2067
//	 */
2068
//	public static void replErrorLog(String message) {
2069
//		try {
2070
//			FileOutputStream fos = new FileOutputStream(PropertyService
2071
//					.getProperty("replication.logdir")
2072
//					+ "/metacatreplicationerror.log", true);
2073
//			PrintWriter pw = new PrintWriter(fos);
2074
//			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
2075
//			java.util.Date localtime = new java.util.Date();
2076
//			String dateString = formatter.format(localtime);
2077
//			dateString += " :: " + message;
2078
//			//time stamp each entry
2079
//			pw.println(dateString);
2080
//			pw.flush();
2081
//		} catch (Exception e) {
2082
//			logReplication.error("error writing to replication error log from "
2083
//					+ "MetacatReplication.replErrorLog: " + e.getMessage());
2084
//			//e.printStackTrace(System.out);
2085
//		}
2086
//	}
2087

    
2088
	/**
2089
	 * Returns true if the replicate field for server in xml_replication is 1.
2090
	 * Returns false otherwise
2091
	 */
2092
	public static boolean replToServer(String server) {
2093
		DBConnection dbConn = null;
2094
		int serialNumber = -1;
2095
		PreparedStatement pstmt = null;
2096
		try {
2097
			dbConn = DBConnectionPool.getDBConnection("MetacatReplication.repltoServer");
2098
			serialNumber = dbConn.getCheckOutSerialNumber();
2099
			pstmt = dbConn.prepareStatement("select replicate from "
2100
					+ "xml_replication where server like '" + server + "'");
2101
			pstmt.execute();
2102
			ResultSet rs = pstmt.getResultSet();
2103
			boolean tablehasrows = rs.next();
2104
			if (tablehasrows) {
2105
				int i = rs.getInt(1);
2106
				if (i == 1) {
2107
					pstmt.close();
2108
					//conn.close();
2109
					return true;
2110
				} else {
2111
					pstmt.close();
2112
					//conn.close();
2113
					return false;
2114
				}
2115
			}
2116
		} catch (SQLException sqle) {
2117
			logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2118
			logReplication.error("ReplicationService.replToServer - SQL error in MetacatReplication.replToServer: "
2119
					+ sqle.getMessage());
2120
		} finally {
2121
			try {
2122
				pstmt.close();
2123
				//conn.close();
2124
			}//try
2125
			catch (Exception ee) {
2126
				logMetacat.error("ReplicationService.replToServer - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
2127
				logReplication.error("ReplicationService.replToServer - Error in MetacatReplication.replToServer: "
2128
						+ ee.getMessage());
2129
			}//catch
2130
			finally {
2131
				DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2132
			}//finally
2133
		}//finally
2134
		return false;
2135
		//the default if this server does not exist is to not replicate to it.
2136
	}
2137

    
2138
}
(7-7/8)