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: daigle $'
9
 *     '$Date: 2008-07-15 09:58:15 -0700 (Tue, 15 Jul 2008) $'
10
 * '$Revision: 4123 $'
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;
28

    
29
import java.util.*;
30
import java.util.Date;
31
import java.io.*;
32
import java.sql.*;
33
import java.net.*;
34
import java.text.*;
35

    
36
import javax.servlet.*;
37
import javax.servlet.http.*;
38

    
39
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
40
import edu.ucsb.nceas.metacat.service.PropertyService;
41
import edu.ucsb.nceas.metacat.service.SessionService;
42
import edu.ucsb.nceas.metacat.util.LDAPUtil;
43
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
44
import edu.ucsb.nceas.metacat.util.SessionData;
45
import edu.ucsb.nceas.metacat.util.SystemUtil;
46
import edu.ucsb.nceas.utilities.GeneralPropertyException;
47
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
48

    
49
import org.apache.log4j.Logger;
50
import org.xml.sax.*;
51

    
52
public class MetacatReplication extends HttpServlet implements Runnable
53
{
54
  private long timeInterval;
55
  private Date firstTime;
56
  private boolean timedReplicationIsOn = false;
57
  Timer replicationDaemon;
58
  private Vector fileLocks = new Vector();
59
  private Thread lockThread = null;
60
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
61
  public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
62
  private static final String TIMEREPLICATION = "timedreplication";
63
  private static final String TIMEREPLICATIONINTERVAl = "timedreplicationinterval";
64
  private static final String FIRSTTIME  = "firsttimedreplication";
65
  private static final int    TIMEINTERVALLIMIT = 7200000;
66
  private static Logger logMetacat = Logger.getLogger(MetacatReplication.class);
67
  public static final String REPLICATIONUSER = "replication";
68

    
69
  /**
70
   * Initialize the servlet by creating appropriate database connections
71
   */
72
  public void init(ServletConfig config) throws ServletException
73
  {
74
     //initialize db connections to handle any update requests
75
    //deltaT = util.getProperty("deltaT");
76
    //the default deltaT can be set from metacat.properties
77
    //create a thread to do the delta-T check but don't execute it yet
78
    replicationDaemon = new Timer(true);
79
    try
80
    {
81
       timedReplicationIsOn = (new Boolean(PropertyService.getProperty(TIMEREPLICATION ).trim())).booleanValue();
82
       logMetacat.info("The timed replication on is"+timedReplicationIsOn);
83
       timeInterval = (new Long(PropertyService.getProperty(TIMEREPLICATIONINTERVAl).trim())).longValue();
84
       logMetacat.warn("The timed replication time Inerval is "+ timeInterval);
85
       String firstTimeStr = PropertyService.getProperty(FIRSTTIME);
86
       logMetacat.warn("first replication time form property is "+firstTimeStr);
87
       firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
88
       logMetacat.warn("After combine current time, the real first time is "
89
                                +firstTime.toString()+" minisec");
90
       // set up time replication if it is on
91
       if (timedReplicationIsOn)
92
       {
93
           replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime, timeInterval);
94
           MetacatReplication.replLog("deltaT handler started with rate=" +
95
                   timeInterval + " mini seconds at " +firstTime.toString());
96
       }
97
    }
98
    catch (Exception e)
99
    {
100
        // the timed replication in Metacat.properties file has problem
101
        // so timed replication is setting to false;
102
        logMetacat.error("Couldn't set up timed replication "+
103
                     " in Metacat replication servlet init because " +
104
                 e.getMessage());
105
        MetacatReplication.replErrorLog("Couldn't set up timed replication "+
106
                " in Metacat replication servlet init because " +
107
                e.getMessage());
108
        timedReplicationIsOn = false;
109
    }
110
    
111
  }
112

    
113
  public void destroy()
114
  {
115
    replicationDaemon.cancel();
116
   
117
  }
118

    
119
  public void doGet (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
  public void doPost(HttpServletRequest request, HttpServletResponse response)
127
                     throws ServletException, IOException
128
  {
129
    // Process the data and send back the response
130
    handleGetOrPost(request, response);
131
  }
132

    
133
  private void handleGetOrPost(HttpServletRequest request,
134
                               HttpServletResponse response)
135
                               throws ServletException, IOException
136
  {
137
    //PrintWriter out = response.getWriter();
138
    //ServletOutputStream outPut = response.getOutputStream();
139
    Hashtable params = new Hashtable();
140
    Enumeration paramlist = request.getParameterNames();
141

    
142

    
143

    
144
// NOT NEEDED - doesn't provide enough security because of possible IP spoofing
145
// REPLACED with running replication comminications over HTTPS
146
//    String requestingServerIP = request.getRemoteAddr();
147
//    InetAddress iaddr = InetAddress.getByName(requestingServerIP);
148
//    String requestingServer = iaddr.getHostName();
149

    
150
    while (paramlist.hasMoreElements()) {
151
      String name = (String)paramlist.nextElement();
152
      String[] value = request.getParameterValues(name);
153
      params.put(name, value);
154
    }
155

    
156
    String action = ((String[])params.get("action"))[0];
157
    String server = null;
158

    
159
    try {
160
      // check if the server is included in the list of replicated servers
161
      if ( !action.equals("servercontrol") &&
162
           !action.equals("stop") &&
163
           !action.equals("start") &&
164
           !action.equals("getall") ) {
165

    
166
        server = ((String[])params.get("server"))[0];
167
        if ( getServerCodeForServerName(server) == 0 ) {
168
          System.out.println("Action \"" + action +
169
                             "\" rejected for server: " + server);
170
          return;
171
        } else {
172
          System.out.println("Action \"" + action +
173
                             "\" accepted for server: " + server);
174
        }
175
      }
176
      else
177
      {
178
          // start, stop, getall and servercontrol need to check
179
          // if user is administor
180
          HttpSession sess = request.getSession(true);
181
          SessionData sessionData = null;
182
          String sess_id = "";
183
          String username = "";
184
          String[] groupnames = {""};
185

    
186
          if (params.containsKey("sessionid")) 
187
          {
188
             sess_id = ((String[]) params.get("sessionid"))[0];
189
             logMetacat.info("in has sessionid "+ sess_id);
190
             if (SessionService.isSessionRegistered(sess_id)) 
191
             {
192
                  logMetacat.info("find the id " + sess_id + " in hash table");
193
                  sessionData = SessionService.getRegisteredSession(sess_id);
194
             }
195
           } 
196
          if (sessionData == null) {
197
        	  sessionData = new SessionData(sess.getId(), 
198
					(String) sess.getAttribute("username"), 
199
					(String[]) sess.getAttribute("groups"),
200
					(String) sess.getAttribute("password"));
201
          }
202
          
203
           username = sessionData.getUserName();
204
           logMetacat.warn("The user name from session is: "+ username);
205
           groupnames = sessionData.getGroupNames();
206
           if (!LDAPUtil.isAdministrator(username, groupnames)) 
207
           {
208
               PrintWriter out = response.getWriter();
209
               out.print("<error>");
210
               out.print("The user \"" + username +
211
                       "\" is not authorized for this action.");
212
               out.print("</error>");
213
               out.close();
214
               logMetacat.warn("The user \"" + username +
215
                       "\" is not authorized for this action: " +action);
216
               replErrorLog("The user \"" + username +
217
                       "\" is not authorized for this action: " +action);
218
               return;
219
           }
220
                        
221
      }// this is final else
222
    } catch (Exception e) {
223
      System.out.println("Error in MetacatReplication.handleGetOrPost: " +
224
                         e.getMessage() );
225
      return;
226
    }
227
    
228
    if ( action.equals("readdata") )
229
    {
230
      OutputStream outStream = response.getOutputStream();
231
      //to get the data file.
232
      handleGetDataFileRequest(outStream, params, response);
233
      outStream.close();
234
    }
235
    else if ( action.equals("forcereplicatedatafile") )
236
    {
237
      //read a specific docid from remote host, and store it into local host
238
      handleForceReplicateDataFileRequest(params, request);
239

    
240
    }
241
    else
242
    {
243
    PrintWriter out = response.getWriter();
244
    if ( action.equals("stop") ) {
245
      //stop the replication server
246
      replicationDaemon.cancel();
247
      replicationDaemon = new Timer(true);
248
      timedReplicationIsOn = false;
249
      try {
250
    	  PropertyService.setProperty(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
251
      } catch (GeneralPropertyException gpe) {
252
    	  logMetacat.warn("Could not set " + TIMEREPLICATION + " property: " + gpe.getMessage());
253
      }
254
      out.println("Replication Handler Stopped");
255
      MetacatReplication.replLog("deltaT handler stopped");
256

    
257

    
258
    } else if ( action.equals("start") ) {
259
       String firstTimeStr = "";
260
      //start the replication server
261
       if ( params.containsKey("rate") ) {
262
        timeInterval = new Long(
263
               new String(((String[])params.get("rate"))[0])).longValue();
264
        if(timeInterval < TIMEINTERVALLIMIT) {
265
            out.println("Replication deltaT rate cannot be less than "+
266
                    TIMEINTERVALLIMIT + " millisecs and system automatically setup the rate to "+TIMEINTERVALLIMIT);
267
            //deltaT<30 is a timing mess!
268
            timeInterval = TIMEINTERVALLIMIT;
269
        }
270
      } else {
271
        timeInterval = TIMEINTERVALLIMIT ;
272
      }
273
      logMetacat.info("New rate is: " + timeInterval + " mini seconds.");
274
      if ( params.containsKey("firsttime"))
275
      {
276
         firstTimeStr = ((String[])params.get("firsttime"))[0];
277
         try
278
         {
279
           firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
280
           logMetacat.info("The first time setting is "+firstTime.toString());
281
         }
282
         catch (Exception e)
283
         {
284
            throw new ServletException(e.getMessage());
285
         }
286
         logMetacat.warn("After combine current time, the real first time is "
287
                                  +firstTime.toString()+" minisec");
288
      }
289
      else
290
      {
291
          MetacatReplication.replErrorLog("You should specify the first time " +
292
                                          "to start a time replication");
293
          logMetacat.warn("You should specify the first time " +
294
                                  "to start a time replication");
295
          return;
296
      }
297
      
298
      timedReplicationIsOn = true;
299
      try {
300
      // save settings to property file
301
      PropertyService.setProperty(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
302
      // note we couldn't use firstTime object because it has date info
303
      // we only need time info such as 10:00 PM
304
      PropertyService.setProperty(FIRSTTIME, firstTimeStr);
305
      PropertyService.setProperty(TIMEREPLICATIONINTERVAl, (new Long(timeInterval)).toString());
306
      } catch (GeneralPropertyException gpe) {
307
    	  logMetacat.warn("Could not set property: " + gpe.getMessage());
308
      }
309
      replicationDaemon.cancel();
310
      replicationDaemon = new Timer(true);
311
      replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime,
312
                                            timeInterval);
313
      out.println("Replication Handler Started");
314
      MetacatReplication.replLog("deltaT handler started with rate=" +
315
                                    timeInterval + " milliseconds at " +firstTime.toString());
316

    
317

    
318
    } else if ( action.equals("getall") ) {
319
      //updates this server exactly once
320
      replicationDaemon.schedule(new ReplicationHandler(), 0);
321
      response.setContentType("text/html");
322
      out.println("<html><body>\"Get All\" Done</body></html>");
323

    
324
    } else if ( action.equals("forcereplicate") ) {
325
      //read a specific docid from remote host, and store it into local host
326
      handleForceReplicateRequest(out, params, response, request);
327

    
328
    } else if ( action.equals(FORCEREPLICATEDELETE) ) {
329
      //read a specific docid from remote host, and store it into local host
330
      handleForceReplicateDeleteRequest(out, params, response, request);
331

    
332
    } else if ( action.equals("update") ) {
333
      //request an update list from the server
334
      handleUpdateRequest(out, params, response);
335

    
336
    } else if ( action.equals("read") ) {
337
      //request a specific document from the server
338
      //note that this could be replaced by a call to metacatServlet
339
      //handleGetDocumentAction().
340
      handleGetDocumentRequest(out, params, response);
341
    } else if ( action.equals("getlock") ) {
342
      handleGetLockRequest(out, params, response);
343

    
344
    } else if ( action.equals("getdocumentinfo") ) {
345
      handleGetDocumentInfoRequest(out, params, response);
346

    
347
    } else if ( action.equals("gettime") ) {
348
      handleGetTimeRequest(out, params, response);
349

    
350
    } else if ( action.equals("getcatalog") ) {
351
      handleGetCatalogRequest(out, params, response, true);
352

    
353
    } else if ( action.equals("servercontrol") ) {
354
      handleServerControlRequest(out, params, response);
355
    } else if ( action.equals("test") ) {
356
      response.setContentType("text/html");
357
      out.println("<html><body>Test successfully</body></html>");
358
    }
359

    
360
    out.close();
361
    }//else
362
  }
363

    
364
  /**
365
   * This method can add, delete and list the servers currently included in
366
   * xml_replication.
367
   * action           subaction            other needed params
368
   * ---------------------------------------------------------
369
   * servercontrol    add                  server
370
   * servercontrol    delete               server
371
   * servercontrol    list
372
   */
373
  private void handleServerControlRequest(PrintWriter out, Hashtable params,
374
                                          HttpServletResponse response)
375
  {
376
    String subaction = ((String[])params.get("subaction"))[0];
377
    DBConnection dbConn = null;
378
    int serialNumber = -1;
379
    PreparedStatement pstmt = null;
380
    String replicate =null;
381
    String server = null;
382
    String dataReplicate = null;
383
    String hub = null;
384
    try {
385
      //conn = util.openDBConnection();
386
      dbConn=DBConnectionPool.
387
               getDBConnection("MetacatReplication.handleServerControlRequest");
388
      serialNumber=dbConn.getCheckOutSerialNumber();
389

    
390
      // add server to server list
391
      if ( subaction.equals("add") ) {
392
        replicate = ((String[])params.get("replicate"))[0];
393
        server = ((String[])params.get("server"))[0];
394

    
395
        //Get data replication value
396
        dataReplicate = ((String[])params.get("datareplicate"))[0];
397
        //Get hub value
398
        hub = ((String[])params.get("hub"))[0];
399

    
400
        /*pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
401
                  "(server, last_checked, replicate, datareplicate, hub) " +
402
                                      "VALUES ('" + server + "', to_date(" +
403
                                      "'01/01/00', 'MM/DD/YY'), '" +
404
                                      replicate +"', '" +dataReplicate+"', '"
405
                                      + hub +"')");*/
406
        pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
407
                  "(server, last_checked, replicate, datareplicate, hub) " +
408
                                      "VALUES ('" + server + "', "+
409
                                      dbAdapter.toDate("01/01/1980", "MM/DD/YYYY")
410
                                      + ", '" +
411
                                      replicate +"', '" +dataReplicate+"', '"
412
                                      + hub +"')");
413

    
414
        pstmt.execute();
415
        pstmt.close();
416
        dbConn.commit();
417
        out.println("Server " + server + " added");
418
        response.setContentType("text/html");
419
        out.println("<html><body><table border=\"1\">");
420
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
421
        out.println("<b>replicate</b></td>");
422
        out.println("<td><b>datareplicate</b></td>");
423
        out.println("<td><b>hub</b></td></tr>");
424
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
425
        //increase dbconnection usage
426
        dbConn.increaseUsageCount(1);
427

    
428
        pstmt.execute();
429
        ResultSet rs = pstmt.getResultSet();
430
        boolean tablehasrows = rs.next();
431
        while(tablehasrows) {
432
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
433
          out.println(rs.getString(3) + "</td><td>");
434
          out.println(rs.getString(4) + "</td><td>");
435
          out.println(rs.getString(5) + "</td><td>");
436
          out.println(rs.getString(6) + "</td></tr>");
437

    
438
          tablehasrows = rs.next();
439
        }
440
        out.println("</table></body></html>");
441

    
442
        // download certificate with the public key on this server
443
        // and import it as a trusted certificate
444
        String certURL = ((String[])params.get("certificate"))[0];
445
        downloadCertificate(certURL);
446

    
447
      // delete server from server list
448
      } else if ( subaction.equals("delete") ) {
449
        server = ((String[])params.get("server"))[0];
450
        pstmt = dbConn.prepareStatement("DELETE FROM xml_replication " +
451
                                      "WHERE server LIKE '" + server + "'");
452
        pstmt.execute();
453
        pstmt.close();
454
        dbConn.commit();
455
        out.println("Server " + server + " deleted");
456
        response.setContentType("text/html");
457
        out.println("<html><body><table border=\"1\">");
458
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
459
        out.println("<b>replicate</b></td>");
460
        out.println("<td><b>datareplicate</b></td>");
461
        out.println("<td><b>hub</b></td></tr>");
462

    
463
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
464
        //increase dbconnection usage
465
        dbConn.increaseUsageCount(1);
466
        pstmt.execute();
467
        ResultSet rs = pstmt.getResultSet();
468
        boolean tablehasrows = rs.next();
469
        while(tablehasrows)
470
        {
471
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
472
          out.println(rs.getString(3) + "</td><td>");
473
          out.println(rs.getString(4) + "</td><td>");
474
          out.println(rs.getString(5) + "</td><td>");
475
          out.println(rs.getString(6) + "</td></tr>");
476
          tablehasrows = rs.next();
477
        }
478
        out.println("</table></body></html>");
479

    
480
      // list servers in server list
481
      } else if ( subaction.equals("list") ) {
482
        response.setContentType("text/html");
483
        out.println("<html><body><table border=\"1\">");
484
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
485
        out.println("<b>replicate</b></td>");
486
        out.println("<td><b>datareplicate</b></td>");
487
        out.println("<td><b>hub</b></td></tr>");
488
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
489
        pstmt.execute();
490
        ResultSet rs = pstmt.getResultSet();
491
        boolean tablehasrows = rs.next();
492
        while(tablehasrows) {
493
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
494
          out.println(rs.getString(3) + "</td><td>");
495
          out.println(rs.getString(4) + "</td><td>");
496
          out.println(rs.getString(5) + "</td><td>");
497
          out.println(rs.getString(6) + "</td></tr>");
498
          tablehasrows = rs.next();
499
        }
500
        out.println("</table></body></html>");
501
      }
502
      else
503
      {
504

    
505
        out.println("<error>Unkonwn subaction</error>");
506

    
507
      }
508
      pstmt.close();
509
      //conn.close();
510

    
511
    } catch(Exception e) {
512
      System.out.println("Error in " +
513
                         "MetacatReplication.handleServerControlRequest " +
514
                         e.getMessage());
515
      e.printStackTrace(System.out);
516
    }
517
    finally
518
    {
519
      try
520
      {
521
        pstmt.close();
522
      }//try
523
      catch (SQLException ee)
524
      {
525
        logMetacat.error("Error in " +
526
                "MetacatReplication.handleServerControlRequest to close pstmt "
527
                 + ee.getMessage());
528
      }//catch
529
      finally
530
      {
531
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
532
      }//finally
533
    }//finally
534

    
535
  }
536

    
537
   	// download certificate with the public key from certURL and
538
	// upload it onto this server; it then must be imported as a
539
	// trusted certificate
540
	private void downloadCertificate(String certURL) throws FileNotFoundException,
541
			IOException, MalformedURLException, PropertyNotFoundException {
542
		
543
		// the path to be uploaded to
544
		String certPath = PropertyService.getProperty("application.tomcatDir")
545
				+ "/webapps/" + PropertyService.getProperty("application.context"); 
546

    
547
		// get filename from the URL of the certificate
548
		String filename = certURL;
549
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
550
		if (slash > -1) {
551
			filename = filename.substring(slash + 1);
552
		}
553

    
554
		// open file output strem to write the input into it
555
		File f = new File(certPath, filename);
556
		synchronized (f) {
557
			try {
558
				if (f.exists()) {
559
					throw new IOException("File already exist: " + f.getCanonicalFile());
560
					// if ( f.exists() && !f.canWrite() ) {
561
					// throw new IOException("Not writable: " +
562
					// f.getCanonicalFile());
563
				}
564
			} catch (SecurityException se) {
565
				// if a security manager exists,
566
				// its checkRead method is called for f.exist()
567
				// or checkWrite method is called for f.canWrite()
568
				throw se;
569
			}
570

    
571
			// create a buffered byte output stream
572
			// that uses a default-sized output buffer
573
			FileOutputStream fos = new FileOutputStream(f);
574
			BufferedOutputStream out = new BufferedOutputStream(fos);
575

    
576
			// this should be http url
577
			URL url = new URL(certURL);
578
			BufferedInputStream bis = null;
579
			try {
580
				bis = new BufferedInputStream(url.openStream());
581
				byte[] buf = new byte[4 * 1024]; // 4K buffer
582
				int b = bis.read(buf);
583
				while (b != -1) {
584
					out.write(buf, 0, b);
585
					b = bis.read(buf);
586
				}
587
			} finally {
588
				if (bis != null)
589
					bis.close();
590
			}
591
			// the input and the output streams must be closed
592
			bis.close();
593
			out.flush();
594
			out.close();
595
			fos.close();
596
		} // end of synchronized(f)
597
	}
598

    
599
  /**
600
	 * when a forcereplication request comes in, local host sends a read request
601
	 * to the requesting server (remote server) for the specified docid. Then
602
	 * store it in local database.
603
	 */
604
  private void handleForceReplicateRequest(PrintWriter out, Hashtable params,
605
                                           HttpServletResponse response, HttpServletRequest request)
606
  {
607
    String server = ((String[])params.get("server"))[0]; // the server that
608
    String docid = ((String[])params.get("docid"))[0]; // sent the document
609
    String dbaction = "UPDATE"; // the default action is UPDATE
610
    boolean override = false;
611
    int serverCode = 1;
612
    DBConnection dbConn = null;
613
    int serialNumber = -1;
614

    
615
    try {
616
      //if the url contains a dbaction then the default action is overridden
617
      if(params.containsKey("dbaction")) {
618
        dbaction = ((String[])params.get("dbaction"))[0];
619
        //serverCode = MetacatReplication.getServerCode(server);
620
        //override = true; //we are now overriding the default action
621
      }
622
      MetacatReplication.replLog("force replication request from " + server);
623
      logMetacat.info("Force replication request from: "+ server);
624
      logMetacat.info("Force replication docid: "+docid);
625
      logMetacat.info("Force replication action: "+dbaction);
626
      // sending back read request to remote server
627
      URL u = new URL("https://" + server + "?server="
628
                +MetaCatUtil.getLocalReplicationServerName()
629
                +"&action=read&docid=" + docid);
630
      String xmldoc = MetacatReplication.getURLContent(u);
631

    
632
      // get the document info from server
633
      URL docinfourl = new URL("https://" + server +
634
                               "?server="+MetaCatUtil.getLocalReplicationServerName()
635
                               +"&action=getdocumentinfo&docid=" + docid);
636

    
637
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
638

    
639
      //dih is the parser for the docinfo xml format
640
      DocInfoHandler dih = new DocInfoHandler();
641
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
642
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
643
      Hashtable docinfoHash = dih.getDocInfo();
644

    
645
      // Get user owner of this docid
646
      String user = (String)docinfoHash.get("user_owner");
647
      // Get home server of this docid
648
      String homeServer=(String)docinfoHash.get("home_server");
649
      String createdDate = (String)docinfoHash.get("date_created");
650
      String updatedDate = (String)docinfoHash.get("date_updated");
651
      logMetacat.info("homeServer: "+homeServer);
652
      // Get Document type
653
      String docType = (String)docinfoHash.get("doctype");
654
      logMetacat.info("docType: "+docType);
655
      String parserBase = null;
656
      // this for eml2 and we need user eml2 parser
657
      if (docType != null &&
658
          (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
659
      {
660
         logMetacat.warn("This is an eml200 document!");
661
         parserBase = DocumentImpl.EML200;
662
      }
663
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
664
      {
665
         logMetacat.warn("This is an eml2.0.1 document!");
666
         parserBase = DocumentImpl.EML200;
667
      }
668
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
669
      {
670
         logMetacat.warn("This is an eml2.1.0 document!");
671
         parserBase = DocumentImpl.EML210;
672
      }
673
      logMetacat.warn("The parserBase is: "+parserBase);
674

    
675
      // Get DBConnection from pool
676
      dbConn=DBConnectionPool.
677
              getDBConnection("MetacatReplication.handleForceReplicateRequest");
678
      serialNumber=dbConn.getCheckOutSerialNumber();
679
      // write the document to local database
680
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
681
      wrapper.writeReplication(dbConn, new StringReader(xmldoc), null, null,
682
                               dbaction, docid, user, null, homeServer, 
683
                               server, createdDate, updatedDate);
684

    
685
      MetacatReplication.replLog("document " + docid + " added to DB with " +
686
                                 "action " + dbaction);
687
      EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, dbaction);
688
    }//try
689
    catch(Exception e)
690
    {
691
      MetacatReplication.replErrorLog("document " + docid +
692
                                      " failed to added to DB with " +
693
                                      "action " + dbaction + " because "+
694
                                       e.getMessage());
695
      logMetacat.error("ERROR in MetacatReplication.handleForceReplicate" +
696
                         "Request(): " + e.getMessage());
697

    
698
    }//catch
699
    finally
700
    {
701
      // Return the checked out DBConnection
702
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
703
    }//finally
704
  }
705

    
706
/*
707
 * when a forcereplication delete request comes in, local host will delete this
708
 * document
709
 */
710
private void handleForceReplicateDeleteRequest(PrintWriter out, Hashtable params,
711
                                         HttpServletResponse response, HttpServletRequest request)
712
{
713
  String server = ((String[])params.get("server"))[0]; // the server that
714
  String docid = ((String[])params.get("docid"))[0]; // sent the document
715
  try
716
  {
717
    MetacatReplication.replLog("force replication delete request from " + server);
718
    MetacatReplication.replLog("force replication delete docid " + docid);
719
    logMetacat.info("Force replication delete request from: "+ server);
720
    logMetacat.info("Force replication delete docid: "+docid);
721
    DocumentImpl.delete(docid, null, null, server);
722
    MetacatReplication.replLog("document " + docid + " was successfully deleted ");
723
    EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, "delete");
724
    logMetacat.info("document " + docid + " was successfully deleted ");
725
  }
726
  catch(Exception e)
727
  {
728
    MetacatReplication.replErrorLog("document " + docid +
729
                                    " failed to delete because "+
730
                                     e.getMessage());
731
    logMetacat.error("ERROR in MetacatReplication.handleForceDeleteReplicate" +
732
                       "Request(): " + e.getMessage());
733

    
734
  }//catch
735

    
736
}
737

    
738

    
739
  /**
740
   * when a forcereplication data file request comes in, local host sends a
741
   * readdata request to the requesting server (remote server) for the specified
742
   * docid. Then store it in local database and file system
743
   */
744
  private void handleForceReplicateDataFileRequest(Hashtable params, HttpServletRequest request)
745
  {
746

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

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

    
768
    try
769
    {
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
      {
775
        dbaction = ((String[])params.get("dbaction"))[0];
776
      }
777
      else//default value is update
778
      {
779
        dbaction = "update";
780
      }
781

    
782
      MetacatReplication.replLog("force replication request from " + server);
783
      logMetacat.info("Force replication request from: "+ server);
784
      logMetacat.info("Force replication docid: "+docid);
785
      logMetacat.info("Force replication action: "+dbaction);
786
      // get the document info from server
787
      URL docinfourl = new URL("https://" + server +
788
                               "?server="+MetaCatUtil.getLocalReplicationServerName()
789
                               +"&action=getdocumentinfo&docid=" + docid);
790

    
791
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
792

    
793
      //dih is the parser for the docinfo xml format
794
      DocInfoHandler dih = new DocInfoHandler();
795
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
796
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
797
      Hashtable docinfoHash = dih.getDocInfo();
798
      String user = (String)docinfoHash.get("user_owner");
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
      logMetacat.info("docHomeServer of datafile: "+docHomeServer);
810

    
811

    
812

    
813
      //if action is delete, we don't delete the data file. Just archieve
814
      //the xml_documents
815
      /*if (dbaction.equals("delete"))
816
      {
817
        //conn = util.getConnection();
818
        DocumentImpl.delete(docid,user,null);
819
        //util.returnConnection(conn);
820
      }*/
821
      //To data file insert or update is same
822
      if (dbaction.equals("insert")||dbaction.equals("update"))
823
      {
824
        //Get data file and store it into local file system.
825
        // sending back readdata request to server
826
        URL url = new URL("https://" + server + "?server="
827
                +MetaCatUtil.getLocalReplicationServerName()
828
                +"&action=readdata&docid=" + docid);
829
        String datafilePath = PropertyService.getProperty("application.datafilepath");
830
        //register data file into xml_documents table and wite data file
831
        //into file system
832
        DocumentImpl.writeDataFileInReplication(url.openStream(), datafilePath,
833
                            docName, docType, docid, user,docHomeServer,server, 
834
                            DocumentImpl.DOCUMENTTABLE, false, createdDate, updatedDate);
835
                            //false means non-timed replication
836
        MetacatReplication.replLog("datafile " + docid + " added to DB with " +
837
                "action " + dbaction);
838
        EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, dbaction);
839
     }
840

    
841

    
842

    
843
    
844
    }
845
    catch(Exception e)
846
    {
847

    
848
      MetacatReplication.replErrorLog("Datafile " + docid +
849
                                      " failed to added to DB with " +
850
                                      "action " + dbaction + " because "+
851
                                       e.getMessage());
852
      logMetacat.error
853
              ("ERROR in MetacatReplication.handleForceDataFileReplicate" +
854
                         "Request(): " + e.getMessage());
855
    }
856
  }
857
  /**
858
   * Grants or denies a lock to a requesting host.
859
   * The servlet parameters of interrest are:
860
   * docid: the docid of the file the lock is being requested for
861
   * currentdate: the timestamp of the document on the remote server
862
   *
863
   */
864
  private void handleGetLockRequest(PrintWriter out, Hashtable params,
865
                                    HttpServletResponse response)
866
  {
867

    
868
    try
869
    {
870

    
871
      String docid = ((String[])params.get("docid"))[0];
872
      String remoteRev = ((String[])params.get("updaterev"))[0];
873
      DocumentImpl requestDoc = new DocumentImpl(docid);
874
      MetacatReplication.replLog("lock request for " + docid);
875
      int localRevInt = requestDoc.getRev();
876
      int remoteRevInt = Integer.parseInt(remoteRev);
877

    
878
      if(remoteRevInt >= localRevInt)
879
      {
880
        if(!fileLocks.contains(docid))
881
        { //grant the lock if it is not already locked
882
          fileLocks.add(0, docid); //insert at the beginning of the queue Vector
883
          //send a message back to the the remote host authorizing the insert
884
          out.println("<lockgranted><docid>" +docid+ "</docid></lockgranted>");
885
          lockThread = new Thread(this);
886
          lockThread.setPriority(Thread.MIN_PRIORITY);
887
          lockThread.start();
888
          MetacatReplication.replLog("lock granted for " + docid);
889
        }
890
        else
891
        { //deny the lock
892
          out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
893
          MetacatReplication.replLog("lock denied for " + docid +
894
                                     "reason: file already locked");
895
        }
896
      }
897
      else
898
      {//deny the lock.
899
        out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
900
        MetacatReplication.replLog("lock denied for " + docid +
901
                                   "reason: client has outdated file");
902
      }
903
      //conn.close();
904
    }
905
    catch(Exception e)
906
    {
907
      System.out.println("error requesting file lock from MetacatReplication." +
908
                         "handleGetLockRequest: " + e.getMessage());
909
      e.printStackTrace(System.out);
910
    }
911
  }
912

    
913
  /**
914
   * Sends all of the xml_documents information encoded in xml to a requestor
915
   * the format is:
916
   * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
917
   *                  user_updated, home_server, public_access, rev)/>
918
   * all of the subelements of document info are #PCDATA
919
   */
920
  private void handleGetDocumentInfoRequest(PrintWriter out, Hashtable params,
921
                                        HttpServletResponse response)
922
  {
923
    String docid = ((String[])(params.get("docid")))[0];
924
    StringBuffer sb = new StringBuffer();
925

    
926
    try
927
    {
928

    
929
      DocumentImpl doc = new DocumentImpl(docid);
930
      sb.append("<documentinfo><docid>").append(docid);
931
      sb.append("</docid><docname>").append(doc.getDocname());
932
      sb.append("</docname><doctype>").append(doc.getDoctype());
933
      sb.append("</doctype>");
934
      sb.append("<user_owner>").append(doc.getUserowner());
935
      sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
936
      sb.append("</user_updated>");
937
      sb.append("<date_created>");
938
      sb.append(doc.getCreateDate());
939
      sb.append("</date_created>");
940
      sb.append("<date_updated>");
941
      sb.append(doc.getUpdateDate());
942
      sb.append("</date_updated>");
943
      sb.append("<home_server>");
944
      sb.append(doc.getDocHomeServer());
945
      sb.append("</home_server>");
946
      sb.append("<public_access>").append(doc.getPublicaccess());
947
      sb.append("</public_access><rev>").append(doc.getRev());
948
      sb.append("</rev></documentinfo>");
949
      response.setContentType("text/xml");
950
      out.println(sb.toString());
951

    
952
    }
953
    catch (Exception e)
954
    {
955
      System.out.println("error in " +
956
                         "metacatReplication.handlegetdocumentinforequest: " +
957
                          e.getMessage());
958
    }
959

    
960
  }
961

    
962
  /**
963
   * Sends a datafile to a remote host
964
   */
965
  private void handleGetDataFileRequest(OutputStream outPut,
966
                            Hashtable params, HttpServletResponse response)
967

    
968
  {
969
    // File path for data file
970
    String filepath;
971
    // Request docid
972
    String docId = ((String[])(params.get("docid")))[0];
973
    //check if the doicd is null
974
    if (docId==null)
975
    {
976
      logMetacat.error("Didn't specify docid for replication");
977
      return;
978
    }
979

    
980
    //try to open a https stream to test if the request server's public key
981
    //in the key store, this is security issue
982
    try
983
    {
984
      filepath = PropertyService.getProperty("application.datafilepath");
985
      String server = ((String[])params.get("server"))[0];
986
      URL u = new URL("https://" + server + "?server="
987
                +MetaCatUtil.getLocalReplicationServerName()
988
                +"&action=test");
989
      String test = MetacatReplication.getURLContent(u);
990
      //couldn't pass the test
991
      if (test.indexOf("successfully")==-1)
992
      {
993
        //response.setContentType("text/xml");
994
        //outPut.println("<error>Couldn't pass the trust test</error>");
995
        logMetacat.error("Couldn't pass the trust test");
996
        return;
997
      }
998
    }//try
999
    catch (Exception ee)
1000
    {
1001
      return;
1002
    }//catch
1003

    
1004
    if(!filepath.endsWith("/"))
1005
    {
1006
          filepath += "/";
1007
    }
1008
    // Get file aboslute file name
1009
    String filename = filepath + docId;
1010

    
1011
    //MIME type
1012
    String contentType = null;
1013
    if (filename.endsWith(".xml"))
1014
    {
1015
        contentType="text/xml";
1016
    }
1017
    else if (filename.endsWith(".css"))
1018
    {
1019
        contentType="text/css";
1020
    }
1021
    else if (filename.endsWith(".dtd"))
1022
    {
1023
        contentType="text/plain";
1024
    }
1025
    else if (filename.endsWith(".xsd"))
1026
    {
1027
        contentType="text/xml";
1028
    }
1029
    else if (filename.endsWith("/"))
1030
    {
1031
        contentType="text/html";
1032
    }
1033
    else
1034
    {
1035
        File f = new File(filename);
1036
        if ( f.isDirectory() )
1037
        {
1038
           contentType="text/html";
1039
        }
1040
        else
1041
        {
1042
           contentType="application/octet-stream";
1043
        }
1044
     }
1045

    
1046
   // Set the mime type
1047
   response.setContentType(contentType);
1048

    
1049
   // Get the content of the file
1050
   FileInputStream fin = null;
1051
   try
1052
   {
1053
      // FileInputStream to metacat
1054
      fin = new FileInputStream(filename);
1055
      // 4K buffer
1056
      byte[] buf = new byte[4 * 1024];
1057
      // Read data from file input stream to byte array
1058
      int b = fin.read(buf);
1059
      // Write to outStream from byte array
1060
      while (b != -1)
1061
      {
1062
        outPut.write(buf, 0, b);
1063
        b = fin.read(buf);
1064
      }
1065
      // close file input stream
1066
      fin.close();
1067

    
1068
   }//try
1069
   catch(Exception e)
1070
   {
1071
      System.out.println("error getting data file from MetacatReplication." +
1072
                         "handlGetDataFileRequest " + e.getMessage());
1073
      e.printStackTrace(System.out);
1074
   }//catch
1075

    
1076
}
1077

    
1078

    
1079
  /**
1080
   * Sends a document to a remote host
1081
   */
1082
  private void handleGetDocumentRequest(PrintWriter out, Hashtable params,
1083
                                        HttpServletResponse response)
1084
  {
1085

    
1086
    try
1087
    {
1088
      //try to open a https stream to test if the request server's public key
1089
      //in the key store, this is security issue
1090
      String server = ((String[])params.get("server"))[0];
1091
      URL u = new URL("https://" + server + "?server="
1092
                +MetaCatUtil.getLocalReplicationServerName()
1093
                +"&action=test");
1094
      String test = MetacatReplication.getURLContent(u);
1095
      //couldn't pass the test
1096
      if (test.indexOf("successfully")==-1)
1097
      {
1098
        response.setContentType("text/xml");
1099
        out.println("<error>Couldn't pass the trust test "+test+" </error>");
1100
        out.close();
1101
        return;
1102
      }
1103

    
1104
      String docid = ((String[])(params.get("docid")))[0];
1105

    
1106
      DocumentImpl di = new DocumentImpl(docid);
1107
      response.setContentType("text/xml");
1108
      out.print(di.toString(null, null, true));
1109

    
1110
      MetacatReplication.replLog("document " + docid + " sent");
1111

    
1112
    }
1113
    catch(Exception e)
1114
    {
1115
      logMetacat.error("error getting document from MetacatReplication."
1116
                          +"handlGetDocumentRequest " + e.getMessage());
1117
      //e.printStackTrace(System.out);
1118
      response.setContentType("text/xml");
1119
      out.println("<error>"+e.getMessage()+"</error>");
1120
    }
1121

    
1122
  }
1123

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

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

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

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

    
1186

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

    
1198
      // Store the sql command
1199
      StringBuffer docsql = new StringBuffer();
1200
      StringBuffer revisionSql = new StringBuffer();
1201
      // Stroe the docid list
1202
      StringBuffer doclist = new StringBuffer();
1203
      // Store the deleted docid list
1204
      StringBuffer delsql = new StringBuffer();
1205
      // Store the data set file
1206
      Vector packageFiles = new Vector();
1207

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

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

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

    
1242

    
1243

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

    
1329
      pstmt = dbConn.prepareStatement(delsql.toString());
1330
      //usage count should increas 1
1331
      dbConn.increaseUsageCount(1);
1332

    
1333
      pstmt.execute();
1334
      rs = pstmt.getResultSet();
1335
      tablehasrows = rs.next();
1336
      while(tablehasrows)
1337
      { //handle the deleted documents
1338
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1339
        doclist.append("</docid><rev></rev></deletedDocument>");
1340
        //note that rev is always empty for deleted docs
1341
        tablehasrows = rs.next();
1342
      }
1343

    
1344
      //now we can put the package files into the xml results
1345
      for(int i=0; i<packageFiles.size(); i++)
1346
      {
1347
        Vector v = (Vector)packageFiles.elementAt(i);
1348
        doclist.append("<updatedDocument>");
1349
        doclist.append("<docid>").append((String)v.elementAt(0));
1350
        doclist.append("</docid><rev>");
1351
        doclist.append(((Integer)v.elementAt(1)).intValue());
1352
        doclist.append("</rev>");
1353
        doclist.append("</updatedDocument>");
1354
      }
1355
      // add revision doc list  
1356
      doclist.append(prepareRevisionDoc(dbConn,revisionSql.toString(),replicateData));
1357
        
1358
      doclist.append("</updates></replication>");
1359
      logMetacat.info("doclist: " + doclist.toString());
1360
      pstmt.close();
1361
      //conn.close();
1362
      response.setContentType("text/xml");
1363
      out.println(doclist.toString());
1364

    
1365
    }
1366
    catch(Exception e)
1367
    {
1368
      logMetacat.error("error in MetacatReplication." +
1369
                         "handleupdaterequest: " + e.getMessage());
1370
      //e.printStackTrace(System.out);
1371
      response.setContentType("text/xml");
1372
      out.println("<error>"+e.getMessage()+"</error>");
1373
    }
1374
    finally
1375
    {
1376
      try
1377
      {
1378
        pstmt.close();
1379
      }//try
1380
      catch (SQLException ee)
1381
      {
1382
        logMetacat.error("Error in MetacatReplication." +
1383
                "handleUpdaterequest to close pstmt: "+ee.getMessage());
1384
      }//catch
1385
      finally
1386
      {
1387
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1388
      }//finally
1389
    }//finally
1390

    
1391
  }//handlUpdateRequest
1392
  
1393
  /*
1394
   * This method will get the xml string for document in xml_revision
1395
   * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1396
   */
1397
  private String prepareRevisionDoc(DBConnection dbConn, String revSql, 
1398
                            boolean replicateData) throws Exception
1399
  {
1400
      logMetacat.warn("The revision document sql is "+ revSql);
1401
      StringBuffer revDocList = new StringBuffer();
1402
      PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1403
      //usage count should increas 1
1404
      dbConn.increaseUsageCount(1);
1405

    
1406
      pstmt.execute();
1407
      ResultSet rs = pstmt.getResultSet();
1408
      boolean tablehasrows = rs.next();
1409
      while(tablehasrows)
1410
      {
1411
        String recordDoctype = rs.getString(3);
1412
        
1413
        //If this is data file and it isn't configured to replicate data
1414
        if (recordDoctype.equals("BIN") && !replicateData)
1415
        {  
1416
            // do nothing
1417
            continue;
1418
        }
1419
        else
1420
        {  
1421
            
1422
            revDocList.append("<revisionDocument>");
1423
            revDocList.append("<docid>").append(rs.getString(1));
1424
            revDocList.append("</docid><rev>").append(rs.getInt(2));
1425
            revDocList.append("</rev>");
1426
            // data file
1427
            if (recordDoctype.equals("BIN"))
1428
            {
1429
                revDocList.append("<datafile>");
1430
                revDocList.append(PropertyService.getProperty("datafileflag"));
1431
                revDocList.append("</datafile>");
1432
            }
1433
            revDocList.append("</revisionDocument>");
1434
        
1435
         }//else
1436
         tablehasrows = rs.next();
1437
      }
1438
      //System.out.println("The revision list is"+ revDocList.toString());
1439
      return revDocList.toString();
1440
  }
1441

    
1442
  /**
1443
   * Returns the xml_catalog table encoded in xml
1444
   */
1445
  public static String getCatalogXML()
1446
  {
1447
    return handleGetCatalogRequest(null, null, null, false);
1448
  }
1449

    
1450
  /**
1451
   * Sends the contents of the xml_catalog table encoded in xml
1452
   * The xml format is:
1453
   * <!ELEMENT xml_catalog (row*)>
1454
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1455
   *                system_id)>
1456
   * All of the sub elements of row are #PCDATA
1457

    
1458
   * If printFlag == false then do not print to out.
1459
   */
1460
  private static String handleGetCatalogRequest(PrintWriter out,
1461
                                                Hashtable params,
1462
                                                HttpServletResponse response,
1463
                                                boolean printFlag)
1464
  {
1465
    DBConnection dbConn = null;
1466
    int serialNumber = -1;
1467
    PreparedStatement pstmt = null;
1468
    try
1469
    {
1470
      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1471
                                                "handleGetCatalogRequest");*/
1472
      dbConn=DBConnectionPool.
1473
                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
1474
      serialNumber=dbConn.getCheckOutSerialNumber();
1475
      pstmt = dbConn.prepareStatement("select entry_type, " +
1476
                              "source_doctype, target_doctype, public_id, " +
1477
                              "system_id from xml_catalog");
1478
      pstmt.execute();
1479
      ResultSet rs = pstmt.getResultSet();
1480
      boolean tablehasrows = rs.next();
1481
      StringBuffer sb = new StringBuffer();
1482
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1483
      while(tablehasrows)
1484
      {
1485
        sb.append("<row><entry_type>").append(rs.getString(1));
1486
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1487
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1488
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1489
        // system id may not have server url on front.  Add it if not.
1490
        String systemID = rs.getString(5);
1491
        if (!systemID.startsWith("http://")) {
1492
        	systemID = SystemUtil.getContextURL() + systemID;
1493
        }
1494
        sb.append("</public_id><system_id>").append(systemID);
1495
        sb.append("</system_id></row>");
1496

    
1497
        tablehasrows = rs.next();
1498
      }
1499
      sb.append("</xml_catalog>");
1500
      //conn.close();
1501
      if(printFlag)
1502
      {
1503
        response.setContentType("text/xml");
1504
        out.println(sb.toString());
1505
      }
1506
      pstmt.close();
1507
      return sb.toString();
1508
    }
1509
    catch(Exception e)
1510
    {
1511

    
1512
      logMetacat.error("error in MetacatReplication.handleGetCatalogRequest:"+
1513
                          e.getMessage());
1514
      e.printStackTrace(System.out);
1515
      if(printFlag)
1516
      {
1517
        out.println("<error>"+e.getMessage()+"</error>");
1518
      }
1519
    }
1520
    finally
1521
    {
1522
      try
1523
      {
1524
        pstmt.close();
1525
      }//try
1526
      catch (SQLException ee)
1527
      {
1528
        logMetacat.error("Error in MetacatReplication.handleGetCatalogRequest: "
1529
           +ee.getMessage());
1530
      }//catch
1531
      finally
1532
      {
1533
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1534
      }//finally
1535
    }//finally
1536

    
1537
    return null;
1538
  }
1539

    
1540
  /**
1541
   * Sends the current system date to the remote server.  Using this action
1542
   * for replication gets rid of any problems with syncronizing clocks
1543
   * because a time specific to a document is always kept on its home server.
1544
   */
1545
  private void handleGetTimeRequest(PrintWriter out, Hashtable params,
1546
                                    HttpServletResponse response)
1547
  {
1548
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
1549
    java.util.Date localtime = new java.util.Date();
1550
    String dateString = formatter.format(localtime);
1551
    response.setContentType("text/xml");
1552

    
1553
    out.println("<timestamp>" + dateString + "</timestamp>");
1554
  }
1555

    
1556
  /**
1557
   * this method handles the timeout for a file lock.  when a lock is
1558
   * granted it is granted for 30 seconds.  When this thread runs out
1559
   * it deletes the docid from the queue, thus eliminating the lock.
1560
   */
1561
  public void run()
1562
  {
1563
    try
1564
    {
1565
      logMetacat.info("thread started for docid: " +
1566
                               (String)fileLocks.elementAt(0));
1567

    
1568
      Thread.sleep(30000); //the lock will expire in 30 seconds
1569
      logMetacat.info("thread for docid: " +
1570
                             (String)fileLocks.elementAt(fileLocks.size() - 1) +
1571
                              " exiting.");
1572

    
1573
      fileLocks.remove(fileLocks.size() - 1);
1574
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1575
      //in the vector, the first one inserted will be removed.
1576
    }
1577
    catch(Exception e)
1578
    {
1579
      logMetacat.error("error in file lock thread from " +
1580
                                "MetacatReplication.run: " + e.getMessage());
1581
    }
1582
  }
1583

    
1584
  /**
1585
   * Returns the name of a server given a serverCode
1586
   * @param serverCode the serverid of the server
1587
   * @return the servername or null if the specified serverCode does not
1588
   *         exist.
1589
   */
1590
  public static String getServerNameForServerCode(int serverCode)
1591
  {
1592
    //System.out.println("serverid: " + serverCode);
1593
    DBConnection dbConn = null;
1594
    int serialNumber = -1;
1595
    PreparedStatement pstmt = null;
1596
    try
1597
    {
1598
      dbConn=DBConnectionPool.
1599
                  getDBConnection("MetacatReplication.getServer");
1600
      serialNumber=dbConn.getCheckOutSerialNumber();
1601
      String sql = new String("select server from " +
1602
                              "xml_replication where serverid = " +
1603
                              serverCode);
1604
      pstmt = dbConn.prepareStatement(sql);
1605
      //System.out.println("getserver sql: " + sql);
1606
      pstmt.execute();
1607
      ResultSet rs = pstmt.getResultSet();
1608
      boolean tablehasrows = rs.next();
1609
      if(tablehasrows)
1610
      {
1611
        //System.out.println("server: " + rs.getString(1));
1612
        return rs.getString(1);
1613
      }
1614

    
1615
      //conn.close();
1616
    }
1617
    catch(Exception e)
1618
    {
1619
      System.out.println("Error in MetacatReplication.getServer: " +
1620
                          e.getMessage());
1621
    }
1622
    finally
1623
    {
1624
      try
1625
      {
1626
        pstmt.close();
1627
      }//try
1628
      catch (SQLException ee)
1629
      {
1630
        logMetacat.error("Error in MetacactReplication.getserver: "+
1631
                                    ee.getMessage());
1632
      }//catch
1633
      finally
1634
      {
1635
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1636
      }//fianlly
1637
    }//finally
1638

    
1639

    
1640

    
1641
    return null;
1642
      //return null if the server does not exist
1643
  }
1644

    
1645
  /**
1646
   * Returns a server code given a server name
1647
   * @param server the name of the server
1648
   * @return integer > 0 representing the code of the server, 0 if the server
1649
   *  does not exist.
1650
   */
1651
  public static int getServerCodeForServerName(String server) throws Exception
1652
  {
1653
    DBConnection dbConn = null;
1654
    int serialNumber = -1;
1655
    PreparedStatement pstmt = null;
1656
    int serverCode = 0;
1657

    
1658
    try {
1659

    
1660
      //conn = util.openDBConnection();
1661
      dbConn=DBConnectionPool.
1662
                  getDBConnection("MetacatReplication.getServerCode");
1663
      serialNumber=dbConn.getCheckOutSerialNumber();
1664
      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
1665
                                    "WHERE server LIKE '" + server + "'");
1666
      pstmt.execute();
1667
      ResultSet rs = pstmt.getResultSet();
1668
      boolean tablehasrows = rs.next();
1669
      if ( tablehasrows ) {
1670
        serverCode = rs.getInt(1);
1671
        pstmt.close();
1672
        //conn.close();
1673
        return serverCode;
1674
      }
1675

    
1676
    } catch(Exception e) {
1677
      throw e;
1678

    
1679
    } finally {
1680
      try
1681
      {
1682
        pstmt.close();
1683
        //conn.close();
1684
       }//try
1685
       catch(Exception ee)
1686
       {
1687
         logMetacat.error("Error in MetacatReplicatio.getServerCode: "
1688
                                  +ee.getMessage());
1689

    
1690
       }//catch
1691
       finally
1692
       {
1693
         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1694
       }//finally
1695
    }//finally
1696

    
1697
    return serverCode;
1698
  }
1699

    
1700
  /**
1701
   * Method to get a host server information for given docid
1702
   * @param conn a connection to the database
1703
   */
1704
  public static Hashtable getHomeServerInfoForDocId(String docId)
1705
  {
1706
    Hashtable sl = new Hashtable();
1707
    DBConnection dbConn = null;
1708
    int serialNumber = -1;
1709
    docId=MetaCatUtil.getDocIdFromString(docId);
1710
    PreparedStatement pstmt=null;
1711
    int serverLocation;
1712
    try
1713
    {
1714
      //get conection
1715
      dbConn=DBConnectionPool.
1716
                  getDBConnection("ReplicationHandler.getHomeServer");
1717
      serialNumber=dbConn.getCheckOutSerialNumber();
1718
      //get a server location from xml_document table
1719
      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
1720
                                            +"where docid = ?");
1721
      pstmt.setString(1, docId);
1722
      pstmt.execute();
1723
      ResultSet serverName = pstmt.getResultSet();
1724
      //get a server location
1725
      if(serverName.next())
1726
      {
1727
        serverLocation=serverName.getInt(1);
1728
        pstmt.close();
1729
      }
1730
      else
1731
      {
1732
        pstmt.close();
1733
        //ut.returnConnection(conn);
1734
        return null;
1735
      }
1736
      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
1737
                        "from xml_replication where serverid = ?");
1738
      //increase usage count
1739
      dbConn.increaseUsageCount(1);
1740
      pstmt.setInt(1, serverLocation);
1741
      pstmt.execute();
1742
      ResultSet rs = pstmt.getResultSet();
1743
      boolean tableHasRows = rs.next();
1744
      if (tableHasRows)
1745
      {
1746

    
1747
          String server = rs.getString(1);
1748
          String last_checked = rs.getString(2);
1749
          if(!server.equals("localhost"))
1750
          {
1751
            sl.put(server, last_checked);
1752
          }
1753

    
1754
      }
1755
      else
1756
      {
1757
        pstmt.close();
1758
        //ut.returnConnection(conn);
1759
        return null;
1760
      }
1761
      pstmt.close();
1762
    }
1763
    catch(Exception e)
1764
    {
1765
      System.out.println("error in replicationHandler.getHomeServer(): " +
1766
                         e.getMessage());
1767
    }
1768
    finally
1769
    {
1770
      try
1771
      {
1772
        pstmt.close();
1773
        //ut.returnConnection(conn);
1774
      }
1775
      catch (Exception ee)
1776
      {
1777
        logMetacat.error("Eror irn rplicationHandler.getHomeServer() "+
1778
                          "to close pstmt: "+ee.getMessage());
1779
      }
1780
      finally
1781
      {
1782
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1783
      }
1784

    
1785
    }//finally
1786
    return sl;
1787
  }
1788

    
1789
  /**
1790
   * Returns a home server location  given a accnum
1791
   * @param accNum , given accNum for a document
1792
   *
1793
   */
1794
  public static int getHomeServerCodeForDocId(String accNum) throws Exception
1795
  {
1796
    DBConnection dbConn = null;
1797
    int serialNumber = -1;
1798
    PreparedStatement pstmt = null;
1799
    int serverCode = 1;
1800
    String docId=MetaCatUtil.getDocIdFromString(accNum);
1801

    
1802
    try
1803
    {
1804

    
1805
      // Get DBConnection
1806
      dbConn=DBConnectionPool.
1807
                  getDBConnection("ReplicationHandler.getServerLocation");
1808
      serialNumber=dbConn.getCheckOutSerialNumber();
1809
      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1810
                              + "WHERE docid LIKE '" + docId + "'");
1811
      pstmt.execute();
1812
      ResultSet rs = pstmt.getResultSet();
1813
      boolean tablehasrows = rs.next();
1814
      //If a document is find, return the server location for it
1815
      if ( tablehasrows )
1816
      {
1817
        serverCode = rs.getInt(1);
1818
        pstmt.close();
1819
        //conn.close();
1820
        return serverCode;
1821
      }
1822
      //if couldn't find in xml_documents table, we think server code is 1
1823
      //(this is new document)
1824
      else
1825
      {
1826
        pstmt.close();
1827
        //conn.close();
1828
        return serverCode;
1829
      }
1830

    
1831
    }
1832
    catch(Exception e)
1833
    {
1834

    
1835
      throw e;
1836

    
1837
    }
1838
    finally
1839
    {
1840
      try
1841
      {
1842
        pstmt.close();
1843
        //conn.close();
1844

    
1845
      }
1846
      catch(Exception ee)
1847
      {
1848
        logMetacat.error("Erorr in Replication.getServerLocation "+
1849
                     "to close pstmt"+ee.getMessage());
1850
      }
1851
      finally
1852
      {
1853
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1854
      }//finally
1855
    }//finally
1856
   //return serverCode;
1857
  }
1858

    
1859

    
1860

    
1861
  /**
1862
   * This method returns the content of a url
1863
   * @param u the url to return the content from
1864
   * @return a string representing the content of the url
1865
   * @throws java.io.IOException
1866
   */
1867
  public static String getURLContent(URL u) throws java.io.IOException
1868
  {
1869
    char istreamChar;
1870
    int istreamInt;
1871
    logMetacat.info("Before open the stream"+u.toString());
1872
    InputStream input = u.openStream();
1873
    logMetacat.info("Afetr open the stream"+u.toString());
1874
    InputStreamReader istream = new InputStreamReader(input);
1875
    StringBuffer serverResponse = new StringBuffer();
1876
    while((istreamInt = istream.read()) != -1)
1877
    {
1878
      istreamChar = (char)istreamInt;
1879
      serverResponse.append(istreamChar);
1880
    }
1881
    istream.close();
1882
    input.close();
1883

    
1884
    return serverResponse.toString();
1885
  }
1886

    
1887
  /**
1888
	 * Method for writing replication messages to a log file specified in
1889
	 * metacat.properties
1890
	 */
1891
	public static void replLog(String message) {
1892
		try {
1893
			FileOutputStream fos = 
1894
				new FileOutputStream(PropertyService.getProperty("application.tomcatDir")
1895
					+ "/logs/metacatreplication.log", true);
1896
			PrintWriter pw = new PrintWriter(fos);
1897
			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
1898
			java.util.Date localtime = new java.util.Date();
1899
			String dateString = formatter.format(localtime);
1900
			dateString += " :: " + message;
1901
			// time stamp each entry
1902
			pw.println(dateString);
1903
			pw.flush();
1904
		} catch (Exception e) {
1905
			System.out.println("error writing to replication log from "
1906
					+ "MetacatReplication.replLog: " + e.getMessage());
1907
			// e.printStackTrace(System.out);
1908
		}
1909
	}
1910

    
1911
  /**
1912
	 * Method for writing replication messages to a log file specified in
1913
	 * metacat.properties
1914
	 */
1915
  public static void replErrorLog(String message)
1916
  {
1917
    try
1918
    {
1919
      FileOutputStream fos = new FileOutputStream(
1920
                                 PropertyService.getProperty("replicationerrorlog"), true);
1921
      PrintWriter pw = new PrintWriter(fos);
1922
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1923
      java.util.Date localtime = new java.util.Date();
1924
      String dateString = formatter.format(localtime);
1925
      dateString += " :: " + message;
1926
      //time stamp each entry
1927
      pw.println(dateString);
1928
      pw.flush();
1929
    }
1930
    catch(Exception e)
1931
    {
1932
      System.out.println("error writing to replication log from " +
1933
                         "MetacatReplication.replLog: " + e.getMessage());
1934
      //e.printStackTrace(System.out);
1935
    }
1936
  }
1937

    
1938
  /**
1939
   * Returns true if the replicate field for server in xml_replication is 1.
1940
   * Returns false otherwise
1941
   */
1942
  public static boolean replToServer(String server)
1943
  {
1944
    DBConnection dbConn = null;
1945
    int serialNumber = -1;
1946
    PreparedStatement pstmt = null;
1947
    try
1948
    {
1949
      dbConn=DBConnectionPool.
1950
                  getDBConnection("MetacatReplication.repltoServer");
1951
      serialNumber=dbConn.getCheckOutSerialNumber();
1952
      pstmt = dbConn.prepareStatement("select replicate from " +
1953
                                    "xml_replication where server like '" +
1954
                                     server + "'");
1955
      pstmt.execute();
1956
      ResultSet rs = pstmt.getResultSet();
1957
      boolean tablehasrows = rs.next();
1958
      if(tablehasrows)
1959
      {
1960
        int i = rs.getInt(1);
1961
        if(i == 1)
1962
        {
1963
          pstmt.close();
1964
          //conn.close();
1965
          return true;
1966
        }
1967
        else
1968
        {
1969
          pstmt.close();
1970
          //conn.close();
1971
          return false;
1972
        }
1973
      }
1974
    }
1975
    catch(Exception e)
1976
    {
1977
      System.out.println("error in MetacatReplication.replToServer: " +
1978
                         e.getMessage());
1979
    }
1980
    finally
1981
    {
1982
      try
1983
      {
1984
        pstmt.close();
1985
        //conn.close();
1986
      }//try
1987
      catch(Exception ee)
1988
      {
1989
        logMetacat.error("Error in MetacatReplication.replToServer: "
1990
                                  +ee.getMessage());
1991
      }//catch
1992
      finally
1993
      {
1994
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1995
      }//finally
1996
    }//finally
1997
    return false;
1998
    //the default if this server does not exist is to not replicate to it.
1999
  }
2000

    
2001

    
2002
}
(46-46/67)