Project

General

Profile

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