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: tao $'
9
 *     '$Date: 2007-04-13 11:49:06 -0700 (Fri, 13 Apr 2007) $'
10
 * '$Revision: 3233 $'
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 edu.ucsb.nceas.dbadapter.AbstractDatabase;
30
import java.util.*;
31
import java.util.Date;
32
import java.io.*;
33
import java.sql.*;
34
import java.net.*;
35
import java.lang.*;
36
import java.text.*;
37
import javax.servlet.*;
38
import javax.servlet.http.*;
39

    
40
import org.apache.log4j.Logger;
41
import org.xml.sax.*;
42

    
43
public class MetacatReplication extends HttpServlet implements Runnable
44
{
45
  private long timeInterval;
46
  private Date firstTime;
47
  private boolean timedReplicationIsOn = false;
48
  Timer replicationDaemon;
49
  private static MetaCatUtil util = new MetaCatUtil();
50
  private Vector fileLocks = new Vector();
51
  private Thread lockThread = null;
52
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
53
  public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
54
  private static final String TIMEREPLICATION = "timedreplication";
55
  private static final String TIMEREPLICATIONINTERVAl = "timedreplicationinterval";
56
  private static final String FIRSTTIME  = "firsttimedreplication";
57
  private static final int    TIMEINTERVALLIMIT = 7200000;
58
  private static Logger logMetacat = Logger.getLogger(MetacatReplication.class);
59
  public static final String REPLICATIONUSER = "replication";
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, request);
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, request);
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, request);
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, HttpServletRequest request)
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
      EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, dbaction);
662
    }//try
663
    catch(Exception e)
664
    {
665
      MetacatReplication.replErrorLog("document " + docid +
666
                                      " failed to added to DB with " +
667
                                      "action " + dbaction + " because "+
668
                                       e.getMessage());
669
      logMetacat.error("ERROR in MetacatReplication.handleForceReplicate" +
670
                         "Request(): " + e.getMessage());
671

    
672
    }//catch
673
    finally
674
    {
675
      // Return the checked out DBConnection
676
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
677
    }//finally
678
  }
679

    
680
/*
681
 * when a forcereplication delete request comes in, local host will delete this
682
 * document
683
 */
684
private void handleForceReplicateDeleteRequest(PrintWriter out, Hashtable params,
685
                                         HttpServletResponse response, HttpServletRequest request)
686
{
687
  String server = ((String[])params.get("server"))[0]; // the server that
688
  String docid = ((String[])params.get("docid"))[0]; // sent the document
689
  try
690
  {
691
    MetacatReplication.replLog("force replication delete request from " + server);
692
    MetacatReplication.replLog("force replication delete docid " + docid);
693
    logMetacat.info("Force replication delete request from: "+ server);
694
    logMetacat.info("Force replication delete docid: "+docid);
695
    DocumentImpl.delete(docid, null, null, server);
696
    MetacatReplication.replLog("document " + docid + " was successfully deleted ");
697
    EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, "delete");
698
    logMetacat.info("document " + docid + " was successfully deleted ");
699
  }
700
  catch(Exception e)
701
  {
702
    MetacatReplication.replErrorLog("document " + docid +
703
                                    " failed to delete because "+
704
                                     e.getMessage());
705
    logMetacat.error("ERROR in MetacatReplication.handleForceDeleteReplicate" +
706
                       "Request(): " + e.getMessage());
707

    
708
  }//catch
709

    
710
}
711

    
712

    
713
  /**
714
   * when a forcereplication data file request comes in, local host sends a
715
   * readdata request to the requesting server (remote server) for the specified
716
   * docid. Then store it in local database and file system
717
   */
718
  private void handleForceReplicateDataFileRequest(Hashtable params, HttpServletRequest request)
719
  {
720

    
721
    //make sure there is some parameters
722
    if(params.isEmpty())
723
    {
724
      return;
725
    }
726
    // Get remote server
727
    String server = ((String[])params.get("server"))[0];
728
    // the docid should include rev number
729
    String docid = ((String[])params.get("docid"))[0];
730
    // Make sure there is a docid and server
731
    if (docid==null || server==null || server.equals(""))
732
    {
733
      logMetacat.error("Didn't specify docid or server for replication");
734
      return;
735
    }
736

    
737
    // Overide or not
738
    boolean override = false;
739
    // dbaction - update or insert
740
    String dbaction=null;
741

    
742
    try
743
    {
744
      //docid was switch to two parts uinque code and rev
745
      //String uniqueCode=MetaCatUtil.getDocIdFromString(docid);
746
      //int rev=MetaCatUtil.getVersionFromString(docid);
747
      if(params.containsKey("dbaction"))
748
      {
749
        dbaction = ((String[])params.get("dbaction"))[0];
750
      }
751
      else//default value is update
752
      {
753
        dbaction = "update";
754
      }
755

    
756
      MetacatReplication.replLog("force replication request from " + server);
757
      logMetacat.info("Force replication request from: "+ server);
758
      logMetacat.info("Force replication docid: "+docid);
759
      logMetacat.info("Force replication action: "+dbaction);
760
      // get the document info from server
761
      URL docinfourl = new URL("https://" + server +
762
                               "?server="+util.getLocalReplicationServerName()
763
                               +"&action=getdocumentinfo&docid=" + docid);
764

    
765
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
766

    
767
      //dih is the parser for the docinfo xml format
768
      DocInfoHandler dih = new DocInfoHandler();
769
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
770
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
771
      Hashtable docinfoHash = dih.getDocInfo();
772
      String user = (String)docinfoHash.get("user_owner");
773

    
774
      String docName = (String)docinfoHash.get("docname");
775

    
776
      String docType = (String)docinfoHash.get("doctype");
777

    
778
      String docHomeServer= (String)docinfoHash.get("home_server");
779
      
780
      String createdDate = (String)docinfoHash.get("date_created");
781
      
782
      String updatedDate = (String)docinfoHash.get("date_updated");
783
      logMetacat.info("docHomeServer of datafile: "+docHomeServer);
784

    
785

    
786

    
787
      //if action is delete, we don't delete the data file. Just archieve
788
      //the xml_documents
789
      /*if (dbaction.equals("delete"))
790
      {
791
        //conn = util.getConnection();
792
        DocumentImpl.delete(docid,user,null);
793
        //util.returnConnection(conn);
794
      }*/
795
      //To data file insert or update is same
796
      if (dbaction.equals("insert")||dbaction.equals("update"))
797
      {
798
        //Get data file and store it into local file system.
799
        // sending back readdata request to server
800
        URL url = new URL("https://" + server + "?server="
801
                +util.getLocalReplicationServerName()
802
                +"&action=readdata&docid=" + docid);
803
        String datafilePath = util.getOption("datafilepath");
804
        //register data file into xml_documents table and wite data file
805
        //into file system
806
        DocumentImpl.writeDataFileInReplication(url.openStream(), datafilePath,
807
                            docName, docType, docid, user,docHomeServer,server, 
808
                            DocumentImpl.DOCUMENTTABLE, false, createdDate, updatedDate);
809
                            //false means non-timed replication
810
        MetacatReplication.replLog("datafile " + docid + " added to DB with " +
811
                "action " + dbaction);
812
        EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, dbaction);
813
     }
814

    
815

    
816

    
817
    
818
    }
819
    catch(Exception e)
820
    {
821

    
822
      MetacatReplication.replErrorLog("Datafile " + docid +
823
                                      " failed to added to DB with " +
824
                                      "action " + dbaction + " because "+
825
                                       e.getMessage());
826
      logMetacat.error
827
              ("ERROR in MetacatReplication.handleForceDataFileReplicate" +
828
                         "Request(): " + e.getMessage());
829
    }
830
  }
831
  /**
832
   * Grants or denies a lock to a requesting host.
833
   * The servlet parameters of interrest are:
834
   * docid: the docid of the file the lock is being requested for
835
   * currentdate: the timestamp of the document on the remote server
836
   *
837
   */
838
  private void handleGetLockRequest(PrintWriter out, Hashtable params,
839
                                    HttpServletResponse response)
840
  {
841

    
842
    try
843
    {
844

    
845
      String docid = ((String[])params.get("docid"))[0];
846
      String remoteRev = ((String[])params.get("updaterev"))[0];
847
      DocumentImpl requestDoc = new DocumentImpl(docid);
848
      MetacatReplication.replLog("lock request for " + docid);
849
      int localRevInt = requestDoc.getRev();
850
      int remoteRevInt = Integer.parseInt(remoteRev);
851

    
852
      if(remoteRevInt >= localRevInt)
853
      {
854
        if(!fileLocks.contains(docid))
855
        { //grant the lock if it is not already locked
856
          fileLocks.add(0, docid); //insert at the beginning of the queue Vector
857
          //send a message back to the the remote host authorizing the insert
858
          out.println("<lockgranted><docid>" +docid+ "</docid></lockgranted>");
859
          lockThread = new Thread(this);
860
          lockThread.setPriority(Thread.MIN_PRIORITY);
861
          lockThread.start();
862
          MetacatReplication.replLog("lock granted for " + docid);
863
        }
864
        else
865
        { //deny the lock
866
          out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
867
          MetacatReplication.replLog("lock denied for " + docid +
868
                                     "reason: file already locked");
869
        }
870
      }
871
      else
872
      {//deny the lock.
873
        out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
874
        MetacatReplication.replLog("lock denied for " + docid +
875
                                   "reason: client has outdated file");
876
      }
877
      //conn.close();
878
    }
879
    catch(Exception e)
880
    {
881
      System.out.println("error requesting file lock from MetacatReplication." +
882
                         "handleGetLockRequest: " + e.getMessage());
883
      e.printStackTrace(System.out);
884
    }
885
  }
886

    
887
  /**
888
   * Sends all of the xml_documents information encoded in xml to a requestor
889
   * the format is:
890
   * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
891
   *                  user_updated, home_server, public_access, rev)/>
892
   * all of the subelements of document info are #PCDATA
893
   */
894
  private void handleGetDocumentInfoRequest(PrintWriter out, Hashtable params,
895
                                        HttpServletResponse response)
896
  {
897
    String docid = ((String[])(params.get("docid")))[0];
898
    StringBuffer sb = new StringBuffer();
899

    
900
    try
901
    {
902

    
903
      DocumentImpl doc = new DocumentImpl(docid);
904
      sb.append("<documentinfo><docid>").append(docid);
905
      sb.append("</docid><docname>").append(doc.getDocname());
906
      sb.append("</docname><doctype>").append(doc.getDoctype());
907
      sb.append("</doctype>");
908
      sb.append("<user_owner>").append(doc.getUserowner());
909
      sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
910
      sb.append("</user_updated>");
911
      sb.append("<date_created>");
912
      sb.append(doc.getCreateDate());
913
      sb.append("</date_created>");
914
      sb.append("<date_updated>");
915
      sb.append(doc.getUpdateDate());
916
      sb.append("</date_updated>");
917
      sb.append("<home_server>");
918
      sb.append(doc.getDocHomeServer());
919
      sb.append("</home_server>");
920
      sb.append("<public_access>").append(doc.getPublicaccess());
921
      sb.append("</public_access><rev>").append(doc.getRev());
922
      sb.append("</rev></documentinfo>");
923
      response.setContentType("text/xml");
924
      out.println(sb.toString());
925

    
926
    }
927
    catch (Exception e)
928
    {
929
      System.out.println("error in " +
930
                         "metacatReplication.handlegetdocumentinforequest: " +
931
                          e.getMessage());
932
    }
933

    
934
  }
935

    
936
  /**
937
   * Sends a datafile to a remote host
938
   */
939
  private void handleGetDataFileRequest(OutputStream outPut,
940
                            Hashtable params, HttpServletResponse response)
941

    
942
  {
943
    // File path for data file
944
    String filepath = util.getOption("datafilepath");
945
    // Request docid
946
    String docId = ((String[])(params.get("docid")))[0];
947
    //check if the doicd is null
948
    if (docId==null)
949
    {
950
      logMetacat.error("Didn't specify docid for replication");
951
      return;
952
    }
953

    
954
    //try to open a https stream to test if the request server's public key
955
    //in the key store, this is security issue
956
    try
957
    {
958
      String server = ((String[])params.get("server"))[0];
959
      URL u = new URL("https://" + server + "?server="
960
                +util.getLocalReplicationServerName()
961
                +"&action=test");
962
      String test = MetacatReplication.getURLContent(u);
963
      //couldn't pass the test
964
      if (test.indexOf("successfully")==-1)
965
      {
966
        //response.setContentType("text/xml");
967
        //outPut.println("<error>Couldn't pass the trust test</error>");
968
        logMetacat.error("Couldn't pass the trust test");
969
        return;
970
      }
971
    }//try
972
    catch (Exception ee)
973
    {
974
      return;
975
    }//catch
976

    
977
    if(!filepath.endsWith("/"))
978
    {
979
          filepath += "/";
980
    }
981
    // Get file aboslute file name
982
    String filename = filepath + docId;
983

    
984
    //MIME type
985
    String contentType = null;
986
    if (filename.endsWith(".xml"))
987
    {
988
        contentType="text/xml";
989
    }
990
    else if (filename.endsWith(".css"))
991
    {
992
        contentType="text/css";
993
    }
994
    else if (filename.endsWith(".dtd"))
995
    {
996
        contentType="text/plain";
997
    }
998
    else if (filename.endsWith(".xsd"))
999
    {
1000
        contentType="text/xml";
1001
    }
1002
    else if (filename.endsWith("/"))
1003
    {
1004
        contentType="text/html";
1005
    }
1006
    else
1007
    {
1008
        File f = new File(filename);
1009
        if ( f.isDirectory() )
1010
        {
1011
           contentType="text/html";
1012
        }
1013
        else
1014
        {
1015
           contentType="application/octet-stream";
1016
        }
1017
     }
1018

    
1019
   // Set the mime type
1020
   response.setContentType(contentType);
1021

    
1022
   // Get the content of the file
1023
   FileInputStream fin = null;
1024
   try
1025
   {
1026
      // FileInputStream to metacat
1027
      fin = new FileInputStream(filename);
1028
      // 4K buffer
1029
      byte[] buf = new byte[4 * 1024];
1030
      // Read data from file input stream to byte array
1031
      int b = fin.read(buf);
1032
      // Write to outStream from byte array
1033
      while (b != -1)
1034
      {
1035
        outPut.write(buf, 0, b);
1036
        b = fin.read(buf);
1037
      }
1038
      // close file input stream
1039
      fin.close();
1040

    
1041
   }//try
1042
   catch(Exception e)
1043
   {
1044
      System.out.println("error getting data file from MetacatReplication." +
1045
                         "handlGetDataFileRequest " + e.getMessage());
1046
      e.printStackTrace(System.out);
1047
   }//catch
1048

    
1049
}
1050

    
1051

    
1052
  /**
1053
   * Sends a document to a remote host
1054
   */
1055
  private void handleGetDocumentRequest(PrintWriter out, Hashtable params,
1056
                                        HttpServletResponse response)
1057
  {
1058

    
1059
    try
1060
    {
1061
      //try to open a https stream to test if the request server's public key
1062
      //in the key store, this is security issue
1063
      String server = ((String[])params.get("server"))[0];
1064
      URL u = new URL("https://" + server + "?server="
1065
                +util.getLocalReplicationServerName()
1066
                +"&action=test");
1067
      String test = MetacatReplication.getURLContent(u);
1068
      //couldn't pass the test
1069
      if (test.indexOf("successfully")==-1)
1070
      {
1071
        response.setContentType("text/xml");
1072
        out.println("<error>Couldn't pass the trust test "+test+" </error>");
1073
        out.close();
1074
        return;
1075
      }
1076

    
1077
      String docid = ((String[])(params.get("docid")))[0];
1078

    
1079
      DocumentImpl di = new DocumentImpl(docid);
1080
      response.setContentType("text/xml");
1081
      out.print(di.toString(null, null, true));
1082

    
1083
      MetacatReplication.replLog("document " + docid + " sent");
1084

    
1085
    }
1086
    catch(Exception e)
1087
    {
1088
      logMetacat.error("error getting document from MetacatReplication."
1089
                          +"handlGetDocumentRequest " + e.getMessage());
1090
      //e.printStackTrace(System.out);
1091
      response.setContentType("text/xml");
1092
      out.println("<error>"+e.getMessage()+"</error>");
1093
    }
1094

    
1095
  }
1096

    
1097
  /**
1098
   * Sends a list of all of the documents on this sever along with their
1099
   * revision numbers.
1100
   * The format is:
1101
   * <!ELEMENT replication (server, updates)>
1102
   * <!ELEMENT server (#PCDATA)>
1103
   * <!ELEMENT updates ((updatedDocument | deleteDocument | revisionDocument)*)>
1104
   * <!ELEMENT updatedDocument (docid, rev, datafile*)>
1105
   * <!ELEMENT deletedDocument (docid, rev)>
1106
   * <!ELEMENT revisionDocument (docid, rev, datafile*)>
1107
   * <!ELEMENT docid (#PCDATA)>
1108
   * <!ELEMENT rev (#PCDATA)>
1109
   * <!ELEMENT datafile (#PCDATA)>
1110
   * note that the rev in deletedDocument is always empty.  I just left
1111
   * it in there to make the parser implementation easier.
1112
   */
1113
  private void handleUpdateRequest(PrintWriter out, Hashtable params,
1114
                                    HttpServletResponse response)
1115
  {
1116
    // Checked out DBConnection
1117
    DBConnection dbConn = null;
1118
    // DBConenction serial number when checked it out
1119
    int serialNumber = -1;
1120
    PreparedStatement pstmt = null;
1121
    // Server list to store server info of xml_replication table
1122
    ReplicationServerList serverList = null;
1123

    
1124
    try
1125
    {
1126
      // Check out a DBConnection from pool
1127
      dbConn=DBConnectionPool.
1128
                  getDBConnection("MetacatReplication.handleUpdateRequest");
1129
      serialNumber=dbConn.getCheckOutSerialNumber();
1130
      // Create a server list from xml_replication table
1131
      serverList = new ReplicationServerList();
1132

    
1133
      // Get remote server name from param
1134
      String server = ((String[])params.get("server"))[0];
1135
      // If no servr name in param, return a error
1136
      if ( server == null || server.equals(""))
1137
      {
1138
        response.setContentType("text/xml");
1139
        out.println("<error>Request didn't specify server name</error>");
1140
        out.close();
1141
        return;
1142
      }//if
1143

    
1144
      //try to open a https stream to test if the request server's public key
1145
      //in the key store, this is security issue
1146
      URL u = new URL("https://" + server + "?server="
1147
                +util.getLocalReplicationServerName()
1148
                +"&action=test");
1149
      String test = MetacatReplication.getURLContent(u);
1150
      //couldn't pass the test
1151
      if (test.indexOf("successfully")==-1)
1152
      {
1153
        response.setContentType("text/xml");
1154
        out.println("<error>Couldn't pass the trust test</error>");
1155
        out.close();
1156
        return;
1157
      }
1158

    
1159

    
1160
      // Check if local host configure to replicate xml documents to remote
1161
      // server. If not send back a error message
1162
      if (!serverList.getReplicationValue(server))
1163
      {
1164
        response.setContentType("text/xml");
1165
        out.println
1166
        ("<error>Configuration not allow to replicate document to you</error>");
1167
        out.close();
1168
        return;
1169
      }//if
1170

    
1171
      // Store the sql command
1172
      StringBuffer docsql = new StringBuffer();
1173
      StringBuffer revisionSql = new StringBuffer();
1174
      // Stroe the docid list
1175
      StringBuffer doclist = new StringBuffer();
1176
      // Store the deleted docid list
1177
      StringBuffer delsql = new StringBuffer();
1178
      // Store the data set file
1179
      Vector packageFiles = new Vector();
1180

    
1181
      // Append local server's name and replication servlet to doclist
1182
      doclist.append("<?xml version=\"1.0\"?><replication>");
1183
      doclist.append("<server>").append(util.getLocalReplicationServerName());
1184
      //doclist.append(util.getOption("replicationpath"));
1185
      doclist.append("</server><updates>");
1186

    
1187
      // Get correct docid that reside on this server according the requesting
1188
      // server's replicate and data replicate value in xml_replication table
1189
      docsql.append(dbAdapter.getReplicationDocumentListSQL());
1190
      //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)) ");
1191
      revisionSql.append("select docid, rev, doctype from xml_revisions ");
1192
      // If the localhost is not a hub to the remote server, only replicate
1193
      // the docid' which home server is local host (server_location =1)
1194
      if (!serverList.getHubValue(server))
1195
      {
1196
    	String serverLocationDoc = " and a.server_location = 1";
1197
        String serverLocationRev = "where server_location = 1";
1198
        docsql.append(serverLocationDoc);
1199
        revisionSql.append(serverLocationRev);
1200
      }
1201
      logMetacat.info("Doc sql: "+docsql.toString());
1202

    
1203
      // Get any deleted documents
1204
      delsql.append("select distinct docid from ");
1205
      delsql.append("xml_revisions where docid not in (select docid from ");
1206
      delsql.append("xml_documents) ");
1207
      // If the localhost is not a hub to the remote server, only replicate
1208
      // the docid' which home server is local host (server_location =1)
1209
      if (!serverList.getHubValue(server))
1210
      {
1211
        delsql.append("and server_location = 1");
1212
      }
1213
      logMetacat.info("Deleted sql: "+delsql.toString());
1214

    
1215

    
1216

    
1217
      // Get docid list of local host
1218
      pstmt = dbConn.prepareStatement(docsql.toString());
1219
      pstmt.execute();
1220
      ResultSet rs = pstmt.getResultSet();
1221
      boolean tablehasrows = rs.next();
1222
      //If metacat configed to replicate data file
1223
      //if ((util.getOption("replicationsenddata")).equals("on"))
1224
      boolean replicateData = serverList.getDataReplicationValue(server);
1225
      if (replicateData)
1226
      {
1227
        while(tablehasrows)
1228
        {
1229
          String recordDoctype = rs.getString(3);
1230
          Vector packagedoctypes = MetaCatUtil.getOptionList(
1231
                                     MetaCatUtil.getOption("packagedoctype"));
1232
          //if this is a package file, put it at the end
1233
          //because if a package file is read before all of the files it
1234
          //refers to are loaded then there is an error
1235
          if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1236
          {
1237
              //If this is not data file
1238
              if (!recordDoctype.equals("BIN"))
1239
              {
1240
                //for non-data file document
1241
                doclist.append("<updatedDocument>");
1242
                doclist.append("<docid>").append(rs.getString(1));
1243
                doclist.append("</docid><rev>").append(rs.getInt(2));
1244
                doclist.append("</rev>");
1245
                doclist.append("</updatedDocument>");
1246
              }//if
1247
              else
1248
              {
1249
                //for data file document, in datafile attributes
1250
                //we put "datafile" value there
1251
                doclist.append("<updatedDocument>");
1252
                doclist.append("<docid>").append(rs.getString(1));
1253
                doclist.append("</docid><rev>").append(rs.getInt(2));
1254
                doclist.append("</rev>");
1255
                doclist.append("<datafile>");
1256
                doclist.append(MetaCatUtil.getOption("datafileflag"));
1257
                doclist.append("</datafile>");
1258
                doclist.append("</updatedDocument>");
1259
              }//else
1260
          }//if packagedoctpes
1261
          else
1262
          { //the package files are saved to be put into the xml later.
1263
              Vector v = new Vector();
1264
              v.add(new String(rs.getString(1)));
1265
              v.add(new Integer(rs.getInt(2)));
1266
              packageFiles.add(new Vector(v));
1267
          }//esle
1268
          tablehasrows = rs.next();
1269
        }//while
1270
      }//if
1271
      else //metacat was configured not to send data file
1272
      {
1273
        while(tablehasrows)
1274
        {
1275
          String recordDoctype = rs.getString(3);
1276
          if(!recordDoctype.equals("BIN"))
1277
          { //don't replicate data files
1278
            Vector packagedoctypes = MetaCatUtil.getOptionList(
1279
                                     MetaCatUtil.getOption("packagedoctype"));
1280
            if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1281
            {   //if this is a package file, put it at the end
1282
              //because if a package file is read before all of the files it
1283
              //refers to are loaded then there is an error
1284
              doclist.append("<updatedDocument>");
1285
              doclist.append("<docid>").append(rs.getString(1));
1286
              doclist.append("</docid><rev>").append(rs.getInt(2));
1287
              doclist.append("</rev>");
1288
              doclist.append("</updatedDocument>");
1289
            }
1290
            else
1291
            { //the package files are saved to be put into the xml later.
1292
              Vector v = new Vector();
1293
              v.add(new String(rs.getString(1)));
1294
              v.add(new Integer(rs.getInt(2)));
1295
              packageFiles.add(new Vector(v));
1296
            }
1297
         }//if
1298
         tablehasrows = rs.next();
1299
        }//while
1300
      }//else
1301

    
1302
      pstmt = dbConn.prepareStatement(delsql.toString());
1303
      //usage count should increas 1
1304
      dbConn.increaseUsageCount(1);
1305

    
1306
      pstmt.execute();
1307
      rs = pstmt.getResultSet();
1308
      tablehasrows = rs.next();
1309
      while(tablehasrows)
1310
      { //handle the deleted documents
1311
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1312
        doclist.append("</docid><rev></rev></deletedDocument>");
1313
        //note that rev is always empty for deleted docs
1314
        tablehasrows = rs.next();
1315
      }
1316

    
1317
      //now we can put the package files into the xml results
1318
      for(int i=0; i<packageFiles.size(); i++)
1319
      {
1320
        Vector v = (Vector)packageFiles.elementAt(i);
1321
        doclist.append("<updatedDocument>");
1322
        doclist.append("<docid>").append((String)v.elementAt(0));
1323
        doclist.append("</docid><rev>");
1324
        doclist.append(((Integer)v.elementAt(1)).intValue());
1325
        doclist.append("</rev>");
1326
        doclist.append("</updatedDocument>");
1327
      }
1328
      // add revision doc list  
1329
      doclist.append(prepareRevisionDoc(dbConn,revisionSql.toString(),replicateData));
1330
        
1331
      doclist.append("</updates></replication>");
1332
      logMetacat.info("doclist: " + doclist.toString());
1333
      pstmt.close();
1334
      //conn.close();
1335
      response.setContentType("text/xml");
1336
      out.println(doclist.toString());
1337

    
1338
    }
1339
    catch(Exception e)
1340
    {
1341
      logMetacat.error("error in MetacatReplication." +
1342
                         "handleupdaterequest: " + e.getMessage());
1343
      //e.printStackTrace(System.out);
1344
      response.setContentType("text/xml");
1345
      out.println("<error>"+e.getMessage()+"</error>");
1346
    }
1347
    finally
1348
    {
1349
      try
1350
      {
1351
        pstmt.close();
1352
      }//try
1353
      catch (SQLException ee)
1354
      {
1355
        logMetacat.error("Error in MetacatReplication." +
1356
                "handleUpdaterequest to close pstmt: "+ee.getMessage());
1357
      }//catch
1358
      finally
1359
      {
1360
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1361
      }//finally
1362
    }//finally
1363

    
1364
  }//handlUpdateRequest
1365
  
1366
  /*
1367
   * This method will get the xml string for document in xml_revision
1368
   * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1369
   */
1370
  private String prepareRevisionDoc(DBConnection dbConn, String revSql, 
1371
                            boolean replicateData) throws Exception
1372
  {
1373
      logMetacat.warn("The revision document sql is "+ revSql);
1374
      StringBuffer revDocList = new StringBuffer();
1375
      PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1376
      //usage count should increas 1
1377
      dbConn.increaseUsageCount(1);
1378

    
1379
      pstmt.execute();
1380
      ResultSet rs = pstmt.getResultSet();
1381
      boolean tablehasrows = rs.next();
1382
      while(tablehasrows)
1383
      {
1384
        String recordDoctype = rs.getString(3);
1385
        
1386
        //If this is data file and it isn't configured to replicate data
1387
        if (recordDoctype.equals("BIN") && !replicateData)
1388
        {  
1389
            // do nothing
1390
            continue;
1391
        }
1392
        else
1393
        {  
1394
            
1395
            revDocList.append("<revisionDocument>");
1396
            revDocList.append("<docid>").append(rs.getString(1));
1397
            revDocList.append("</docid><rev>").append(rs.getInt(2));
1398
            revDocList.append("</rev>");
1399
            // data file
1400
            if (recordDoctype.equals("BIN"))
1401
            {
1402
                revDocList.append("<datafile>");
1403
                revDocList.append(MetaCatUtil.getOption("datafileflag"));
1404
                revDocList.append("</datafile>");
1405
            }
1406
            revDocList.append("</revisionDocument>");
1407
        
1408
         }//else
1409
         tablehasrows = rs.next();
1410
      }
1411
      //System.out.println("The revision list is"+ revDocList.toString());
1412
      return revDocList.toString();
1413
  }
1414

    
1415
  /**
1416
   * Returns the xml_catalog table encoded in xml
1417
   */
1418
  public static String getCatalogXML()
1419
  {
1420
    return handleGetCatalogRequest(null, null, null, false);
1421
  }
1422

    
1423
  /**
1424
   * Sends the contents of the xml_catalog table encoded in xml
1425
   * The xml format is:
1426
   * <!ELEMENT xml_catalog (row*)>
1427
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1428
   *                system_id)>
1429
   * All of the sub elements of row are #PCDATA
1430

    
1431
   * If printFlag == false then do not print to out.
1432
   */
1433
  private static String handleGetCatalogRequest(PrintWriter out,
1434
                                                Hashtable params,
1435
                                                HttpServletResponse response,
1436
                                                boolean printFlag)
1437
  {
1438
    DBConnection dbConn = null;
1439
    int serialNumber = -1;
1440
    PreparedStatement pstmt = null;
1441
    try
1442
    {
1443
      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1444
                                                "handleGetCatalogRequest");*/
1445
      dbConn=DBConnectionPool.
1446
                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
1447
      serialNumber=dbConn.getCheckOutSerialNumber();
1448
      pstmt = dbConn.prepareStatement("select entry_type, " +
1449
                              "source_doctype, target_doctype, public_id, " +
1450
                              "system_id from xml_catalog");
1451
      pstmt.execute();
1452
      ResultSet rs = pstmt.getResultSet();
1453
      boolean tablehasrows = rs.next();
1454
      StringBuffer sb = new StringBuffer();
1455
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1456
      while(tablehasrows)
1457
      {
1458
        sb.append("<row><entry_type>").append(rs.getString(1));
1459
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1460
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1461
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1462
        sb.append("</public_id><system_id>").append(rs.getString(5));
1463
        sb.append("</system_id></row>");
1464

    
1465
        tablehasrows = rs.next();
1466
      }
1467
      sb.append("</xml_catalog>");
1468
      //conn.close();
1469
      if(printFlag)
1470
      {
1471
        response.setContentType("text/xml");
1472
        out.println(sb.toString());
1473
      }
1474
      pstmt.close();
1475
      return sb.toString();
1476
    }
1477
    catch(Exception e)
1478
    {
1479

    
1480
      logMetacat.error("error in MetacatReplication.handleGetCatalogRequest:"+
1481
                          e.getMessage());
1482
      e.printStackTrace(System.out);
1483
      if(printFlag)
1484
      {
1485
        out.println("<error>"+e.getMessage()+"</error>");
1486
      }
1487
    }
1488
    finally
1489
    {
1490
      try
1491
      {
1492
        pstmt.close();
1493
      }//try
1494
      catch (SQLException ee)
1495
      {
1496
        logMetacat.error("Error in MetacatReplication.handleGetCatalogRequest: "
1497
           +ee.getMessage());
1498
      }//catch
1499
      finally
1500
      {
1501
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1502
      }//finally
1503
    }//finally
1504

    
1505
    return null;
1506
  }
1507

    
1508
  /**
1509
   * Sends the current system date to the remote server.  Using this action
1510
   * for replication gets rid of any problems with syncronizing clocks
1511
   * because a time specific to a document is always kept on its home server.
1512
   */
1513
  private void handleGetTimeRequest(PrintWriter out, Hashtable params,
1514
                                    HttpServletResponse response)
1515
  {
1516
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
1517
    java.util.Date localtime = new java.util.Date();
1518
    String dateString = formatter.format(localtime);
1519
    response.setContentType("text/xml");
1520

    
1521
    out.println("<timestamp>" + dateString + "</timestamp>");
1522
  }
1523

    
1524
  /**
1525
   * this method handles the timeout for a file lock.  when a lock is
1526
   * granted it is granted for 30 seconds.  When this thread runs out
1527
   * it deletes the docid from the queue, thus eliminating the lock.
1528
   */
1529
  public void run()
1530
  {
1531
    try
1532
    {
1533
      logMetacat.info("thread started for docid: " +
1534
                               (String)fileLocks.elementAt(0));
1535

    
1536
      Thread.sleep(30000); //the lock will expire in 30 seconds
1537
      logMetacat.info("thread for docid: " +
1538
                             (String)fileLocks.elementAt(fileLocks.size() - 1) +
1539
                              " exiting.");
1540

    
1541
      fileLocks.remove(fileLocks.size() - 1);
1542
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1543
      //in the vector, the first one inserted will be removed.
1544
    }
1545
    catch(Exception e)
1546
    {
1547
      logMetacat.error("error in file lock thread from " +
1548
                                "MetacatReplication.run: " + e.getMessage());
1549
    }
1550
  }
1551

    
1552
  /**
1553
   * Returns the name of a server given a serverCode
1554
   * @param serverCode the serverid of the server
1555
   * @return the servername or null if the specified serverCode does not
1556
   *         exist.
1557
   */
1558
  public static String getServerNameForServerCode(int serverCode)
1559
  {
1560
    //System.out.println("serverid: " + serverCode);
1561
    DBConnection dbConn = null;
1562
    int serialNumber = -1;
1563
    PreparedStatement pstmt = null;
1564
    try
1565
    {
1566
      dbConn=DBConnectionPool.
1567
                  getDBConnection("MetacatReplication.getServer");
1568
      serialNumber=dbConn.getCheckOutSerialNumber();
1569
      String sql = new String("select server from " +
1570
                              "xml_replication where serverid = " +
1571
                              serverCode);
1572
      pstmt = dbConn.prepareStatement(sql);
1573
      //System.out.println("getserver sql: " + sql);
1574
      pstmt.execute();
1575
      ResultSet rs = pstmt.getResultSet();
1576
      boolean tablehasrows = rs.next();
1577
      if(tablehasrows)
1578
      {
1579
        //System.out.println("server: " + rs.getString(1));
1580
        return rs.getString(1);
1581
      }
1582

    
1583
      //conn.close();
1584
    }
1585
    catch(Exception e)
1586
    {
1587
      System.out.println("Error in MetacatReplication.getServer: " +
1588
                          e.getMessage());
1589
    }
1590
    finally
1591
    {
1592
      try
1593
      {
1594
        pstmt.close();
1595
      }//try
1596
      catch (SQLException ee)
1597
      {
1598
        logMetacat.error("Error in MetacactReplication.getserver: "+
1599
                                    ee.getMessage());
1600
      }//catch
1601
      finally
1602
      {
1603
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1604
      }//fianlly
1605
    }//finally
1606

    
1607

    
1608

    
1609
    return null;
1610
      //return null if the server does not exist
1611
  }
1612

    
1613
  /**
1614
   * Returns a server code given a server name
1615
   * @param server the name of the server
1616
   * @return integer > 0 representing the code of the server, 0 if the server
1617
   *  does not exist.
1618
   */
1619
  public static int getServerCodeForServerName(String server) throws Exception
1620
  {
1621
    DBConnection dbConn = null;
1622
    int serialNumber = -1;
1623
    PreparedStatement pstmt = null;
1624
    int serverCode = 0;
1625

    
1626
    try {
1627

    
1628
      //conn = util.openDBConnection();
1629
      dbConn=DBConnectionPool.
1630
                  getDBConnection("MetacatReplication.getServerCode");
1631
      serialNumber=dbConn.getCheckOutSerialNumber();
1632
      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
1633
                                    "WHERE server LIKE '" + server + "'");
1634
      pstmt.execute();
1635
      ResultSet rs = pstmt.getResultSet();
1636
      boolean tablehasrows = rs.next();
1637
      if ( tablehasrows ) {
1638
        serverCode = rs.getInt(1);
1639
        pstmt.close();
1640
        //conn.close();
1641
        return serverCode;
1642
      }
1643

    
1644
    } catch(Exception e) {
1645
      throw e;
1646

    
1647
    } finally {
1648
      try
1649
      {
1650
        pstmt.close();
1651
        //conn.close();
1652
       }//try
1653
       catch(Exception ee)
1654
       {
1655
         logMetacat.error("Error in MetacatReplicatio.getServerCode: "
1656
                                  +ee.getMessage());
1657

    
1658
       }//catch
1659
       finally
1660
       {
1661
         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1662
       }//finally
1663
    }//finally
1664

    
1665
    return serverCode;
1666
  }
1667

    
1668
  /**
1669
   * Method to get a host server information for given docid
1670
   * @param conn a connection to the database
1671
   */
1672
  public static Hashtable getHomeServerInfoForDocId(String docId)
1673
  {
1674
    Hashtable sl = new Hashtable();
1675
    DBConnection dbConn = null;
1676
    int serialNumber = -1;
1677
    //MetaCatUtil ut=new MetaCatUtil();
1678
    docId=MetaCatUtil.getDocIdFromString(docId);
1679
    PreparedStatement pstmt=null;
1680
    int serverLocation;
1681
    try
1682
    {
1683
      //get conection
1684
      dbConn=DBConnectionPool.
1685
                  getDBConnection("ReplicationHandler.getHomeServer");
1686
      serialNumber=dbConn.getCheckOutSerialNumber();
1687
      //get a server location from xml_document table
1688
      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
1689
                                            +"where docid = ?");
1690
      pstmt.setString(1, docId);
1691
      pstmt.execute();
1692
      ResultSet serverName = pstmt.getResultSet();
1693
      //get a server location
1694
      if(serverName.next())
1695
      {
1696
        serverLocation=serverName.getInt(1);
1697
        pstmt.close();
1698
      }
1699
      else
1700
      {
1701
        pstmt.close();
1702
        //ut.returnConnection(conn);
1703
        return null;
1704
      }
1705
      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
1706
                        "from xml_replication where serverid = ?");
1707
      //increase usage count
1708
      dbConn.increaseUsageCount(1);
1709
      pstmt.setInt(1, serverLocation);
1710
      pstmt.execute();
1711
      ResultSet rs = pstmt.getResultSet();
1712
      boolean tableHasRows = rs.next();
1713
      if (tableHasRows)
1714
      {
1715

    
1716
          String server = rs.getString(1);
1717
          String last_checked = rs.getString(2);
1718
          if(!server.equals("localhost"))
1719
          {
1720
            sl.put(server, last_checked);
1721
          }
1722

    
1723
      }
1724
      else
1725
      {
1726
        pstmt.close();
1727
        //ut.returnConnection(conn);
1728
        return null;
1729
      }
1730
      pstmt.close();
1731
    }
1732
    catch(Exception e)
1733
    {
1734
      System.out.println("error in replicationHandler.getHomeServer(): " +
1735
                         e.getMessage());
1736
    }
1737
    finally
1738
    {
1739
      try
1740
      {
1741
        pstmt.close();
1742
        //ut.returnConnection(conn);
1743
      }
1744
      catch (Exception ee)
1745
      {
1746
        logMetacat.error("Eror irn rplicationHandler.getHomeServer() "+
1747
                          "to close pstmt: "+ee.getMessage());
1748
      }
1749
      finally
1750
      {
1751
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1752
      }
1753

    
1754
    }//finally
1755
    return sl;
1756
  }
1757

    
1758
  /**
1759
   * Returns a home server location  given a accnum
1760
   * @param accNum , given accNum for a document
1761
   *
1762
   */
1763
  public static int getHomeServerCodeForDocId(String accNum) throws Exception
1764
  {
1765
    DBConnection dbConn = null;
1766
    int serialNumber = -1;
1767
    PreparedStatement pstmt = null;
1768
    int serverCode = 1;
1769
    //MetaCatUtil ut = new MetaCatUtil();
1770
    String docId=MetaCatUtil.getDocIdFromString(accNum);
1771

    
1772
    try
1773
    {
1774

    
1775
      // Get DBConnection
1776
      dbConn=DBConnectionPool.
1777
                  getDBConnection("ReplicationHandler.getServerLocation");
1778
      serialNumber=dbConn.getCheckOutSerialNumber();
1779
      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1780
                              + "WHERE docid LIKE '" + docId + "'");
1781
      pstmt.execute();
1782
      ResultSet rs = pstmt.getResultSet();
1783
      boolean tablehasrows = rs.next();
1784
      //If a document is find, return the server location for it
1785
      if ( tablehasrows )
1786
      {
1787
        serverCode = rs.getInt(1);
1788
        pstmt.close();
1789
        //conn.close();
1790
        return serverCode;
1791
      }
1792
      //if couldn't find in xml_documents table, we think server code is 1
1793
      //(this is new document)
1794
      else
1795
      {
1796
        pstmt.close();
1797
        //conn.close();
1798
        return serverCode;
1799
      }
1800

    
1801
    }
1802
    catch(Exception e)
1803
    {
1804

    
1805
      throw e;
1806

    
1807
    }
1808
    finally
1809
    {
1810
      try
1811
      {
1812
        pstmt.close();
1813
        //conn.close();
1814

    
1815
      }
1816
      catch(Exception ee)
1817
      {
1818
        logMetacat.error("Erorr in Replication.getServerLocation "+
1819
                     "to close pstmt"+ee.getMessage());
1820
      }
1821
      finally
1822
      {
1823
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1824
      }//finally
1825
    }//finally
1826
   //return serverCode;
1827
  }
1828

    
1829

    
1830

    
1831
  /**
1832
   * This method returns the content of a url
1833
   * @param u the url to return the content from
1834
   * @return a string representing the content of the url
1835
   * @throws java.io.IOException
1836
   */
1837
  public static String getURLContent(URL u) throws java.io.IOException
1838
  {
1839
    char istreamChar;
1840
    int istreamInt;
1841
    logMetacat.info("Before open the stream"+u.toString());
1842
    InputStream input = u.openStream();
1843
    logMetacat.info("Afetr open the stream"+u.toString());
1844
    InputStreamReader istream = new InputStreamReader(input);
1845
    StringBuffer serverResponse = new StringBuffer();
1846
    while((istreamInt = istream.read()) != -1)
1847
    {
1848
      istreamChar = (char)istreamInt;
1849
      serverResponse.append(istreamChar);
1850
    }
1851
    istream.close();
1852
    input.close();
1853

    
1854
    return serverResponse.toString();
1855
  }
1856

    
1857
  /**
1858
   * Method for writing replication messages to a log file specified in
1859
   * metacat.properties
1860
   */
1861
  public static void replLog(String message)
1862
  {
1863
    try
1864
    {
1865
      FileOutputStream fos = new FileOutputStream(
1866
                                 util.getOption("replicationlog"), true);
1867
      PrintWriter pw = new PrintWriter(fos);
1868
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1869
      java.util.Date localtime = new java.util.Date();
1870
      String dateString = formatter.format(localtime);
1871
      dateString += " :: " + message;
1872
      //time stamp each entry
1873
      pw.println(dateString);
1874
      pw.flush();
1875
    }
1876
    catch(Exception e)
1877
    {
1878
      System.out.println("error writing to replication log from " +
1879
                         "MetacatReplication.replLog: " + e.getMessage());
1880
      //e.printStackTrace(System.out);
1881
    }
1882
  }
1883

    
1884
  /**
1885
   * Method for writing replication messages to a log file specified in
1886
   * metacat.properties
1887
   */
1888
  public static void replErrorLog(String message)
1889
  {
1890
    try
1891
    {
1892
      FileOutputStream fos = new FileOutputStream(
1893
                                 util.getOption("replicationerrorlog"), true);
1894
      PrintWriter pw = new PrintWriter(fos);
1895
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1896
      java.util.Date localtime = new java.util.Date();
1897
      String dateString = formatter.format(localtime);
1898
      dateString += " :: " + message;
1899
      //time stamp each entry
1900
      pw.println(dateString);
1901
      pw.flush();
1902
    }
1903
    catch(Exception e)
1904
    {
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
   * Returns true if the replicate field for server in xml_replication is 1.
1913
   * Returns false otherwise
1914
   */
1915
  public static boolean replToServer(String server)
1916
  {
1917
    DBConnection dbConn = null;
1918
    int serialNumber = -1;
1919
    PreparedStatement pstmt = null;
1920
    try
1921
    {
1922
      dbConn=DBConnectionPool.
1923
                  getDBConnection("MetacatReplication.repltoServer");
1924
      serialNumber=dbConn.getCheckOutSerialNumber();
1925
      pstmt = dbConn.prepareStatement("select replicate from " +
1926
                                    "xml_replication where server like '" +
1927
                                     server + "'");
1928
      pstmt.execute();
1929
      ResultSet rs = pstmt.getResultSet();
1930
      boolean tablehasrows = rs.next();
1931
      if(tablehasrows)
1932
      {
1933
        int i = rs.getInt(1);
1934
        if(i == 1)
1935
        {
1936
          pstmt.close();
1937
          //conn.close();
1938
          return true;
1939
        }
1940
        else
1941
        {
1942
          pstmt.close();
1943
          //conn.close();
1944
          return false;
1945
        }
1946
      }
1947
    }
1948
    catch(Exception e)
1949
    {
1950
      System.out.println("error in MetacatReplication.replToServer: " +
1951
                         e.getMessage());
1952
    }
1953
    finally
1954
    {
1955
      try
1956
      {
1957
        pstmt.close();
1958
        //conn.close();
1959
      }//try
1960
      catch(Exception ee)
1961
      {
1962
        logMetacat.error("Error in MetacatReplication.replToServer: "
1963
                                  +ee.getMessage());
1964
      }//catch
1965
      finally
1966
      {
1967
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1968
      }//finally
1969
    }//finally
1970
    return false;
1971
    //the default if this server does not exist is to not replicate to it.
1972
  }
1973

    
1974

    
1975
}
(46-46/66)