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