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
|
* Release: @release@
|
8
|
*
|
9
|
* '$Author: sgarg $'
|
10
|
* '$Date: 2005-10-10 11:06:55 -0700 (Mon, 10 Oct 2005) $'
|
11
|
* '$Revision: 2663 $'
|
12
|
*
|
13
|
* This program is free software; you can redistribute it and/or modify
|
14
|
* it under the terms of the GNU General Public License as published by
|
15
|
* the Free Software Foundation; either version 2 of the License, or
|
16
|
* (at your option) any later version.
|
17
|
*
|
18
|
* This program is distributed in the hope that it will be useful,
|
19
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
20
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
21
|
* GNU General Public License for more details.
|
22
|
*
|
23
|
* You should have received a copy of the GNU General Public License
|
24
|
* along with this program; if not, write to the Free Software
|
25
|
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
26
|
*/
|
27
|
|
28
|
package edu.ucsb.nceas.metacat;
|
29
|
|
30
|
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
|
31
|
import java.util.*;
|
32
|
import java.util.Date;
|
33
|
import java.io.*;
|
34
|
import java.sql.*;
|
35
|
import java.net.*;
|
36
|
import java.lang.*;
|
37
|
import java.text.*;
|
38
|
import javax.servlet.*;
|
39
|
import javax.servlet.http.*;
|
40
|
|
41
|
import org.apache.log4j.Logger;
|
42
|
import org.xml.sax.*;
|
43
|
|
44
|
public class MetacatReplication extends HttpServlet implements Runnable
|
45
|
{
|
46
|
private long timeInterval;
|
47
|
private Date firstTime;
|
48
|
private boolean timedReplicationIsOn = false;
|
49
|
Timer replicationDaemon;
|
50
|
private static MetaCatUtil util = new MetaCatUtil();
|
51
|
private Vector fileLocks = new Vector();
|
52
|
private Thread lockThread = null;
|
53
|
private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
|
54
|
public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
|
55
|
private static final String TIMEREPLICATION = "timedreplication";
|
56
|
private static final String TIMEREPLICATIONINTERVAl = "timedreplicationinterval";
|
57
|
private static final String FIRSTTIME = "firsttimedreplication";
|
58
|
private static final int TIMEINTERVALLIMIT = 7200000;
|
59
|
private static Logger logMetacat = Logger.getLogger(MetacatReplication.class);
|
60
|
|
61
|
/**
|
62
|
* Initialize the servlet by creating appropriate database connections
|
63
|
*/
|
64
|
public void init(ServletConfig config) throws ServletException
|
65
|
{
|
66
|
//initialize db connections to handle any update requests
|
67
|
MetaCatUtil util = new MetaCatUtil();
|
68
|
//deltaT = util.getOption("deltaT");
|
69
|
//the default deltaT can be set from metacat.properties
|
70
|
//create a thread to do the delta-T check but don't execute it yet
|
71
|
replicationDaemon = new Timer(true);
|
72
|
try
|
73
|
{
|
74
|
timedReplicationIsOn = (new Boolean(util.getOption(TIMEREPLICATION ).trim())).booleanValue();
|
75
|
logMetacat.info("The timed replication on is"+timedReplicationIsOn);
|
76
|
timeInterval = (new Long(util.getOption(TIMEREPLICATIONINTERVAl).trim())).longValue();
|
77
|
logMetacat.warn("The timed replication time Inerval is "+ timeInterval);
|
78
|
String firstTimeStr = util.getOption(FIRSTTIME);
|
79
|
logMetacat.warn("first replication time form property is "+firstTimeStr);
|
80
|
firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
|
81
|
logMetacat.warn("After combine current time, the real first time is "
|
82
|
+firstTime.toString()+" minisec");
|
83
|
// set up time replication if it is on
|
84
|
if (timedReplicationIsOn)
|
85
|
{
|
86
|
replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime, timeInterval);
|
87
|
MetacatReplication.replLog("deltaT handler started with rate=" +
|
88
|
timeInterval + " mini seconds at " +firstTime.toString());
|
89
|
}
|
90
|
}
|
91
|
catch (Exception e)
|
92
|
{
|
93
|
// the timed replication in Metacat.properties file has problem
|
94
|
// so timed replication is setting to false;
|
95
|
logMetacat.error("Couldn't set up timed replication "+
|
96
|
" in Metacat replication servlet init because " +
|
97
|
e.getMessage());
|
98
|
MetacatReplication.replErrorLog("Couldn't set up timed replication "+
|
99
|
" in Metacat replication servlet init because " +
|
100
|
e.getMessage());
|
101
|
timedReplicationIsOn = false;
|
102
|
}
|
103
|
|
104
|
}
|
105
|
|
106
|
public void destroy()
|
107
|
{
|
108
|
replicationDaemon.cancel();
|
109
|
|
110
|
}
|
111
|
|
112
|
public void doGet (HttpServletRequest request, HttpServletResponse response)
|
113
|
throws ServletException, IOException
|
114
|
{
|
115
|
// Process the data and send back the response
|
116
|
handleGetOrPost(request, response);
|
117
|
}
|
118
|
|
119
|
public void doPost(HttpServletRequest request, HttpServletResponse response)
|
120
|
throws ServletException, IOException
|
121
|
{
|
122
|
// Process the data and send back the response
|
123
|
handleGetOrPost(request, response);
|
124
|
}
|
125
|
|
126
|
private void handleGetOrPost(HttpServletRequest request,
|
127
|
HttpServletResponse response)
|
128
|
throws ServletException, IOException
|
129
|
{
|
130
|
//PrintWriter out = response.getWriter();
|
131
|
//ServletOutputStream outPut = response.getOutputStream();
|
132
|
Hashtable params = new Hashtable();
|
133
|
Enumeration paramlist = request.getParameterNames();
|
134
|
|
135
|
|
136
|
|
137
|
// NOT NEEDED - doesn't provide enough security because of possible IP spoofing
|
138
|
// REPLACED with running replication comminications over HTTPS
|
139
|
// String requestingServerIP = request.getRemoteAddr();
|
140
|
// InetAddress iaddr = InetAddress.getByName(requestingServerIP);
|
141
|
// String requestingServer = iaddr.getHostName();
|
142
|
|
143
|
while (paramlist.hasMoreElements()) {
|
144
|
String name = (String)paramlist.nextElement();
|
145
|
String[] value = request.getParameterValues(name);
|
146
|
params.put(name, value);
|
147
|
}
|
148
|
|
149
|
String action = ((String[])params.get("action"))[0];
|
150
|
String server = null;
|
151
|
|
152
|
try {
|
153
|
// check if the server is included in the list of replicated servers
|
154
|
if ( !action.equals("servercontrol") &&
|
155
|
!action.equals("stop") &&
|
156
|
!action.equals("start") &&
|
157
|
!action.equals("getall") ) {
|
158
|
|
159
|
server = ((String[])params.get("server"))[0];
|
160
|
if ( getServerCodeForServerName(server) == 0 ) {
|
161
|
System.out.println("Action \"" + action +
|
162
|
"\" rejected for server: " + server);
|
163
|
return;
|
164
|
} else {
|
165
|
System.out.println("Action \"" + action +
|
166
|
"\" accepted for server: " + server);
|
167
|
}
|
168
|
}
|
169
|
else
|
170
|
{
|
171
|
// start, stop, getall and servercontrol need to check
|
172
|
// if user is administor
|
173
|
HttpSession sess = request.getSession(true);
|
174
|
String sess_id = "";
|
175
|
String username = "";
|
176
|
String[] groupnames = {""};
|
177
|
Hashtable sessionHash = MetaCatServlet.getSessionHash();
|
178
|
if (params.containsKey("sessionid"))
|
179
|
{
|
180
|
sess_id = ((String[]) params.get("sessionid"))[0];
|
181
|
logMetacat.info("in has sessionid "+ sess_id);
|
182
|
if (sessionHash.containsKey(sess_id))
|
183
|
{
|
184
|
logMetacat.info("find the id " + sess_id + " in hash table");
|
185
|
sess = (HttpSession) sessionHash.get(sess_id);
|
186
|
}
|
187
|
}
|
188
|
username = (String) sess.getAttribute("username");
|
189
|
logMetacat.warn("The user name from session is: "+ username);
|
190
|
groupnames = (String[]) sess.getAttribute("groupnames");
|
191
|
if (!MetaCatUtil.isAdministrator(username, groupnames))
|
192
|
{
|
193
|
PrintWriter out = response.getWriter();
|
194
|
out.print("<error>");
|
195
|
out.print("The user \"" + username +
|
196
|
"\" is not authorized for this action.");
|
197
|
out.print("</error>");
|
198
|
out.close();
|
199
|
logMetacat.warn("The user \"" + username +
|
200
|
"\" is not authorized for this action: " +action);
|
201
|
replErrorLog("The user \"" + username +
|
202
|
"\" is not authorized for this action: " +action);
|
203
|
return;
|
204
|
}
|
205
|
|
206
|
}// this is final else
|
207
|
} catch (Exception e) {
|
208
|
System.out.println("Error in MetacatReplication.handleGetOrPost: " +
|
209
|
e.getMessage() );
|
210
|
return;
|
211
|
}
|
212
|
|
213
|
if ( action.equals("readdata") )
|
214
|
{
|
215
|
OutputStream outStream = response.getOutputStream();
|
216
|
//to get the data file.
|
217
|
handleGetDataFileRequest(outStream, params, response);
|
218
|
outStream.close();
|
219
|
}
|
220
|
else if ( action.equals("forcereplicatedatafile") )
|
221
|
{
|
222
|
//read a specific docid from remote host, and store it into local host
|
223
|
handleForceReplicateDataFileRequest(params);
|
224
|
|
225
|
}
|
226
|
else
|
227
|
{
|
228
|
PrintWriter out = response.getWriter();
|
229
|
if ( action.equals("stop") ) {
|
230
|
//stop the replication server
|
231
|
replicationDaemon.cancel();
|
232
|
replicationDaemon = new Timer(true);
|
233
|
timedReplicationIsOn = false;
|
234
|
MetaCatUtil.setOption(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
|
235
|
out.println("Replication Handler Stopped");
|
236
|
MetacatReplication.replLog("deltaT handler stopped");
|
237
|
|
238
|
|
239
|
} else if ( action.equals("start") ) {
|
240
|
String firstTimeStr = "";
|
241
|
//start the replication server
|
242
|
if ( params.containsKey("rate") ) {
|
243
|
timeInterval = new Long(
|
244
|
new String(((String[])params.get("rate"))[0])).longValue();
|
245
|
if(timeInterval < TIMEINTERVALLIMIT) {
|
246
|
out.println("Replication deltaT rate cannot be less than "+
|
247
|
TIMEINTERVALLIMIT + " millisecs and system automatically setup the rate to "+TIMEINTERVALLIMIT);
|
248
|
//deltaT<30 is a timing mess!
|
249
|
timeInterval = TIMEINTERVALLIMIT;
|
250
|
}
|
251
|
} else {
|
252
|
timeInterval = TIMEINTERVALLIMIT ;
|
253
|
}
|
254
|
logMetacat.info("New rate is: " + timeInterval + " mini seconds.");
|
255
|
if ( params.containsKey("firsttime"))
|
256
|
{
|
257
|
firstTimeStr = ((String[])params.get("firsttime"))[0];
|
258
|
try
|
259
|
{
|
260
|
firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
|
261
|
logMetacat.info("The first time setting is "+firstTime.toString());
|
262
|
}
|
263
|
catch (Exception e)
|
264
|
{
|
265
|
throw new ServletException(e.getMessage());
|
266
|
}
|
267
|
logMetacat.warn("After combine current time, the real first time is "
|
268
|
+firstTime.toString()+" minisec");
|
269
|
}
|
270
|
else
|
271
|
{
|
272
|
MetacatReplication.replErrorLog("You should specify the first time " +
|
273
|
"to start a time replication");
|
274
|
logMetacat.warn("You should specify the first time " +
|
275
|
"to start a time replication");
|
276
|
return;
|
277
|
}
|
278
|
|
279
|
timedReplicationIsOn = true;
|
280
|
// save settings to property file
|
281
|
MetaCatUtil.setOption(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
|
282
|
// note we couldn't use firstTime object because it has date info
|
283
|
// we only need time info such as 10:00 PM
|
284
|
MetaCatUtil.setOption(FIRSTTIME, firstTimeStr);
|
285
|
MetaCatUtil.setOption(TIMEREPLICATIONINTERVAl, (new Long(timeInterval)).toString());
|
286
|
replicationDaemon.cancel();
|
287
|
replicationDaemon = new Timer(true);
|
288
|
replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime,
|
289
|
timeInterval);
|
290
|
out.println("Replication Handler Started");
|
291
|
MetacatReplication.replLog("deltaT handler started with rate=" +
|
292
|
timeInterval + " milliseconds at " +firstTime.toString());
|
293
|
|
294
|
|
295
|
} else if ( action.equals("getall") ) {
|
296
|
//updates this server exactly once
|
297
|
replicationDaemon.schedule(new ReplicationHandler(), 0);
|
298
|
response.setContentType("text/html");
|
299
|
out.println("<html><body>\"Get All\" Done</body></html>");
|
300
|
|
301
|
} else if ( action.equals("forcereplicate") ) {
|
302
|
//read a specific docid from remote host, and store it into local host
|
303
|
handleForceReplicateRequest(out, params, response);
|
304
|
|
305
|
} else if ( action.equals(FORCEREPLICATEDELETE) ) {
|
306
|
//read a specific docid from remote host, and store it into local host
|
307
|
handleForceReplicateDeleteRequest(out, params, response);
|
308
|
|
309
|
} else if ( action.equals("update") ) {
|
310
|
//request an update list from the server
|
311
|
handleUpdateRequest(out, params, response);
|
312
|
|
313
|
} else if ( action.equals("read") ) {
|
314
|
//request a specific document from the server
|
315
|
//note that this could be replaced by a call to metacatServlet
|
316
|
//handleGetDocumentAction().
|
317
|
handleGetDocumentRequest(out, params, response);
|
318
|
} else if ( action.equals("getlock") ) {
|
319
|
handleGetLockRequest(out, params, response);
|
320
|
|
321
|
} else if ( action.equals("getdocumentinfo") ) {
|
322
|
handleGetDocumentInfoRequest(out, params, response);
|
323
|
|
324
|
} else if ( action.equals("gettime") ) {
|
325
|
handleGetTimeRequest(out, params, response);
|
326
|
|
327
|
} else if ( action.equals("getcatalog") ) {
|
328
|
handleGetCatalogRequest(out, params, response, true);
|
329
|
|
330
|
} else if ( action.equals("servercontrol") ) {
|
331
|
handleServerControlRequest(out, params, response);
|
332
|
} else if ( action.equals("test") ) {
|
333
|
response.setContentType("text/html");
|
334
|
out.println("<html><body>Test successfully</body></html>");
|
335
|
}
|
336
|
|
337
|
out.close();
|
338
|
}//else
|
339
|
}
|
340
|
|
341
|
/**
|
342
|
* This method can add, delete and list the servers currently included in
|
343
|
* xml_replication.
|
344
|
* action subaction other needed params
|
345
|
* ---------------------------------------------------------
|
346
|
* servercontrol add server
|
347
|
* servercontrol delete server
|
348
|
* servercontrol list
|
349
|
*/
|
350
|
private void handleServerControlRequest(PrintWriter out, Hashtable params,
|
351
|
HttpServletResponse response)
|
352
|
{
|
353
|
String subaction = ((String[])params.get("subaction"))[0];
|
354
|
DBConnection dbConn = null;
|
355
|
int serialNumber = -1;
|
356
|
PreparedStatement pstmt = null;
|
357
|
String replicate =null;
|
358
|
String server = null;
|
359
|
String dataReplicate = null;
|
360
|
String hub = null;
|
361
|
try {
|
362
|
//conn = util.openDBConnection();
|
363
|
dbConn=DBConnectionPool.
|
364
|
getDBConnection("MetacatReplication.handleServerControlRequest");
|
365
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
366
|
|
367
|
// add server to server list
|
368
|
if ( subaction.equals("add") ) {
|
369
|
replicate = ((String[])params.get("replicate"))[0];
|
370
|
server = ((String[])params.get("server"))[0];
|
371
|
|
372
|
//Get data replication value
|
373
|
dataReplicate = ((String[])params.get("datareplicate"))[0];
|
374
|
//Get hub value
|
375
|
hub = ((String[])params.get("hub"))[0];
|
376
|
|
377
|
/*pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
|
378
|
"(server, last_checked, replicate, datareplicate, hub) " +
|
379
|
"VALUES ('" + server + "', to_date(" +
|
380
|
"'01/01/00', 'MM/DD/YY'), '" +
|
381
|
replicate +"', '" +dataReplicate+"', '"
|
382
|
+ hub +"')");*/
|
383
|
pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
|
384
|
"(server, last_checked, replicate, datareplicate, hub) " +
|
385
|
"VALUES ('" + server + "', "+
|
386
|
dbAdapter.toDate("01/01/1980", "MM/DD/YYYY")
|
387
|
+ ", '" +
|
388
|
replicate +"', '" +dataReplicate+"', '"
|
389
|
+ hub +"')");
|
390
|
|
391
|
pstmt.execute();
|
392
|
pstmt.close();
|
393
|
dbConn.commit();
|
394
|
out.println("Server " + server + " added");
|
395
|
response.setContentType("text/html");
|
396
|
out.println("<html><body><table border=\"1\">");
|
397
|
out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
|
398
|
out.println("<b>replicate</b></td>");
|
399
|
out.println("<td><b>datareplicate</b></td>");
|
400
|
out.println("<td><b>hub</b></td></tr>");
|
401
|
pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
|
402
|
//increase dbconnection usage
|
403
|
dbConn.increaseUsageCount(1);
|
404
|
|
405
|
pstmt.execute();
|
406
|
ResultSet rs = pstmt.getResultSet();
|
407
|
boolean tablehasrows = rs.next();
|
408
|
while(tablehasrows) {
|
409
|
out.println("<tr><td>" + rs.getString(2) + "</td><td>");
|
410
|
out.println(rs.getString(3) + "</td><td>");
|
411
|
out.println(rs.getString(4) + "</td><td>");
|
412
|
out.println(rs.getString(5) + "</td><td>");
|
413
|
out.println(rs.getString(6) + "</td></tr>");
|
414
|
|
415
|
tablehasrows = rs.next();
|
416
|
}
|
417
|
out.println("</table></body></html>");
|
418
|
|
419
|
// download certificate with the public key on this server
|
420
|
// and import it as a trusted certificate
|
421
|
String certURL = ((String[])params.get("certificate"))[0];
|
422
|
downloadCertificate(certURL);
|
423
|
|
424
|
// delete server from server list
|
425
|
} else if ( subaction.equals("delete") ) {
|
426
|
server = ((String[])params.get("server"))[0];
|
427
|
pstmt = dbConn.prepareStatement("DELETE FROM xml_replication " +
|
428
|
"WHERE server LIKE '" + server + "'");
|
429
|
pstmt.execute();
|
430
|
pstmt.close();
|
431
|
dbConn.commit();
|
432
|
out.println("Server " + server + " deleted");
|
433
|
response.setContentType("text/html");
|
434
|
out.println("<html><body><table border=\"1\">");
|
435
|
out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
|
436
|
out.println("<b>replicate</b></td>");
|
437
|
out.println("<td><b>datareplicate</b></td>");
|
438
|
out.println("<td><b>hub</b></td></tr>");
|
439
|
|
440
|
pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
|
441
|
//increase dbconnection usage
|
442
|
dbConn.increaseUsageCount(1);
|
443
|
pstmt.execute();
|
444
|
ResultSet rs = pstmt.getResultSet();
|
445
|
boolean tablehasrows = rs.next();
|
446
|
while(tablehasrows)
|
447
|
{
|
448
|
out.println("<tr><td>" + rs.getString(2) + "</td><td>");
|
449
|
out.println(rs.getString(3) + "</td><td>");
|
450
|
out.println(rs.getString(4) + "</td><td>");
|
451
|
out.println(rs.getString(5) + "</td><td>");
|
452
|
out.println(rs.getString(6) + "</td></tr>");
|
453
|
tablehasrows = rs.next();
|
454
|
}
|
455
|
out.println("</table></body></html>");
|
456
|
|
457
|
// list servers in server list
|
458
|
} else if ( subaction.equals("list") ) {
|
459
|
response.setContentType("text/html");
|
460
|
out.println("<html><body><table border=\"1\">");
|
461
|
out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
|
462
|
out.println("<b>replicate</b></td>");
|
463
|
out.println("<td><b>datareplicate</b></td>");
|
464
|
out.println("<td><b>hub</b></td></tr>");
|
465
|
pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
|
466
|
pstmt.execute();
|
467
|
ResultSet rs = pstmt.getResultSet();
|
468
|
boolean tablehasrows = rs.next();
|
469
|
while(tablehasrows) {
|
470
|
out.println("<tr><td>" + rs.getString(2) + "</td><td>");
|
471
|
out.println(rs.getString(3) + "</td><td>");
|
472
|
out.println(rs.getString(4) + "</td><td>");
|
473
|
out.println(rs.getString(5) + "</td><td>");
|
474
|
out.println(rs.getString(6) + "</td></tr>");
|
475
|
tablehasrows = rs.next();
|
476
|
}
|
477
|
out.println("</table></body></html>");
|
478
|
}
|
479
|
else
|
480
|
{
|
481
|
|
482
|
out.println("<error>Unkonwn subaction</error>");
|
483
|
|
484
|
}
|
485
|
pstmt.close();
|
486
|
//conn.close();
|
487
|
|
488
|
} catch(Exception e) {
|
489
|
System.out.println("Error in " +
|
490
|
"MetacatReplication.handleServerControlRequest " +
|
491
|
e.getMessage());
|
492
|
e.printStackTrace(System.out);
|
493
|
}
|
494
|
finally
|
495
|
{
|
496
|
try
|
497
|
{
|
498
|
pstmt.close();
|
499
|
}//try
|
500
|
catch (SQLException ee)
|
501
|
{
|
502
|
logMetacat.error("Error in " +
|
503
|
"MetacatReplication.handleServerControlRequest to close pstmt "
|
504
|
+ ee.getMessage());
|
505
|
}//catch
|
506
|
finally
|
507
|
{
|
508
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
509
|
}//finally
|
510
|
}//finally
|
511
|
|
512
|
}
|
513
|
|
514
|
// download certificate with the public key from certURL and
|
515
|
// upload it onto this server; it then must be imported as a
|
516
|
// trusted certificate
|
517
|
private void downloadCertificate (String certURL)
|
518
|
throws FileNotFoundException, IOException, MalformedURLException
|
519
|
{
|
520
|
MetaCatUtil util = new MetaCatUtil();
|
521
|
String certPath = util.getOption("certPath"); //the path to be uploaded to
|
522
|
|
523
|
// get filename from the URL of the certificate
|
524
|
String filename = certURL;
|
525
|
int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
|
526
|
if ( slash > -1 ) {
|
527
|
filename = filename.substring(slash + 1);
|
528
|
}
|
529
|
|
530
|
// open file output strem to write the input into it
|
531
|
File f = new File(certPath, filename);
|
532
|
synchronized (f) {
|
533
|
try {
|
534
|
if ( f.exists() ) {
|
535
|
throw new IOException("File already exist: " + f.getCanonicalFile());
|
536
|
//if ( f.exists() && !f.canWrite() ) {
|
537
|
// throw new IOException("Not writable: " + f.getCanonicalFile());
|
538
|
}
|
539
|
} catch (SecurityException se) {
|
540
|
// if a security manager exists,
|
541
|
// its checkRead method is called for f.exist()
|
542
|
// or checkWrite method is called for f.canWrite()
|
543
|
throw se;
|
544
|
}
|
545
|
|
546
|
// create a buffered byte output stream
|
547
|
// that uses a default-sized output buffer
|
548
|
FileOutputStream fos = new FileOutputStream(f);
|
549
|
BufferedOutputStream out = new BufferedOutputStream(fos);
|
550
|
|
551
|
// this should be http url
|
552
|
URL url = new URL(certURL);
|
553
|
BufferedInputStream bis = null;
|
554
|
try {
|
555
|
bis = new BufferedInputStream(url.openStream());
|
556
|
byte[] buf = new byte[4 * 1024]; // 4K buffer
|
557
|
int b = bis.read(buf);
|
558
|
while (b != -1) {
|
559
|
out.write(buf, 0, b);
|
560
|
b = bis.read(buf);
|
561
|
}
|
562
|
} finally {
|
563
|
if (bis != null) bis.close();
|
564
|
}
|
565
|
// the input and the output streams must be closed
|
566
|
bis.close();
|
567
|
out.flush();
|
568
|
out.close();
|
569
|
fos.close();
|
570
|
} // end of synchronized(f)
|
571
|
}
|
572
|
|
573
|
/**
|
574
|
* when a forcereplication request comes in, local host sends a read request
|
575
|
* to the requesting server (remote server) for the specified docid.
|
576
|
* Then store it in local database.
|
577
|
*/
|
578
|
private void handleForceReplicateRequest(PrintWriter out, Hashtable params,
|
579
|
HttpServletResponse response)
|
580
|
{
|
581
|
String server = ((String[])params.get("server"))[0]; // the server that
|
582
|
String docid = ((String[])params.get("docid"))[0]; // sent the document
|
583
|
String dbaction = "UPDATE"; // the default action is UPDATE
|
584
|
boolean override = false;
|
585
|
int serverCode = 1;
|
586
|
DBConnection dbConn = null;
|
587
|
int serialNumber = -1;
|
588
|
|
589
|
try {
|
590
|
//if the url contains a dbaction then the default action is overridden
|
591
|
if(params.containsKey("dbaction")) {
|
592
|
dbaction = ((String[])params.get("dbaction"))[0];
|
593
|
//serverCode = MetacatReplication.getServerCode(server);
|
594
|
//override = true; //we are now overriding the default action
|
595
|
}
|
596
|
MetacatReplication.replLog("force replication request from " + server);
|
597
|
logMetacat.info("Force replication request from: "+ server);
|
598
|
logMetacat.info("Force replication docid: "+docid);
|
599
|
logMetacat.info("Force replication action: "+dbaction);
|
600
|
// sending back read request to remote server
|
601
|
URL u = new URL("https://" + server + "?server="
|
602
|
+util.getLocalReplicationServerName()
|
603
|
+"&action=read&docid=" + docid);
|
604
|
String xmldoc = MetacatReplication.getURLContent(u);
|
605
|
|
606
|
// get the document info from server
|
607
|
URL docinfourl = new URL("https://" + server +
|
608
|
"?server="+util.getLocalReplicationServerName()
|
609
|
+"&action=getdocumentinfo&docid=" + docid);
|
610
|
|
611
|
String docInfoStr = MetacatReplication.getURLContent(docinfourl);
|
612
|
|
613
|
//dih is the parser for the docinfo xml format
|
614
|
DocInfoHandler dih = new DocInfoHandler();
|
615
|
XMLReader docinfoParser = ReplicationHandler.initParser(dih);
|
616
|
docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
|
617
|
Hashtable docinfoHash = dih.getDocInfo();
|
618
|
|
619
|
// Get user owner of this docid
|
620
|
String user = (String)docinfoHash.get("user_owner");
|
621
|
// Get home server of this docid
|
622
|
String homeServer=(String)docinfoHash.get("home_server");
|
623
|
String createdDate = (String)docinfoHash.get("date_created");
|
624
|
String updatedDate = (String)docinfoHash.get("date_updated");
|
625
|
logMetacat.info("homeServer: "+homeServer);
|
626
|
// Get Document type
|
627
|
String docType = (String)docinfoHash.get("doctype");
|
628
|
logMetacat.info("docType: "+docType);
|
629
|
String parserBase = null;
|
630
|
// this for eml2 and we need user eml2 parser
|
631
|
if (docType != null &&
|
632
|
(docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
|
633
|
{
|
634
|
logMetacat.warn("This is an eml200 document!");
|
635
|
parserBase = DocumentImpl.EML200;
|
636
|
}
|
637
|
else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
|
638
|
{
|
639
|
logMetacat.warn("This is an eml2.0.1 document!");
|
640
|
parserBase = DocumentImpl.EML200;
|
641
|
}
|
642
|
else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
|
643
|
{
|
644
|
logMetacat.warn("This is an eml2.1.0 document!");
|
645
|
parserBase = DocumentImpl.EML210;
|
646
|
}
|
647
|
logMetacat.warn("The parserBase is: "+parserBase);
|
648
|
|
649
|
// Get DBConnection from pool
|
650
|
dbConn=DBConnectionPool.
|
651
|
getDBConnection("MetacatReplication.handleForceReplicateRequest");
|
652
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
653
|
// write the document to local database
|
654
|
DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
|
655
|
wrapper.writeReplication(dbConn, new StringReader(xmldoc), null, null,
|
656
|
dbaction, docid, user, null, homeServer,
|
657
|
server, createdDate, updatedDate);
|
658
|
|
659
|
MetacatReplication.replLog("document " + docid + " added to DB with " +
|
660
|
"action " + dbaction);
|
661
|
}//try
|
662
|
catch(Exception e)
|
663
|
{
|
664
|
MetacatReplication.replErrorLog("document " + docid +
|
665
|
" failed to added to DB with " +
|
666
|
"action " + dbaction + " because "+
|
667
|
e.getMessage());
|
668
|
logMetacat.error("ERROR in MetacatReplication.handleForceReplicate" +
|
669
|
"Request(): " + e.getMessage());
|
670
|
|
671
|
}//catch
|
672
|
finally
|
673
|
{
|
674
|
// Return the checked out DBConnection
|
675
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
676
|
}//finally
|
677
|
}
|
678
|
|
679
|
/*
|
680
|
* when a forcereplication delete request comes in, local host will delete this
|
681
|
* document
|
682
|
*/
|
683
|
private void handleForceReplicateDeleteRequest(PrintWriter out, Hashtable params,
|
684
|
HttpServletResponse response)
|
685
|
{
|
686
|
String server = ((String[])params.get("server"))[0]; // the server that
|
687
|
String docid = ((String[])params.get("docid"))[0]; // sent the document
|
688
|
try
|
689
|
{
|
690
|
MetacatReplication.replLog("force replication delete request from " + server);
|
691
|
MetacatReplication.replLog("force replication delete docid " + docid);
|
692
|
logMetacat.info("Force replication delete request from: "+ server);
|
693
|
logMetacat.info("Force replication delete docid: "+docid);
|
694
|
DocumentImpl.delete(docid, null, null, server);
|
695
|
MetacatReplication.replLog("document " + docid + " was successfully deleted ");
|
696
|
logMetacat.info("document " + docid + " was successfully deleted ");
|
697
|
}
|
698
|
catch(Exception e)
|
699
|
{
|
700
|
MetacatReplication.replErrorLog("document " + docid +
|
701
|
" failed to delete because "+
|
702
|
e.getMessage());
|
703
|
logMetacat.error("ERROR in MetacatReplication.handleForceDeleteReplicate" +
|
704
|
"Request(): " + e.getMessage());
|
705
|
|
706
|
}//catch
|
707
|
|
708
|
}
|
709
|
|
710
|
|
711
|
/**
|
712
|
* when a forcereplication data file request comes in, local host sends a
|
713
|
* readdata request to the requesting server (remote server) for the specified
|
714
|
* docid. Then store it in local database and file system
|
715
|
*/
|
716
|
private void handleForceReplicateDataFileRequest(Hashtable params)
|
717
|
{
|
718
|
|
719
|
//make sure there is some parameters
|
720
|
if(params.isEmpty())
|
721
|
{
|
722
|
return;
|
723
|
}
|
724
|
// Get remote server
|
725
|
String server = ((String[])params.get("server"))[0];
|
726
|
// the docid should include rev number
|
727
|
String docid = ((String[])params.get("docid"))[0];
|
728
|
// Make sure there is a docid and server
|
729
|
if (docid==null || server==null || server.equals(""))
|
730
|
{
|
731
|
logMetacat.error("Didn't specify docid or server for replication");
|
732
|
return;
|
733
|
}
|
734
|
|
735
|
// Overide or not
|
736
|
boolean override = false;
|
737
|
// dbaction - update or insert
|
738
|
String dbaction=null;
|
739
|
|
740
|
try
|
741
|
{
|
742
|
//docid was switch to two parts uinque code and rev
|
743
|
//String uniqueCode=MetaCatUtil.getDocIdFromString(docid);
|
744
|
//int rev=MetaCatUtil.getVersionFromString(docid);
|
745
|
if(params.containsKey("dbaction"))
|
746
|
{
|
747
|
dbaction = ((String[])params.get("dbaction"))[0];
|
748
|
}
|
749
|
else//default value is update
|
750
|
{
|
751
|
dbaction = "update";
|
752
|
}
|
753
|
|
754
|
MetacatReplication.replLog("force replication request from " + server);
|
755
|
logMetacat.info("Force replication request from: "+ server);
|
756
|
logMetacat.info("Force replication docid: "+docid);
|
757
|
logMetacat.info("Force replication action: "+dbaction);
|
758
|
// get the document info from server
|
759
|
URL docinfourl = new URL("https://" + server +
|
760
|
"?server="+util.getLocalReplicationServerName()
|
761
|
+"&action=getdocumentinfo&docid=" + docid);
|
762
|
|
763
|
String docInfoStr = MetacatReplication.getURLContent(docinfourl);
|
764
|
|
765
|
//dih is the parser for the docinfo xml format
|
766
|
DocInfoHandler dih = new DocInfoHandler();
|
767
|
XMLReader docinfoParser = ReplicationHandler.initParser(dih);
|
768
|
docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
|
769
|
Hashtable docinfoHash = dih.getDocInfo();
|
770
|
String user = (String)docinfoHash.get("user_owner");
|
771
|
|
772
|
String docName = (String)docinfoHash.get("docname");
|
773
|
|
774
|
String docType = (String)docinfoHash.get("doctype");
|
775
|
|
776
|
String docHomeServer= (String)docinfoHash.get("home_server");
|
777
|
|
778
|
String createdDate = (String)docinfoHash.get("date_created");
|
779
|
|
780
|
String updatedDate = (String)docinfoHash.get("date_updated");
|
781
|
logMetacat.info("docHomeServer of datafile: "+docHomeServer);
|
782
|
|
783
|
|
784
|
|
785
|
//if action is delete, we don't delete the data file. Just archieve
|
786
|
//the xml_documents
|
787
|
/*if (dbaction.equals("delete"))
|
788
|
{
|
789
|
//conn = util.getConnection();
|
790
|
DocumentImpl.delete(docid,user,null);
|
791
|
//util.returnConnection(conn);
|
792
|
}*/
|
793
|
//To data file insert or update is same
|
794
|
if (dbaction.equals("insert")||dbaction.equals("update"))
|
795
|
{
|
796
|
//Get data file and store it into local file system.
|
797
|
// sending back readdata request to server
|
798
|
URL url = new URL("https://" + server + "?server="
|
799
|
+util.getLocalReplicationServerName()
|
800
|
+"&action=readdata&docid=" + docid);
|
801
|
String datafilePath = util.getOption("datafilepath");
|
802
|
//register data file into xml_documents table and wite data file
|
803
|
//into file system
|
804
|
DocumentImpl.writeDataFileInReplication(url.openStream(), datafilePath,
|
805
|
docName, docType, docid, user,docHomeServer,server,
|
806
|
DocumentImpl.DOCUMENTTABLE, false, createdDate, updatedDate);
|
807
|
//false means non-timed replication
|
808
|
}
|
809
|
|
810
|
|
811
|
|
812
|
MetacatReplication.replLog("datafile " + docid + " added to DB with " +
|
813
|
"action " + dbaction);
|
814
|
}
|
815
|
catch(Exception e)
|
816
|
{
|
817
|
|
818
|
MetacatReplication.replErrorLog("Datafile " + docid +
|
819
|
" failed to added to DB with " +
|
820
|
"action " + dbaction + " because "+
|
821
|
e.getMessage());
|
822
|
logMetacat.error
|
823
|
("ERROR in MetacatReplication.handleForceDataFileReplicate" +
|
824
|
"Request(): " + e.getMessage());
|
825
|
}
|
826
|
}
|
827
|
/**
|
828
|
* Grants or denies a lock to a requesting host.
|
829
|
* The servlet parameters of interrest are:
|
830
|
* docid: the docid of the file the lock is being requested for
|
831
|
* currentdate: the timestamp of the document on the remote server
|
832
|
*
|
833
|
*/
|
834
|
private void handleGetLockRequest(PrintWriter out, Hashtable params,
|
835
|
HttpServletResponse response)
|
836
|
{
|
837
|
|
838
|
try
|
839
|
{
|
840
|
|
841
|
String docid = ((String[])params.get("docid"))[0];
|
842
|
String remoteRev = ((String[])params.get("updaterev"))[0];
|
843
|
DocumentImpl requestDoc = new DocumentImpl(docid);
|
844
|
MetacatReplication.replLog("lock request for " + docid);
|
845
|
int localRevInt = requestDoc.getRev();
|
846
|
int remoteRevInt = Integer.parseInt(remoteRev);
|
847
|
|
848
|
if(remoteRevInt >= localRevInt)
|
849
|
{
|
850
|
if(!fileLocks.contains(docid))
|
851
|
{ //grant the lock if it is not already locked
|
852
|
fileLocks.add(0, docid); //insert at the beginning of the queue Vector
|
853
|
//send a message back to the the remote host authorizing the insert
|
854
|
out.println("<lockgranted><docid>" +docid+ "</docid></lockgranted>");
|
855
|
lockThread = new Thread(this);
|
856
|
lockThread.setPriority(Thread.MIN_PRIORITY);
|
857
|
lockThread.start();
|
858
|
MetacatReplication.replLog("lock granted for " + docid);
|
859
|
}
|
860
|
else
|
861
|
{ //deny the lock
|
862
|
out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
|
863
|
MetacatReplication.replLog("lock denied for " + docid +
|
864
|
"reason: file already locked");
|
865
|
}
|
866
|
}
|
867
|
else
|
868
|
{//deny the lock.
|
869
|
out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
|
870
|
MetacatReplication.replLog("lock denied for " + docid +
|
871
|
"reason: client has outdated file");
|
872
|
}
|
873
|
//conn.close();
|
874
|
}
|
875
|
catch(Exception e)
|
876
|
{
|
877
|
System.out.println("error requesting file lock from MetacatReplication." +
|
878
|
"handleGetLockRequest: " + e.getMessage());
|
879
|
e.printStackTrace(System.out);
|
880
|
}
|
881
|
}
|
882
|
|
883
|
/**
|
884
|
* Sends all of the xml_documents information encoded in xml to a requestor
|
885
|
* the format is:
|
886
|
* <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
|
887
|
* user_updated, home_server, public_access, rev)/>
|
888
|
* all of the subelements of document info are #PCDATA
|
889
|
*/
|
890
|
private void handleGetDocumentInfoRequest(PrintWriter out, Hashtable params,
|
891
|
HttpServletResponse response)
|
892
|
{
|
893
|
String docid = ((String[])(params.get("docid")))[0];
|
894
|
StringBuffer sb = new StringBuffer();
|
895
|
|
896
|
try
|
897
|
{
|
898
|
|
899
|
DocumentImpl doc = new DocumentImpl(docid);
|
900
|
sb.append("<documentinfo><docid>").append(docid);
|
901
|
sb.append("</docid><docname>").append(doc.getDocname());
|
902
|
sb.append("</docname><doctype>").append(doc.getDoctype());
|
903
|
sb.append("</doctype>");
|
904
|
sb.append("<user_owner>").append(doc.getUserowner());
|
905
|
sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
|
906
|
sb.append("</user_updated>");
|
907
|
sb.append("<date_created>");
|
908
|
sb.append(doc.getCreateDate());
|
909
|
sb.append("</date_created>");
|
910
|
sb.append("<date_updated>");
|
911
|
sb.append(doc.getUpdateDate());
|
912
|
sb.append("</date_updated>");
|
913
|
sb.append("<home_server>");
|
914
|
sb.append(doc.getDocHomeServer());
|
915
|
sb.append("</home_server>");
|
916
|
sb.append("<public_access>").append(doc.getPublicaccess());
|
917
|
sb.append("</public_access><rev>").append(doc.getRev());
|
918
|
sb.append("</rev></documentinfo>");
|
919
|
response.setContentType("text/xml");
|
920
|
out.println(sb.toString());
|
921
|
|
922
|
}
|
923
|
catch (Exception e)
|
924
|
{
|
925
|
System.out.println("error in " +
|
926
|
"metacatReplication.handlegetdocumentinforequest: " +
|
927
|
e.getMessage());
|
928
|
}
|
929
|
|
930
|
}
|
931
|
|
932
|
/**
|
933
|
* Sends a datafile to a remote host
|
934
|
*/
|
935
|
private void handleGetDataFileRequest(OutputStream outPut,
|
936
|
Hashtable params, HttpServletResponse response)
|
937
|
|
938
|
{
|
939
|
// File path for data file
|
940
|
String filepath = util.getOption("datafilepath");
|
941
|
// Request docid
|
942
|
String docId = ((String[])(params.get("docid")))[0];
|
943
|
//check if the doicd is null
|
944
|
if (docId==null)
|
945
|
{
|
946
|
logMetacat.error("Didn't specify docid for replication");
|
947
|
return;
|
948
|
}
|
949
|
|
950
|
//try to open a https stream to test if the request server's public key
|
951
|
//in the key store, this is security issue
|
952
|
try
|
953
|
{
|
954
|
String server = ((String[])params.get("server"))[0];
|
955
|
URL u = new URL("https://" + server + "?server="
|
956
|
+util.getLocalReplicationServerName()
|
957
|
+"&action=test");
|
958
|
String test = MetacatReplication.getURLContent(u);
|
959
|
//couldn't pass the test
|
960
|
if (test.indexOf("successfully")==-1)
|
961
|
{
|
962
|
//response.setContentType("text/xml");
|
963
|
//outPut.println("<error>Couldn't pass the trust test</error>");
|
964
|
logMetacat.error("Couldn't pass the trust test");
|
965
|
return;
|
966
|
}
|
967
|
}//try
|
968
|
catch (Exception ee)
|
969
|
{
|
970
|
return;
|
971
|
}//catch
|
972
|
|
973
|
if(!filepath.endsWith("/"))
|
974
|
{
|
975
|
filepath += "/";
|
976
|
}
|
977
|
// Get file aboslute file name
|
978
|
String filename = filepath + docId;
|
979
|
|
980
|
//MIME type
|
981
|
String contentType = null;
|
982
|
if (filename.endsWith(".xml"))
|
983
|
{
|
984
|
contentType="text/xml";
|
985
|
}
|
986
|
else if (filename.endsWith(".css"))
|
987
|
{
|
988
|
contentType="text/css";
|
989
|
}
|
990
|
else if (filename.endsWith(".dtd"))
|
991
|
{
|
992
|
contentType="text/plain";
|
993
|
}
|
994
|
else if (filename.endsWith(".xsd"))
|
995
|
{
|
996
|
contentType="text/xml";
|
997
|
}
|
998
|
else if (filename.endsWith("/"))
|
999
|
{
|
1000
|
contentType="text/html";
|
1001
|
}
|
1002
|
else
|
1003
|
{
|
1004
|
File f = new File(filename);
|
1005
|
if ( f.isDirectory() )
|
1006
|
{
|
1007
|
contentType="text/html";
|
1008
|
}
|
1009
|
else
|
1010
|
{
|
1011
|
contentType="application/octet-stream";
|
1012
|
}
|
1013
|
}
|
1014
|
|
1015
|
// Set the mime type
|
1016
|
response.setContentType(contentType);
|
1017
|
|
1018
|
// Get the content of the file
|
1019
|
FileInputStream fin = null;
|
1020
|
try
|
1021
|
{
|
1022
|
// FileInputStream to metacat
|
1023
|
fin = new FileInputStream(filename);
|
1024
|
// 4K buffer
|
1025
|
byte[] buf = new byte[4 * 1024];
|
1026
|
// Read data from file input stream to byte array
|
1027
|
int b = fin.read(buf);
|
1028
|
// Write to outStream from byte array
|
1029
|
while (b != -1)
|
1030
|
{
|
1031
|
outPut.write(buf, 0, b);
|
1032
|
b = fin.read(buf);
|
1033
|
}
|
1034
|
// close file input stream
|
1035
|
fin.close();
|
1036
|
|
1037
|
}//try
|
1038
|
catch(Exception e)
|
1039
|
{
|
1040
|
System.out.println("error getting data file from MetacatReplication." +
|
1041
|
"handlGetDataFileRequest " + e.getMessage());
|
1042
|
e.printStackTrace(System.out);
|
1043
|
}//catch
|
1044
|
|
1045
|
}
|
1046
|
|
1047
|
|
1048
|
/**
|
1049
|
* Sends a document to a remote host
|
1050
|
*/
|
1051
|
private void handleGetDocumentRequest(PrintWriter out, Hashtable params,
|
1052
|
HttpServletResponse response)
|
1053
|
{
|
1054
|
|
1055
|
try
|
1056
|
{
|
1057
|
//try to open a https stream to test if the request server's public key
|
1058
|
//in the key store, this is security issue
|
1059
|
String server = ((String[])params.get("server"))[0];
|
1060
|
URL u = new URL("https://" + server + "?server="
|
1061
|
+util.getLocalReplicationServerName()
|
1062
|
+"&action=test");
|
1063
|
String test = MetacatReplication.getURLContent(u);
|
1064
|
//couldn't pass the test
|
1065
|
if (test.indexOf("successfully")==-1)
|
1066
|
{
|
1067
|
response.setContentType("text/xml");
|
1068
|
out.println("<error>Couldn't pass the trust test</error>");
|
1069
|
out.close();
|
1070
|
return;
|
1071
|
}
|
1072
|
|
1073
|
String docid = ((String[])(params.get("docid")))[0];
|
1074
|
|
1075
|
DocumentImpl di = new DocumentImpl(docid);
|
1076
|
response.setContentType("text/xml");
|
1077
|
out.print(di.toString(null, null, true));
|
1078
|
|
1079
|
MetacatReplication.replLog("document " + docid + " sent");
|
1080
|
|
1081
|
}
|
1082
|
catch(Exception e)
|
1083
|
{
|
1084
|
logMetacat.error("error getting document from MetacatReplication."
|
1085
|
+"handlGetDocumentRequest " + e.getMessage());
|
1086
|
//e.printStackTrace(System.out);
|
1087
|
response.setContentType("text/xml");
|
1088
|
out.println("<error>"+e.getMessage()+"</error>");
|
1089
|
}
|
1090
|
|
1091
|
}
|
1092
|
|
1093
|
/**
|
1094
|
* Sends a list of all of the documents on this sever along with their
|
1095
|
* revision numbers.
|
1096
|
* The format is:
|
1097
|
* <!ELEMENT replication (server, updates)>
|
1098
|
* <!ELEMENT server (#PCDATA)>
|
1099
|
* <!ELEMENT updates ((updatedDocument | deleteDocument | revisionDocument)*)>
|
1100
|
* <!ELEMENT updatedDocument (docid, rev, datafile*)>
|
1101
|
* <!ELEMENT deletedDocument (docid, rev)>
|
1102
|
* <!ELEMENT revisionDocument (docid, rev, datafile*)>
|
1103
|
* <!ELEMENT docid (#PCDATA)>
|
1104
|
* <!ELEMENT rev (#PCDATA)>
|
1105
|
* <!ELEMENT datafile (#PCDATA)>
|
1106
|
* note that the rev in deletedDocument is always empty. I just left
|
1107
|
* it in there to make the parser implementation easier.
|
1108
|
*/
|
1109
|
private void handleUpdateRequest(PrintWriter out, Hashtable params,
|
1110
|
HttpServletResponse response)
|
1111
|
{
|
1112
|
// Checked out DBConnection
|
1113
|
DBConnection dbConn = null;
|
1114
|
// DBConenction serial number when checked it out
|
1115
|
int serialNumber = -1;
|
1116
|
PreparedStatement pstmt = null;
|
1117
|
// Server list to store server info of xml_replication table
|
1118
|
ReplicationServerList serverList = null;
|
1119
|
|
1120
|
try
|
1121
|
{
|
1122
|
// Check out a DBConnection from pool
|
1123
|
dbConn=DBConnectionPool.
|
1124
|
getDBConnection("MetacatReplication.handleUpdateRequest");
|
1125
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
1126
|
// Create a server list from xml_replication table
|
1127
|
serverList = new ReplicationServerList();
|
1128
|
|
1129
|
// Get remote server name from param
|
1130
|
String server = ((String[])params.get("server"))[0];
|
1131
|
// If no servr name in param, return a error
|
1132
|
if ( server == null || server.equals(""))
|
1133
|
{
|
1134
|
response.setContentType("text/xml");
|
1135
|
out.println("<error>Request didn't specify server name</error>");
|
1136
|
out.close();
|
1137
|
return;
|
1138
|
}//if
|
1139
|
|
1140
|
//try to open a https stream to test if the request server's public key
|
1141
|
//in the key store, this is security issue
|
1142
|
URL u = new URL("https://" + server + "?server="
|
1143
|
+util.getLocalReplicationServerName()
|
1144
|
+"&action=test");
|
1145
|
String test = MetacatReplication.getURLContent(u);
|
1146
|
//couldn't pass the test
|
1147
|
if (test.indexOf("successfully")==-1)
|
1148
|
{
|
1149
|
response.setContentType("text/xml");
|
1150
|
out.println("<error>Couldn't pass the trust test</error>");
|
1151
|
out.close();
|
1152
|
return;
|
1153
|
}
|
1154
|
|
1155
|
|
1156
|
// Check if local host configure to replicate xml documents to remote
|
1157
|
// server. If not send back a error message
|
1158
|
if (!serverList.getReplicationValue(server))
|
1159
|
{
|
1160
|
response.setContentType("text/xml");
|
1161
|
out.println
|
1162
|
("<error>Configuration not allow to replicate document to you</error>");
|
1163
|
out.close();
|
1164
|
return;
|
1165
|
}//if
|
1166
|
|
1167
|
// Store the sql command
|
1168
|
StringBuffer docsql = new StringBuffer();
|
1169
|
StringBuffer revisionSql = new StringBuffer();
|
1170
|
// Stroe the docid list
|
1171
|
StringBuffer doclist = new StringBuffer();
|
1172
|
// Store the deleted docid list
|
1173
|
StringBuffer delsql = new StringBuffer();
|
1174
|
// Store the data set file
|
1175
|
Vector packageFiles = new Vector();
|
1176
|
|
1177
|
// Append local server's name and replication servlet to doclist
|
1178
|
doclist.append("<?xml version=\"1.0\"?><replication>");
|
1179
|
doclist.append("<server>").append(util.getLocalReplicationServerName());
|
1180
|
//doclist.append(util.getOption("replicationpath"));
|
1181
|
doclist.append("</server><updates>");
|
1182
|
|
1183
|
// Get correct docid that reside on this server according the requesting
|
1184
|
// server's replicate and data replicate value in xml_replication table
|
1185
|
docsql.append("select docid, rev, doctype from xml_documents ");
|
1186
|
revisionSql.append("select docid, rev, doctype from xml_revisions ");
|
1187
|
// If the localhost is not a hub to the remote server, only replicate
|
1188
|
// the docid' which home server is local host (server_location =1)
|
1189
|
if (!serverList.getHubValue(server))
|
1190
|
{
|
1191
|
String serverLocation = "where server_location = 1";
|
1192
|
docsql.append(serverLocation);
|
1193
|
revisionSql.append(serverLocation);
|
1194
|
}
|
1195
|
logMetacat.info("Doc sql: "+docsql.toString());
|
1196
|
|
1197
|
// Get any deleted documents
|
1198
|
delsql.append("select distinct docid from ");
|
1199
|
delsql.append("xml_revisions where docid not in (select docid from ");
|
1200
|
delsql.append("xml_documents) ");
|
1201
|
// If the localhost is not a hub to the remote server, only replicate
|
1202
|
// the docid' which home server is local host (server_location =1)
|
1203
|
if (!serverList.getHubValue(server))
|
1204
|
{
|
1205
|
delsql.append("and server_location = 1");
|
1206
|
}
|
1207
|
logMetacat.info("Deleted sql: "+delsql.toString());
|
1208
|
|
1209
|
|
1210
|
|
1211
|
// Get docid list of local host
|
1212
|
pstmt = dbConn.prepareStatement(docsql.toString());
|
1213
|
pstmt.execute();
|
1214
|
ResultSet rs = pstmt.getResultSet();
|
1215
|
boolean tablehasrows = rs.next();
|
1216
|
//If metacat configed to replicate data file
|
1217
|
//if ((util.getOption("replicationsenddata")).equals("on"))
|
1218
|
boolean replicateData = serverList.getDataReplicationValue(server);
|
1219
|
if (replicateData)
|
1220
|
{
|
1221
|
while(tablehasrows)
|
1222
|
{
|
1223
|
String recordDoctype = rs.getString(3);
|
1224
|
Vector packagedoctypes = MetaCatUtil.getOptionList(
|
1225
|
MetaCatUtil.getOption("packagedoctype"));
|
1226
|
//if this is a package file, put it at the end
|
1227
|
//because if a package file is read before all of the files it
|
1228
|
//refers to are loaded then there is an error
|
1229
|
if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
|
1230
|
{
|
1231
|
//If this is not data file
|
1232
|
if (!recordDoctype.equals("BIN"))
|
1233
|
{
|
1234
|
//for non-data file document
|
1235
|
doclist.append("<updatedDocument>");
|
1236
|
doclist.append("<docid>").append(rs.getString(1));
|
1237
|
doclist.append("</docid><rev>").append(rs.getInt(2));
|
1238
|
doclist.append("</rev>");
|
1239
|
doclist.append("</updatedDocument>");
|
1240
|
}//if
|
1241
|
else
|
1242
|
{
|
1243
|
//for data file document, in datafile attributes
|
1244
|
//we put "datafile" value there
|
1245
|
doclist.append("<updatedDocument>");
|
1246
|
doclist.append("<docid>").append(rs.getString(1));
|
1247
|
doclist.append("</docid><rev>").append(rs.getInt(2));
|
1248
|
doclist.append("</rev>");
|
1249
|
doclist.append("<datafile>");
|
1250
|
doclist.append(MetaCatUtil.getOption("datafileflag"));
|
1251
|
doclist.append("</datafile>");
|
1252
|
doclist.append("</updatedDocument>");
|
1253
|
}//else
|
1254
|
}//if packagedoctpes
|
1255
|
else
|
1256
|
{ //the package files are saved to be put into the xml later.
|
1257
|
Vector v = new Vector();
|
1258
|
v.add(new String(rs.getString(1)));
|
1259
|
v.add(new Integer(rs.getInt(2)));
|
1260
|
packageFiles.add(new Vector(v));
|
1261
|
}//esle
|
1262
|
tablehasrows = rs.next();
|
1263
|
}//while
|
1264
|
}//if
|
1265
|
else //metacat was configured not to send data file
|
1266
|
{
|
1267
|
while(tablehasrows)
|
1268
|
{
|
1269
|
String recordDoctype = rs.getString(3);
|
1270
|
if(!recordDoctype.equals("BIN"))
|
1271
|
{ //don't replicate data files
|
1272
|
Vector packagedoctypes = MetaCatUtil.getOptionList(
|
1273
|
MetaCatUtil.getOption("packagedoctype"));
|
1274
|
if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
|
1275
|
{ //if this is a package file, put it at the end
|
1276
|
//because if a package file is read before all of the files it
|
1277
|
//refers to are loaded then there is an error
|
1278
|
doclist.append("<updatedDocument>");
|
1279
|
doclist.append("<docid>").append(rs.getString(1));
|
1280
|
doclist.append("</docid><rev>").append(rs.getInt(2));
|
1281
|
doclist.append("</rev>");
|
1282
|
doclist.append("</updatedDocument>");
|
1283
|
}
|
1284
|
else
|
1285
|
{ //the package files are saved to be put into the xml later.
|
1286
|
Vector v = new Vector();
|
1287
|
v.add(new String(rs.getString(1)));
|
1288
|
v.add(new Integer(rs.getInt(2)));
|
1289
|
packageFiles.add(new Vector(v));
|
1290
|
}
|
1291
|
}//if
|
1292
|
tablehasrows = rs.next();
|
1293
|
}//while
|
1294
|
}//else
|
1295
|
|
1296
|
pstmt = dbConn.prepareStatement(delsql.toString());
|
1297
|
//usage count should increas 1
|
1298
|
dbConn.increaseUsageCount(1);
|
1299
|
|
1300
|
pstmt.execute();
|
1301
|
rs = pstmt.getResultSet();
|
1302
|
tablehasrows = rs.next();
|
1303
|
while(tablehasrows)
|
1304
|
{ //handle the deleted documents
|
1305
|
doclist.append("<deletedDocument><docid>").append(rs.getString(1));
|
1306
|
doclist.append("</docid><rev></rev></deletedDocument>");
|
1307
|
//note that rev is always empty for deleted docs
|
1308
|
tablehasrows = rs.next();
|
1309
|
}
|
1310
|
|
1311
|
//now we can put the package files into the xml results
|
1312
|
for(int i=0; i<packageFiles.size(); i++)
|
1313
|
{
|
1314
|
Vector v = (Vector)packageFiles.elementAt(i);
|
1315
|
doclist.append("<updatedDocument>");
|
1316
|
doclist.append("<docid>").append((String)v.elementAt(0));
|
1317
|
doclist.append("</docid><rev>");
|
1318
|
doclist.append(((Integer)v.elementAt(1)).intValue());
|
1319
|
doclist.append("</rev>");
|
1320
|
doclist.append("</updatedDocument>");
|
1321
|
}
|
1322
|
// add revision doc list
|
1323
|
doclist.append(prepareRevisionDoc(dbConn,revisionSql.toString(),replicateData));
|
1324
|
|
1325
|
doclist.append("</updates></replication>");
|
1326
|
logMetacat.info("doclist: " + doclist.toString());
|
1327
|
pstmt.close();
|
1328
|
//conn.close();
|
1329
|
response.setContentType("text/xml");
|
1330
|
out.println(doclist.toString());
|
1331
|
|
1332
|
}
|
1333
|
catch(Exception e)
|
1334
|
{
|
1335
|
logMetacat.error("error in MetacatReplication." +
|
1336
|
"handleupdaterequest: " + e.getMessage());
|
1337
|
//e.printStackTrace(System.out);
|
1338
|
response.setContentType("text/xml");
|
1339
|
out.println("<error>"+e.getMessage()+"</error>");
|
1340
|
}
|
1341
|
finally
|
1342
|
{
|
1343
|
try
|
1344
|
{
|
1345
|
pstmt.close();
|
1346
|
}//try
|
1347
|
catch (SQLException ee)
|
1348
|
{
|
1349
|
logMetacat.error("Error in MetacatReplication." +
|
1350
|
"handleUpdaterequest to close pstmt: "+ee.getMessage());
|
1351
|
}//catch
|
1352
|
finally
|
1353
|
{
|
1354
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
1355
|
}//finally
|
1356
|
}//finally
|
1357
|
|
1358
|
}//handlUpdateRequest
|
1359
|
|
1360
|
/*
|
1361
|
* This method will get the xml string for document in xml_revision
|
1362
|
* The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
|
1363
|
*/
|
1364
|
private String prepareRevisionDoc(DBConnection dbConn, String revSql,
|
1365
|
boolean replicateData) throws Exception
|
1366
|
{
|
1367
|
logMetacat.warn("The revision document sql is "+ revSql);
|
1368
|
StringBuffer revDocList = new StringBuffer();
|
1369
|
PreparedStatement pstmt = dbConn.prepareStatement(revSql);
|
1370
|
//usage count should increas 1
|
1371
|
dbConn.increaseUsageCount(1);
|
1372
|
|
1373
|
pstmt.execute();
|
1374
|
ResultSet rs = pstmt.getResultSet();
|
1375
|
boolean tablehasrows = rs.next();
|
1376
|
while(tablehasrows)
|
1377
|
{
|
1378
|
String recordDoctype = rs.getString(3);
|
1379
|
|
1380
|
//If this is data file and it isn't configured to replicate data
|
1381
|
if (recordDoctype.equals("BIN") && !replicateData)
|
1382
|
{
|
1383
|
// do nothing
|
1384
|
continue;
|
1385
|
}
|
1386
|
else
|
1387
|
{
|
1388
|
|
1389
|
revDocList.append("<revisionDocument>");
|
1390
|
revDocList.append("<docid>").append(rs.getString(1));
|
1391
|
revDocList.append("</docid><rev>").append(rs.getInt(2));
|
1392
|
revDocList.append("</rev>");
|
1393
|
// data file
|
1394
|
if (recordDoctype.equals("BIN"))
|
1395
|
{
|
1396
|
revDocList.append("<datafile>");
|
1397
|
revDocList.append(MetaCatUtil.getOption("datafileflag"));
|
1398
|
revDocList.append("</datafile>");
|
1399
|
}
|
1400
|
revDocList.append("</revisionDocument>");
|
1401
|
|
1402
|
}//else
|
1403
|
tablehasrows = rs.next();
|
1404
|
}
|
1405
|
//System.out.println("The revision list is"+ revDocList.toString());
|
1406
|
return revDocList.toString();
|
1407
|
}
|
1408
|
|
1409
|
/**
|
1410
|
* Returns the xml_catalog table encoded in xml
|
1411
|
*/
|
1412
|
public static String getCatalogXML()
|
1413
|
{
|
1414
|
return handleGetCatalogRequest(null, null, null, false);
|
1415
|
}
|
1416
|
|
1417
|
/**
|
1418
|
* Sends the contents of the xml_catalog table encoded in xml
|
1419
|
* The xml format is:
|
1420
|
* <!ELEMENT xml_catalog (row*)>
|
1421
|
* <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
|
1422
|
* system_id)>
|
1423
|
* All of the sub elements of row are #PCDATA
|
1424
|
|
1425
|
* If printFlag == false then do not print to out.
|
1426
|
*/
|
1427
|
private static String handleGetCatalogRequest(PrintWriter out,
|
1428
|
Hashtable params,
|
1429
|
HttpServletResponse response,
|
1430
|
boolean printFlag)
|
1431
|
{
|
1432
|
DBConnection dbConn = null;
|
1433
|
int serialNumber = -1;
|
1434
|
PreparedStatement pstmt = null;
|
1435
|
try
|
1436
|
{
|
1437
|
/*conn = MetacatReplication.getDBConnection("MetacatReplication." +
|
1438
|
"handleGetCatalogRequest");*/
|
1439
|
dbConn=DBConnectionPool.
|
1440
|
getDBConnection("MetacatReplication.handleGetCatalogRequest");
|
1441
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
1442
|
pstmt = dbConn.prepareStatement("select entry_type, " +
|
1443
|
"source_doctype, target_doctype, public_id, " +
|
1444
|
"system_id from xml_catalog");
|
1445
|
pstmt.execute();
|
1446
|
ResultSet rs = pstmt.getResultSet();
|
1447
|
boolean tablehasrows = rs.next();
|
1448
|
StringBuffer sb = new StringBuffer();
|
1449
|
sb.append("<?xml version=\"1.0\"?><xml_catalog>");
|
1450
|
while(tablehasrows)
|
1451
|
{
|
1452
|
sb.append("<row><entry_type>").append(rs.getString(1));
|
1453
|
sb.append("</entry_type><source_doctype>").append(rs.getString(2));
|
1454
|
sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
|
1455
|
sb.append("</target_doctype><public_id>").append(rs.getString(4));
|
1456
|
sb.append("</public_id><system_id>").append(rs.getString(5));
|
1457
|
sb.append("</system_id></row>");
|
1458
|
|
1459
|
tablehasrows = rs.next();
|
1460
|
}
|
1461
|
sb.append("</xml_catalog>");
|
1462
|
//conn.close();
|
1463
|
if(printFlag)
|
1464
|
{
|
1465
|
response.setContentType("text/xml");
|
1466
|
out.println(sb.toString());
|
1467
|
}
|
1468
|
pstmt.close();
|
1469
|
return sb.toString();
|
1470
|
}
|
1471
|
catch(Exception e)
|
1472
|
{
|
1473
|
|
1474
|
logMetacat.error("error in MetacatReplication.handleGetCatalogRequest:"+
|
1475
|
e.getMessage());
|
1476
|
e.printStackTrace(System.out);
|
1477
|
if(printFlag)
|
1478
|
{
|
1479
|
out.println("<error>"+e.getMessage()+"</error>");
|
1480
|
}
|
1481
|
}
|
1482
|
finally
|
1483
|
{
|
1484
|
try
|
1485
|
{
|
1486
|
pstmt.close();
|
1487
|
}//try
|
1488
|
catch (SQLException ee)
|
1489
|
{
|
1490
|
logMetacat.error("Error in MetacatReplication.handleGetCatalogRequest: "
|
1491
|
+ee.getMessage());
|
1492
|
}//catch
|
1493
|
finally
|
1494
|
{
|
1495
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
1496
|
}//finally
|
1497
|
}//finally
|
1498
|
|
1499
|
return null;
|
1500
|
}
|
1501
|
|
1502
|
/**
|
1503
|
* Sends the current system date to the remote server. Using this action
|
1504
|
* for replication gets rid of any problems with syncronizing clocks
|
1505
|
* because a time specific to a document is always kept on its home server.
|
1506
|
*/
|
1507
|
private void handleGetTimeRequest(PrintWriter out, Hashtable params,
|
1508
|
HttpServletResponse response)
|
1509
|
{
|
1510
|
SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
|
1511
|
java.util.Date localtime = new java.util.Date();
|
1512
|
String dateString = formatter.format(localtime);
|
1513
|
response.setContentType("text/xml");
|
1514
|
|
1515
|
out.println("<timestamp>" + dateString + "</timestamp>");
|
1516
|
}
|
1517
|
|
1518
|
/**
|
1519
|
* this method handles the timeout for a file lock. when a lock is
|
1520
|
* granted it is granted for 30 seconds. When this thread runs out
|
1521
|
* it deletes the docid from the queue, thus eliminating the lock.
|
1522
|
*/
|
1523
|
public void run()
|
1524
|
{
|
1525
|
try
|
1526
|
{
|
1527
|
logMetacat.info("thread started for docid: " +
|
1528
|
(String)fileLocks.elementAt(0));
|
1529
|
|
1530
|
Thread.sleep(30000); //the lock will expire in 30 seconds
|
1531
|
logMetacat.info("thread for docid: " +
|
1532
|
(String)fileLocks.elementAt(fileLocks.size() - 1) +
|
1533
|
" exiting.");
|
1534
|
|
1535
|
fileLocks.remove(fileLocks.size() - 1);
|
1536
|
//fileLocks is treated as a FIFO queue. If there are more than one lock
|
1537
|
//in the vector, the first one inserted will be removed.
|
1538
|
}
|
1539
|
catch(Exception e)
|
1540
|
{
|
1541
|
logMetacat.error("error in file lock thread from " +
|
1542
|
"MetacatReplication.run: " + e.getMessage());
|
1543
|
}
|
1544
|
}
|
1545
|
|
1546
|
/**
|
1547
|
* Returns the name of a server given a serverCode
|
1548
|
* @param serverCode the serverid of the server
|
1549
|
* @return the servername or null if the specified serverCode does not
|
1550
|
* exist.
|
1551
|
*/
|
1552
|
public static String getServerNameForServerCode(int serverCode)
|
1553
|
{
|
1554
|
//System.out.println("serverid: " + serverCode);
|
1555
|
DBConnection dbConn = null;
|
1556
|
int serialNumber = -1;
|
1557
|
PreparedStatement pstmt = null;
|
1558
|
try
|
1559
|
{
|
1560
|
dbConn=DBConnectionPool.
|
1561
|
getDBConnection("MetacatReplication.getServer");
|
1562
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
1563
|
String sql = new String("select server from " +
|
1564
|
"xml_replication where serverid = " +
|
1565
|
serverCode);
|
1566
|
pstmt = dbConn.prepareStatement(sql);
|
1567
|
//System.out.println("getserver sql: " + sql);
|
1568
|
pstmt.execute();
|
1569
|
ResultSet rs = pstmt.getResultSet();
|
1570
|
boolean tablehasrows = rs.next();
|
1571
|
if(tablehasrows)
|
1572
|
{
|
1573
|
//System.out.println("server: " + rs.getString(1));
|
1574
|
return rs.getString(1);
|
1575
|
}
|
1576
|
|
1577
|
//conn.close();
|
1578
|
}
|
1579
|
catch(Exception e)
|
1580
|
{
|
1581
|
System.out.println("Error in MetacatReplication.getServer: " +
|
1582
|
e.getMessage());
|
1583
|
}
|
1584
|
finally
|
1585
|
{
|
1586
|
try
|
1587
|
{
|
1588
|
pstmt.close();
|
1589
|
}//try
|
1590
|
catch (SQLException ee)
|
1591
|
{
|
1592
|
logMetacat.error("Error in MetacactReplication.getserver: "+
|
1593
|
ee.getMessage());
|
1594
|
}//catch
|
1595
|
finally
|
1596
|
{
|
1597
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
1598
|
}//fianlly
|
1599
|
}//finally
|
1600
|
|
1601
|
|
1602
|
|
1603
|
return null;
|
1604
|
//return null if the server does not exist
|
1605
|
}
|
1606
|
|
1607
|
/**
|
1608
|
* Returns a server code given a server name
|
1609
|
* @param server the name of the server
|
1610
|
* @return integer > 0 representing the code of the server, 0 if the server
|
1611
|
* does not exist.
|
1612
|
*/
|
1613
|
public static int getServerCodeForServerName(String server) throws Exception
|
1614
|
{
|
1615
|
DBConnection dbConn = null;
|
1616
|
int serialNumber = -1;
|
1617
|
PreparedStatement pstmt = null;
|
1618
|
int serverCode = 0;
|
1619
|
|
1620
|
try {
|
1621
|
|
1622
|
//conn = util.openDBConnection();
|
1623
|
dbConn=DBConnectionPool.
|
1624
|
getDBConnection("MetacatReplication.getServerCode");
|
1625
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
1626
|
pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
|
1627
|
"WHERE server LIKE '" + server + "'");
|
1628
|
pstmt.execute();
|
1629
|
ResultSet rs = pstmt.getResultSet();
|
1630
|
boolean tablehasrows = rs.next();
|
1631
|
if ( tablehasrows ) {
|
1632
|
serverCode = rs.getInt(1);
|
1633
|
pstmt.close();
|
1634
|
//conn.close();
|
1635
|
return serverCode;
|
1636
|
}
|
1637
|
|
1638
|
} catch(Exception e) {
|
1639
|
throw e;
|
1640
|
|
1641
|
} finally {
|
1642
|
try
|
1643
|
{
|
1644
|
pstmt.close();
|
1645
|
//conn.close();
|
1646
|
}//try
|
1647
|
catch(Exception ee)
|
1648
|
{
|
1649
|
logMetacat.error("Error in MetacatReplicatio.getServerCode: "
|
1650
|
+ee.getMessage());
|
1651
|
|
1652
|
}//catch
|
1653
|
finally
|
1654
|
{
|
1655
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
1656
|
}//finally
|
1657
|
}//finally
|
1658
|
|
1659
|
return serverCode;
|
1660
|
}
|
1661
|
|
1662
|
/**
|
1663
|
* Method to get a host server information for given docid
|
1664
|
* @param conn a connection to the database
|
1665
|
*/
|
1666
|
public static Hashtable getHomeServerInfoForDocId(String docId)
|
1667
|
{
|
1668
|
Hashtable sl = new Hashtable();
|
1669
|
DBConnection dbConn = null;
|
1670
|
int serialNumber = -1;
|
1671
|
//MetaCatUtil ut=new MetaCatUtil();
|
1672
|
docId=MetaCatUtil.getDocIdFromString(docId);
|
1673
|
PreparedStatement pstmt=null;
|
1674
|
int serverLocation;
|
1675
|
try
|
1676
|
{
|
1677
|
//get conection
|
1678
|
dbConn=DBConnectionPool.
|
1679
|
getDBConnection("ReplicationHandler.getHomeServer");
|
1680
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
1681
|
//get a server location from xml_document table
|
1682
|
pstmt=dbConn.prepareStatement("select server_location from xml_documents "
|
1683
|
+"where docid = ?");
|
1684
|
pstmt.setString(1, docId);
|
1685
|
pstmt.execute();
|
1686
|
ResultSet serverName = pstmt.getResultSet();
|
1687
|
//get a server location
|
1688
|
if(serverName.next())
|
1689
|
{
|
1690
|
serverLocation=serverName.getInt(1);
|
1691
|
pstmt.close();
|
1692
|
}
|
1693
|
else
|
1694
|
{
|
1695
|
pstmt.close();
|
1696
|
//ut.returnConnection(conn);
|
1697
|
return null;
|
1698
|
}
|
1699
|
pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
|
1700
|
"from xml_replication where serverid = ?");
|
1701
|
//increase usage count
|
1702
|
dbConn.increaseUsageCount(1);
|
1703
|
pstmt.setInt(1, serverLocation);
|
1704
|
pstmt.execute();
|
1705
|
ResultSet rs = pstmt.getResultSet();
|
1706
|
boolean tableHasRows = rs.next();
|
1707
|
if (tableHasRows)
|
1708
|
{
|
1709
|
|
1710
|
String server = rs.getString(1);
|
1711
|
String last_checked = rs.getString(2);
|
1712
|
if(!server.equals("localhost"))
|
1713
|
{
|
1714
|
sl.put(server, last_checked);
|
1715
|
}
|
1716
|
|
1717
|
}
|
1718
|
else
|
1719
|
{
|
1720
|
pstmt.close();
|
1721
|
//ut.returnConnection(conn);
|
1722
|
return null;
|
1723
|
}
|
1724
|
pstmt.close();
|
1725
|
}
|
1726
|
catch(Exception e)
|
1727
|
{
|
1728
|
System.out.println("error in replicationHandler.getHomeServer(): " +
|
1729
|
e.getMessage());
|
1730
|
}
|
1731
|
finally
|
1732
|
{
|
1733
|
try
|
1734
|
{
|
1735
|
pstmt.close();
|
1736
|
//ut.returnConnection(conn);
|
1737
|
}
|
1738
|
catch (Exception ee)
|
1739
|
{
|
1740
|
logMetacat.error("Eror irn rplicationHandler.getHomeServer() "+
|
1741
|
"to close pstmt: "+ee.getMessage());
|
1742
|
}
|
1743
|
finally
|
1744
|
{
|
1745
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
1746
|
}
|
1747
|
|
1748
|
}//finally
|
1749
|
return sl;
|
1750
|
}
|
1751
|
|
1752
|
/**
|
1753
|
* Returns a home server location given a accnum
|
1754
|
* @param accNum , given accNum for a document
|
1755
|
*
|
1756
|
*/
|
1757
|
public static int getHomeServerCodeForDocId(String accNum) throws Exception
|
1758
|
{
|
1759
|
DBConnection dbConn = null;
|
1760
|
int serialNumber = -1;
|
1761
|
PreparedStatement pstmt = null;
|
1762
|
int serverCode = 1;
|
1763
|
//MetaCatUtil ut = new MetaCatUtil();
|
1764
|
String docId=MetaCatUtil.getDocIdFromString(accNum);
|
1765
|
|
1766
|
try
|
1767
|
{
|
1768
|
|
1769
|
// Get DBConnection
|
1770
|
dbConn=DBConnectionPool.
|
1771
|
getDBConnection("ReplicationHandler.getServerLocation");
|
1772
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
1773
|
pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
|
1774
|
+ "WHERE docid LIKE '" + docId + "'");
|
1775
|
pstmt.execute();
|
1776
|
ResultSet rs = pstmt.getResultSet();
|
1777
|
boolean tablehasrows = rs.next();
|
1778
|
//If a document is find, return the server location for it
|
1779
|
if ( tablehasrows )
|
1780
|
{
|
1781
|
serverCode = rs.getInt(1);
|
1782
|
pstmt.close();
|
1783
|
//conn.close();
|
1784
|
return serverCode;
|
1785
|
}
|
1786
|
//if couldn't find in xml_documents table, we think server code is 1
|
1787
|
//(this is new document)
|
1788
|
else
|
1789
|
{
|
1790
|
pstmt.close();
|
1791
|
//conn.close();
|
1792
|
return serverCode;
|
1793
|
}
|
1794
|
|
1795
|
}
|
1796
|
catch(Exception e)
|
1797
|
{
|
1798
|
|
1799
|
throw e;
|
1800
|
|
1801
|
}
|
1802
|
finally
|
1803
|
{
|
1804
|
try
|
1805
|
{
|
1806
|
pstmt.close();
|
1807
|
//conn.close();
|
1808
|
|
1809
|
}
|
1810
|
catch(Exception ee)
|
1811
|
{
|
1812
|
logMetacat.error("Erorr in Replication.getServerLocation "+
|
1813
|
"to close pstmt"+ee.getMessage());
|
1814
|
}
|
1815
|
finally
|
1816
|
{
|
1817
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
1818
|
}//finally
|
1819
|
}//finally
|
1820
|
//return serverCode;
|
1821
|
}
|
1822
|
|
1823
|
|
1824
|
|
1825
|
/**
|
1826
|
* This method returns the content of a url
|
1827
|
* @param u the url to return the content from
|
1828
|
* @return a string representing the content of the url
|
1829
|
* @throws java.io.IOException
|
1830
|
*/
|
1831
|
public static String getURLContent(URL u) throws java.io.IOException
|
1832
|
{
|
1833
|
char istreamChar;
|
1834
|
int istreamInt;
|
1835
|
logMetacat.info("Before open the stream"+u.toString());
|
1836
|
InputStream input = u.openStream();
|
1837
|
logMetacat.info("Afetr open the stream"+u.toString());
|
1838
|
InputStreamReader istream = new InputStreamReader(input);
|
1839
|
StringBuffer serverResponse = new StringBuffer();
|
1840
|
while((istreamInt = istream.read()) != -1)
|
1841
|
{
|
1842
|
istreamChar = (char)istreamInt;
|
1843
|
serverResponse.append(istreamChar);
|
1844
|
}
|
1845
|
istream.close();
|
1846
|
input.close();
|
1847
|
|
1848
|
return serverResponse.toString();
|
1849
|
}
|
1850
|
|
1851
|
/**
|
1852
|
* Method for writing replication messages to a log file specified in
|
1853
|
* metacat.properties
|
1854
|
*/
|
1855
|
public static void replLog(String message)
|
1856
|
{
|
1857
|
try
|
1858
|
{
|
1859
|
FileOutputStream fos = new FileOutputStream(
|
1860
|
util.getOption("replicationlog"), true);
|
1861
|
PrintWriter pw = new PrintWriter(fos);
|
1862
|
SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
|
1863
|
java.util.Date localtime = new java.util.Date();
|
1864
|
String dateString = formatter.format(localtime);
|
1865
|
dateString += " :: " + message;
|
1866
|
//time stamp each entry
|
1867
|
pw.println(dateString);
|
1868
|
pw.flush();
|
1869
|
}
|
1870
|
catch(Exception e)
|
1871
|
{
|
1872
|
System.out.println("error writing to replication log from " +
|
1873
|
"MetacatReplication.replLog: " + e.getMessage());
|
1874
|
//e.printStackTrace(System.out);
|
1875
|
}
|
1876
|
}
|
1877
|
|
1878
|
/**
|
1879
|
* Method for writing replication messages to a log file specified in
|
1880
|
* metacat.properties
|
1881
|
*/
|
1882
|
public static void replErrorLog(String message)
|
1883
|
{
|
1884
|
try
|
1885
|
{
|
1886
|
FileOutputStream fos = new FileOutputStream(
|
1887
|
util.getOption("replicationerrorlog"), true);
|
1888
|
PrintWriter pw = new PrintWriter(fos);
|
1889
|
SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
|
1890
|
java.util.Date localtime = new java.util.Date();
|
1891
|
String dateString = formatter.format(localtime);
|
1892
|
dateString += " :: " + message;
|
1893
|
//time stamp each entry
|
1894
|
pw.println(dateString);
|
1895
|
pw.flush();
|
1896
|
}
|
1897
|
catch(Exception e)
|
1898
|
{
|
1899
|
System.out.println("error writing to replication log from " +
|
1900
|
"MetacatReplication.replLog: " + e.getMessage());
|
1901
|
//e.printStackTrace(System.out);
|
1902
|
}
|
1903
|
}
|
1904
|
|
1905
|
/**
|
1906
|
* Returns true if the replicate field for server in xml_replication is 1.
|
1907
|
* Returns false otherwise
|
1908
|
*/
|
1909
|
public static boolean replToServer(String server)
|
1910
|
{
|
1911
|
DBConnection dbConn = null;
|
1912
|
int serialNumber = -1;
|
1913
|
PreparedStatement pstmt = null;
|
1914
|
try
|
1915
|
{
|
1916
|
dbConn=DBConnectionPool.
|
1917
|
getDBConnection("MetacatReplication.repltoServer");
|
1918
|
serialNumber=dbConn.getCheckOutSerialNumber();
|
1919
|
pstmt = dbConn.prepareStatement("select replicate from " +
|
1920
|
"xml_replication where server like '" +
|
1921
|
server + "'");
|
1922
|
pstmt.execute();
|
1923
|
ResultSet rs = pstmt.getResultSet();
|
1924
|
boolean tablehasrows = rs.next();
|
1925
|
if(tablehasrows)
|
1926
|
{
|
1927
|
int i = rs.getInt(1);
|
1928
|
if(i == 1)
|
1929
|
{
|
1930
|
pstmt.close();
|
1931
|
//conn.close();
|
1932
|
return true;
|
1933
|
}
|
1934
|
else
|
1935
|
{
|
1936
|
pstmt.close();
|
1937
|
//conn.close();
|
1938
|
return false;
|
1939
|
}
|
1940
|
}
|
1941
|
}
|
1942
|
catch(Exception e)
|
1943
|
{
|
1944
|
System.out.println("error in MetacatReplication.replToServer: " +
|
1945
|
e.getMessage());
|
1946
|
}
|
1947
|
finally
|
1948
|
{
|
1949
|
try
|
1950
|
{
|
1951
|
pstmt.close();
|
1952
|
//conn.close();
|
1953
|
}//try
|
1954
|
catch(Exception ee)
|
1955
|
{
|
1956
|
logMetacat.error("Error in MetacatReplication.replToServer: "
|
1957
|
+ee.getMessage());
|
1958
|
}//catch
|
1959
|
finally
|
1960
|
{
|
1961
|
DBConnectionPool.returnDBConnection(dbConn, serialNumber);
|
1962
|
}//finally
|
1963
|
}//finally
|
1964
|
return false;
|
1965
|
//the default if this server does not exist is to not replicate to it.
|
1966
|
}
|
1967
|
|
1968
|
|
1969
|
}
|