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
        out.println("<error>Couldn't pass the trust 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 1042 tao
      docsql.append("select docid, rev, doctype from xml_documents ");
1186 2597 tao
      revisionSql.append("select docid, rev, doctype from xml_revisions ");
1187 1292 tao
      // If the localhost is not a hub to the remote server, only replicate
1188
      // the docid' which home server is local host (server_location =1)
1189
      if (!serverList.getHubValue(server))
1190 1042 tao
      {
1191 2597 tao
        String serverLocation = "where server_location = 1";
1192
        docsql.append(serverLocation);
1193
        revisionSql.append(serverLocation);
1194 1042 tao
      }
1195 2663 sgarg
      logMetacat.info("Doc sql: "+docsql.toString());
1196 2286 tao
1197 1292 tao
      // Get any deleted documents
1198 577 berkley
      delsql.append("select distinct docid from ");
1199
      delsql.append("xml_revisions where docid not in (select docid from ");
1200 1042 tao
      delsql.append("xml_documents) ");
1201 1292 tao
      // If the localhost is not a hub to the remote server, only replicate
1202
      // the docid' which home server is local host (server_location =1)
1203
      if (!serverList.getHubValue(server))
1204 1042 tao
      {
1205
        delsql.append("and server_location = 1");
1206
      }
1207 2663 sgarg
      logMetacat.info("Deleted sql: "+delsql.toString());
1208 2286 tao
1209
1210
1211 1292 tao
      // Get docid list of local host
1212 1217 tao
      pstmt = dbConn.prepareStatement(docsql.toString());
1213 577 berkley
      pstmt.execute();
1214
      ResultSet rs = pstmt.getResultSet();
1215
      boolean tablehasrows = rs.next();
1216 1035 tao
      //If metacat configed to replicate data file
1217 1292 tao
      //if ((util.getOption("replicationsenddata")).equals("on"))
1218 2597 tao
      boolean replicateData = serverList.getDataReplicationValue(server);
1219
      if (replicateData)
1220 577 berkley
      {
1221 1020 tao
        while(tablehasrows)
1222
        {
1223
          String recordDoctype = rs.getString(3);
1224 1035 tao
          Vector packagedoctypes = MetaCatUtil.getOptionList(
1225
                                     MetaCatUtil.getOption("packagedoctype"));
1226 1292 tao
          //if this is a package file, put it at the end
1227
          //because if a package file is read before all of the files it
1228
          //refers to are loaded then there is an error
1229 1768 tao
          if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1230 2286 tao
          {
1231 1292 tao
              //If this is not data file
1232 1035 tao
              if (!recordDoctype.equals("BIN"))
1233
              {
1234
                //for non-data file document
1235
                doclist.append("<updatedDocument>");
1236
                doclist.append("<docid>").append(rs.getString(1));
1237
                doclist.append("</docid><rev>").append(rs.getInt(2));
1238
                doclist.append("</rev>");
1239
                doclist.append("</updatedDocument>");
1240 1292 tao
              }//if
1241 1035 tao
              else
1242
              {
1243
                //for data file document, in datafile attributes
1244
                //we put "datafile" value there
1245
                doclist.append("<updatedDocument>");
1246
                doclist.append("<docid>").append(rs.getString(1));
1247
                doclist.append("</docid><rev>").append(rs.getInt(2));
1248
                doclist.append("</rev>");
1249
                doclist.append("<datafile>");
1250
                doclist.append(MetaCatUtil.getOption("datafileflag"));
1251
                doclist.append("</datafile>");
1252
                doclist.append("</updatedDocument>");
1253 2286 tao
              }//else
1254 1292 tao
          }//if packagedoctpes
1255 1035 tao
          else
1256
          { //the package files are saved to be put into the xml later.
1257
              Vector v = new Vector();
1258
              v.add(new String(rs.getString(1)));
1259
              v.add(new Integer(rs.getInt(2)));
1260
              packageFiles.add(new Vector(v));
1261 1292 tao
          }//esle
1262 1035 tao
          tablehasrows = rs.next();
1263
        }//while
1264
      }//if
1265
      else //metacat was configured not to send data file
1266
      {
1267
        while(tablehasrows)
1268
        {
1269
          String recordDoctype = rs.getString(3);
1270 2286 tao
          if(!recordDoctype.equals("BIN"))
1271 1020 tao
          { //don't replicate data files
1272
            Vector packagedoctypes = MetaCatUtil.getOptionList(
1273 887 berkley
                                     MetaCatUtil.getOption("packagedoctype"));
1274 1768 tao
            if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1275 1020 tao
            {   //if this is a package file, put it at the end
1276
              //because if a package file is read before all of the files it
1277
              //refers to are loaded then there is an error
1278
              doclist.append("<updatedDocument>");
1279
              doclist.append("<docid>").append(rs.getString(1));
1280
              doclist.append("</docid><rev>").append(rs.getInt(2));
1281
              doclist.append("</rev>");
1282
              doclist.append("</updatedDocument>");
1283
            }
1284
            else
1285
            { //the package files are saved to be put into the xml later.
1286
              Vector v = new Vector();
1287
              v.add(new String(rs.getString(1)));
1288
              v.add(new Integer(rs.getInt(2)));
1289
              packageFiles.add(new Vector(v));
1290
            }
1291
         }//if
1292
         tablehasrows = rs.next();
1293
        }//while
1294 1035 tao
      }//else
1295 2286 tao
1296 1217 tao
      pstmt = dbConn.prepareStatement(delsql.toString());
1297
      //usage count should increas 1
1298
      dbConn.increaseUsageCount(1);
1299 2286 tao
1300 577 berkley
      pstmt.execute();
1301
      rs = pstmt.getResultSet();
1302
      tablehasrows = rs.next();
1303
      while(tablehasrows)
1304
      { //handle the deleted documents
1305
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1306
        doclist.append("</docid><rev></rev></deletedDocument>");
1307 583 berkley
        //note that rev is always empty for deleted docs
1308 577 berkley
        tablehasrows = rs.next();
1309
      }
1310 2286 tao
1311 625 berkley
      //now we can put the package files into the xml results
1312
      for(int i=0; i<packageFiles.size(); i++)
1313
      {
1314
        Vector v = (Vector)packageFiles.elementAt(i);
1315
        doclist.append("<updatedDocument>");
1316
        doclist.append("<docid>").append((String)v.elementAt(0));
1317
        doclist.append("</docid><rev>");
1318
        doclist.append(((Integer)v.elementAt(1)).intValue());
1319
        doclist.append("</rev>");
1320
        doclist.append("</updatedDocument>");
1321
      }
1322 2597 tao
      // add revision doc list
1323
      doclist.append(prepareRevisionDoc(dbConn,revisionSql.toString(),replicateData));
1324
1325 577 berkley
      doclist.append("</updates></replication>");
1326 2663 sgarg
      logMetacat.info("doclist: " + doclist.toString());
1327 667 berkley
      pstmt.close();
1328 1217 tao
      //conn.close();
1329 577 berkley
      response.setContentType("text/xml");
1330
      out.println(doclist.toString());
1331 2286 tao
1332 577 berkley
    }
1333
    catch(Exception e)
1334
    {
1335 2663 sgarg
      logMetacat.error("error in MetacatReplication." +
1336
                         "handleupdaterequest: " + e.getMessage());
1337 1101 tao
      //e.printStackTrace(System.out);
1338
      response.setContentType("text/xml");
1339 1292 tao
      out.println("<error>"+e.getMessage()+"</error>");
1340 577 berkley
    }
1341 1217 tao
    finally
1342
    {
1343
      try
1344
      {
1345
        pstmt.close();
1346
      }//try
1347
      catch (SQLException ee)
1348
      {
1349 2663 sgarg
        logMetacat.error("Error in MetacatReplication." +
1350
                "handleUpdaterequest to close pstmt: "+ee.getMessage());
1351 1217 tao
      }//catch
1352
      finally
1353
      {
1354
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1355
      }//finally
1356
    }//finally
1357 2286 tao
1358 1292 tao
  }//handlUpdateRequest
1359 2597 tao
1360
  /*
1361
   * This method will get the xml string for document in xml_revision
1362
   * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1363
   */
1364
  private String prepareRevisionDoc(DBConnection dbConn, String revSql,
1365
                            boolean replicateData) throws Exception
1366
  {
1367 2663 sgarg
      logMetacat.warn("The revision document sql is "+ revSql);
1368 2597 tao
      StringBuffer revDocList = new StringBuffer();
1369 2619 tao
      PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1370 2597 tao
      //usage count should increas 1
1371
      dbConn.increaseUsageCount(1);
1372 2286 tao
1373 2597 tao
      pstmt.execute();
1374
      ResultSet rs = pstmt.getResultSet();
1375
      boolean tablehasrows = rs.next();
1376
      while(tablehasrows)
1377
      {
1378
        String recordDoctype = rs.getString(3);
1379
1380
        //If this is data file and it isn't configured to replicate data
1381
        if (recordDoctype.equals("BIN") && !replicateData)
1382
        {
1383
            // do nothing
1384
            continue;
1385
        }
1386
        else
1387
        {
1388
1389
            revDocList.append("<revisionDocument>");
1390
            revDocList.append("<docid>").append(rs.getString(1));
1391
            revDocList.append("</docid><rev>").append(rs.getInt(2));
1392
            revDocList.append("</rev>");
1393
            // data file
1394
            if (recordDoctype.equals("BIN"))
1395
            {
1396
                revDocList.append("<datafile>");
1397
                revDocList.append(MetaCatUtil.getOption("datafileflag"));
1398
                revDocList.append("</datafile>");
1399
            }
1400 2619 tao
            revDocList.append("</revisionDocument>");
1401 2597 tao
1402
         }//else
1403 2619 tao
         tablehasrows = rs.next();
1404 2597 tao
      }
1405 2619 tao
      //System.out.println("The revision list is"+ revDocList.toString());
1406 2597 tao
      return revDocList.toString();
1407
  }
1408
1409 577 berkley
  /**
1410 590 berkley
   * Returns the xml_catalog table encoded in xml
1411
   */
1412
  public static String getCatalogXML()
1413
  {
1414
    return handleGetCatalogRequest(null, null, null, false);
1415
  }
1416 2286 tao
1417 590 berkley
  /**
1418
   * Sends the contents of the xml_catalog table encoded in xml
1419
   * The xml format is:
1420
   * <!ELEMENT xml_catalog (row*)>
1421
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1422
   *                system_id)>
1423
   * All of the sub elements of row are #PCDATA
1424 2286 tao
1425 590 berkley
   * If printFlag == false then do not print to out.
1426
   */
1427 2286 tao
  private static String handleGetCatalogRequest(PrintWriter out,
1428 590 berkley
                                                Hashtable params,
1429
                                                HttpServletResponse response,
1430
                                                boolean printFlag)
1431
  {
1432 1217 tao
    DBConnection dbConn = null;
1433
    int serialNumber = -1;
1434 667 berkley
    PreparedStatement pstmt = null;
1435 590 berkley
    try
1436 2286 tao
    {
1437 1217 tao
      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1438
                                                "handleGetCatalogRequest");*/
1439
      dbConn=DBConnectionPool.
1440
                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
1441
      serialNumber=dbConn.getCheckOutSerialNumber();
1442
      pstmt = dbConn.prepareStatement("select entry_type, " +
1443 590 berkley
                              "source_doctype, target_doctype, public_id, " +
1444
                              "system_id from xml_catalog");
1445
      pstmt.execute();
1446
      ResultSet rs = pstmt.getResultSet();
1447
      boolean tablehasrows = rs.next();
1448
      StringBuffer sb = new StringBuffer();
1449
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1450
      while(tablehasrows)
1451
      {
1452
        sb.append("<row><entry_type>").append(rs.getString(1));
1453
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1454
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1455
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1456
        sb.append("</public_id><system_id>").append(rs.getString(5));
1457
        sb.append("</system_id></row>");
1458 2286 tao
1459 590 berkley
        tablehasrows = rs.next();
1460
      }
1461
      sb.append("</xml_catalog>");
1462 1217 tao
      //conn.close();
1463 590 berkley
      if(printFlag)
1464
      {
1465
        response.setContentType("text/xml");
1466
        out.println(sb.toString());
1467
      }
1468 667 berkley
      pstmt.close();
1469 590 berkley
      return sb.toString();
1470
    }
1471
    catch(Exception e)
1472
    {
1473 2286 tao
1474 2663 sgarg
      logMetacat.error("error in MetacatReplication.handleGetCatalogRequest:"+
1475
                          e.getMessage());
1476 590 berkley
      e.printStackTrace(System.out);
1477 1292 tao
      if(printFlag)
1478
      {
1479
        out.println("<error>"+e.getMessage()+"</error>");
1480
      }
1481 590 berkley
    }
1482 1217 tao
    finally
1483
    {
1484
      try
1485
      {
1486
        pstmt.close();
1487
      }//try
1488
      catch (SQLException ee)
1489
      {
1490 2663 sgarg
        logMetacat.error("Error in MetacatReplication.handleGetCatalogRequest: "
1491
           +ee.getMessage());
1492 1217 tao
      }//catch
1493
      finally
1494
      {
1495
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1496
      }//finally
1497
    }//finally
1498 2286 tao
1499 590 berkley
    return null;
1500
  }
1501 2286 tao
1502 590 berkley
  /**
1503 568 berkley
   * Sends the current system date to the remote server.  Using this action
1504 2286 tao
   * for replication gets rid of any problems with syncronizing clocks
1505 568 berkley
   * because a time specific to a document is always kept on its home server.
1506
   */
1507 2286 tao
  private void handleGetTimeRequest(PrintWriter out, Hashtable params,
1508 568 berkley
                                    HttpServletResponse response)
1509
  {
1510 1752 tao
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
1511 568 berkley
    java.util.Date localtime = new java.util.Date();
1512
    String dateString = formatter.format(localtime);
1513
    response.setContentType("text/xml");
1514 2286 tao
1515 568 berkley
    out.println("<timestamp>" + dateString + "</timestamp>");
1516
  }
1517 2286 tao
1518 568 berkley
  /**
1519 2286 tao
   * this method handles the timeout for a file lock.  when a lock is
1520 583 berkley
   * granted it is granted for 30 seconds.  When this thread runs out
1521
   * it deletes the docid from the queue, thus eliminating the lock.
1522 561 berkley
   */
1523
  public void run()
1524
  {
1525
    try
1526
    {
1527 2663 sgarg
      logMetacat.info("thread started for docid: " +
1528
                               (String)fileLocks.elementAt(0));
1529 2286 tao
1530 561 berkley
      Thread.sleep(30000); //the lock will expire in 30 seconds
1531 2663 sgarg
      logMetacat.info("thread for docid: " +
1532 2286 tao
                             (String)fileLocks.elementAt(fileLocks.size() - 1) +
1533 2663 sgarg
                              " exiting.");
1534 2286 tao
1535 561 berkley
      fileLocks.remove(fileLocks.size() - 1);
1536 568 berkley
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1537 561 berkley
      //in the vector, the first one inserted will be removed.
1538
    }
1539
    catch(Exception e)
1540
    {
1541 2663 sgarg
      logMetacat.error("error in file lock thread from " +
1542
                                "MetacatReplication.run: " + e.getMessage());
1543 561 berkley
    }
1544
  }
1545 2286 tao
1546 561 berkley
  /**
1547
   * Returns the name of a server given a serverCode
1548
   * @param serverCode the serverid of the server
1549
   * @return the servername or null if the specified serverCode does not
1550
   *         exist.
1551
   */
1552 1292 tao
  public static String getServerNameForServerCode(int serverCode)
1553 561 berkley
  {
1554 569 berkley
    //System.out.println("serverid: " + serverCode);
1555 1217 tao
    DBConnection dbConn = null;
1556
    int serialNumber = -1;
1557
    PreparedStatement pstmt = null;
1558 561 berkley
    try
1559
    {
1560 1217 tao
      dbConn=DBConnectionPool.
1561
                  getDBConnection("MetacatReplication.getServer");
1562
      serialNumber=dbConn.getCheckOutSerialNumber();
1563 569 berkley
      String sql = new String("select server from " +
1564 2286 tao
                              "xml_replication where serverid = " +
1565 561 berkley
                              serverCode);
1566 1217 tao
      pstmt = dbConn.prepareStatement(sql);
1567 569 berkley
      //System.out.println("getserver sql: " + sql);
1568 561 berkley
      pstmt.execute();
1569
      ResultSet rs = pstmt.getResultSet();
1570
      boolean tablehasrows = rs.next();
1571
      if(tablehasrows)
1572
      {
1573 569 berkley
        //System.out.println("server: " + rs.getString(1));
1574 561 berkley
        return rs.getString(1);
1575
      }
1576 2286 tao
1577 1217 tao
      //conn.close();
1578 561 berkley
    }
1579
    catch(Exception e)
1580
    {
1581 2286 tao
      System.out.println("Error in MetacatReplication.getServer: " +
1582 561 berkley
                          e.getMessage());
1583
    }
1584 1217 tao
    finally
1585
    {
1586
      try
1587
      {
1588
        pstmt.close();
1589
      }//try
1590
      catch (SQLException ee)
1591
      {
1592 2663 sgarg
        logMetacat.error("Error in MetacactReplication.getserver: "+
1593
                                    ee.getMessage());
1594 1217 tao
      }//catch
1595
      finally
1596
      {
1597
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1598
      }//fianlly
1599
    }//finally
1600 2286 tao
1601
1602
1603 561 berkley
    return null;
1604
      //return null if the server does not exist
1605
  }
1606 2286 tao
1607 569 berkley
  /**
1608
   * Returns a server code given a server name
1609
   * @param server the name of the server
1610
   * @return integer > 0 representing the code of the server, 0 if the server
1611
   *  does not exist.
1612
   */
1613 1292 tao
  public static int getServerCodeForServerName(String server) throws Exception
1614 569 berkley
  {
1615 1217 tao
    DBConnection dbConn = null;
1616
    int serialNumber = -1;
1617 667 berkley
    PreparedStatement pstmt = null;
1618 837 bojilova
    int serverCode = 0;
1619
1620
    try {
1621
1622 1217 tao
      //conn = util.openDBConnection();
1623
      dbConn=DBConnectionPool.
1624
                  getDBConnection("MetacatReplication.getServerCode");
1625
      serialNumber=dbConn.getCheckOutSerialNumber();
1626
      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
1627 837 bojilova
                                    "WHERE server LIKE '" + server + "'");
1628 569 berkley
      pstmt.execute();
1629
      ResultSet rs = pstmt.getResultSet();
1630
      boolean tablehasrows = rs.next();
1631 2286 tao
      if ( tablehasrows ) {
1632 837 bojilova
        serverCode = rs.getInt(1);
1633 667 berkley
        pstmt.close();
1634 1217 tao
        //conn.close();
1635 837 bojilova
        return serverCode;
1636 569 berkley
      }
1637 2286 tao
1638 837 bojilova
    } catch(Exception e) {
1639
      throw e;
1640
1641
    } finally {
1642 2286 tao
      try
1643 1217 tao
      {
1644 667 berkley
        pstmt.close();
1645 1217 tao
        //conn.close();
1646
       }//try
1647 2286 tao
       catch(Exception ee)
1648 1217 tao
       {
1649 2663 sgarg
         logMetacat.error("Error in MetacatReplicatio.getServerCode: "
1650
                                  +ee.getMessage());
1651 2286 tao
1652 1217 tao
       }//catch
1653
       finally
1654
       {
1655
         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1656
       }//finally
1657
    }//finally
1658 2286 tao
1659 837 bojilova
    return serverCode;
1660 569 berkley
  }
1661 2286 tao
1662 569 berkley
  /**
1663 1292 tao
   * Method to get a host server information for given docid
1664
   * @param conn a connection to the database
1665
   */
1666
  public static Hashtable getHomeServerInfoForDocId(String docId)
1667
  {
1668
    Hashtable sl = new Hashtable();
1669
    DBConnection dbConn = null;
1670
    int serialNumber = -1;
1671
    //MetaCatUtil ut=new MetaCatUtil();
1672
    docId=MetaCatUtil.getDocIdFromString(docId);
1673
    PreparedStatement pstmt=null;
1674
    int serverLocation;
1675
    try
1676
    {
1677
      //get conection
1678
      dbConn=DBConnectionPool.
1679
                  getDBConnection("ReplicationHandler.getHomeServer");
1680
      serialNumber=dbConn.getCheckOutSerialNumber();
1681
      //get a server location from xml_document table
1682
      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
1683
                                            +"where docid = ?");
1684
      pstmt.setString(1, docId);
1685
      pstmt.execute();
1686
      ResultSet serverName = pstmt.getResultSet();
1687
      //get a server location
1688
      if(serverName.next())
1689
      {
1690
        serverLocation=serverName.getInt(1);
1691
        pstmt.close();
1692
      }
1693
      else
1694
      {
1695
        pstmt.close();
1696
        //ut.returnConnection(conn);
1697
        return null;
1698
      }
1699
      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
1700
                        "from xml_replication where serverid = ?");
1701
      //increase usage count
1702
      dbConn.increaseUsageCount(1);
1703
      pstmt.setInt(1, serverLocation);
1704
      pstmt.execute();
1705
      ResultSet rs = pstmt.getResultSet();
1706
      boolean tableHasRows = rs.next();
1707
      if (tableHasRows)
1708
      {
1709 2286 tao
1710 1292 tao
          String server = rs.getString(1);
1711
          String last_checked = rs.getString(2);
1712
          if(!server.equals("localhost"))
1713
          {
1714
            sl.put(server, last_checked);
1715
          }
1716 2286 tao
1717 1292 tao
      }
1718
      else
1719
      {
1720
        pstmt.close();
1721
        //ut.returnConnection(conn);
1722
        return null;
1723
      }
1724
      pstmt.close();
1725
    }
1726
    catch(Exception e)
1727
    {
1728
      System.out.println("error in replicationHandler.getHomeServer(): " +
1729
                         e.getMessage());
1730
    }
1731
    finally
1732
    {
1733
      try
1734
      {
1735
        pstmt.close();
1736
        //ut.returnConnection(conn);
1737
      }
1738
      catch (Exception ee)
1739
      {
1740 2663 sgarg
        logMetacat.error("Eror irn rplicationHandler.getHomeServer() "+
1741
                          "to close pstmt: "+ee.getMessage());
1742 1292 tao
      }
1743
      finally
1744
      {
1745
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1746
      }
1747 2286 tao
1748 1292 tao
    }//finally
1749
    return sl;
1750
  }
1751 2286 tao
1752 1292 tao
  /**
1753
   * Returns a home server location  given a accnum
1754
   * @param accNum , given accNum for a document
1755 2286 tao
   *
1756 1292 tao
   */
1757
  public static int getHomeServerCodeForDocId(String accNum) throws Exception
1758
  {
1759
    DBConnection dbConn = null;
1760
    int serialNumber = -1;
1761
    PreparedStatement pstmt = null;
1762
    int serverCode = 1;
1763
    //MetaCatUtil ut = new MetaCatUtil();
1764
    String docId=MetaCatUtil.getDocIdFromString(accNum);
1765
1766 2286 tao
    try
1767 1292 tao
    {
1768
1769
      // Get DBConnection
1770
      dbConn=DBConnectionPool.
1771
                  getDBConnection("ReplicationHandler.getServerLocation");
1772
      serialNumber=dbConn.getCheckOutSerialNumber();
1773 2286 tao
      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1774 1292 tao
                              + "WHERE docid LIKE '" + docId + "'");
1775
      pstmt.execute();
1776
      ResultSet rs = pstmt.getResultSet();
1777
      boolean tablehasrows = rs.next();
1778
      //If a document is find, return the server location for it
1779 2286 tao
      if ( tablehasrows )
1780
      {
1781 1292 tao
        serverCode = rs.getInt(1);
1782
        pstmt.close();
1783
        //conn.close();
1784
        return serverCode;
1785
      }
1786
      //if couldn't find in xml_documents table, we think server code is 1
1787
      //(this is new document)
1788
      else
1789
      {
1790
        pstmt.close();
1791
        //conn.close();
1792
        return serverCode;
1793
      }
1794 2286 tao
1795
    }
1796
    catch(Exception e)
1797 1292 tao
    {
1798 2286 tao
1799 1292 tao
      throw e;
1800
1801 2286 tao
    }
1802
    finally
1803 1292 tao
    {
1804 2286 tao
      try
1805 1292 tao
      {
1806
        pstmt.close();
1807
        //conn.close();
1808 2286 tao
1809
      }
1810
      catch(Exception ee)
1811 1292 tao
      {
1812 2663 sgarg
        logMetacat.error("Erorr in Replication.getServerLocation "+
1813
                     "to close pstmt"+ee.getMessage());
1814 1292 tao
      }
1815
      finally
1816
      {
1817
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1818
      }//finally
1819
    }//finally
1820
   //return serverCode;
1821
  }
1822 2286 tao
1823
1824
1825 1292 tao
  /**
1826 569 berkley
   * This method returns the content of a url
1827
   * @param u the url to return the content from
1828
   * @return a string representing the content of the url
1829
   * @throws java.io.IOException
1830
   */
1831
  public static String getURLContent(URL u) throws java.io.IOException
1832
  {
1833
    char istreamChar;
1834
    int istreamInt;
1835 2663 sgarg
    logMetacat.info("Before open the stream"+u.toString());
1836 1606 tao
    InputStream input = u.openStream();
1837 2663 sgarg
    logMetacat.info("Afetr open the stream"+u.toString());
1838 1606 tao
    InputStreamReader istream = new InputStreamReader(input);
1839 569 berkley
    StringBuffer serverResponse = new StringBuffer();
1840
    while((istreamInt = istream.read()) != -1)
1841
    {
1842
      istreamChar = (char)istreamInt;
1843
      serverResponse.append(istreamChar);
1844
    }
1845 1606 tao
    istream.close();
1846
    input.close();
1847 2286 tao
1848 569 berkley
    return serverResponse.toString();
1849
  }
1850 2286 tao
1851 584 berkley
  /**
1852 2286 tao
   * Method for writing replication messages to a log file specified in
1853 584 berkley
   * metacat.properties
1854
   */
1855
  public static void replLog(String message)
1856
  {
1857
    try
1858
    {
1859
      FileOutputStream fos = new FileOutputStream(
1860
                                 util.getOption("replicationlog"), true);
1861
      PrintWriter pw = new PrintWriter(fos);
1862
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1863
      java.util.Date localtime = new java.util.Date();
1864
      String dateString = formatter.format(localtime);
1865
      dateString += " :: " + message;
1866
      //time stamp each entry
1867
      pw.println(dateString);
1868
      pw.flush();
1869
    }
1870
    catch(Exception e)
1871
    {
1872 675 berkley
      System.out.println("error writing to replication log from " +
1873
                         "MetacatReplication.replLog: " + e.getMessage());
1874 595 berkley
      //e.printStackTrace(System.out);
1875 584 berkley
    }
1876
  }
1877 2286 tao
1878 629 berkley
  /**
1879 2286 tao
   * Method for writing replication messages to a log file specified in
1880 1583 tao
   * metacat.properties
1881
   */
1882
  public static void replErrorLog(String message)
1883
  {
1884
    try
1885
    {
1886
      FileOutputStream fos = new FileOutputStream(
1887
                                 util.getOption("replicationerrorlog"), true);
1888
      PrintWriter pw = new PrintWriter(fos);
1889
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1890
      java.util.Date localtime = new java.util.Date();
1891
      String dateString = formatter.format(localtime);
1892
      dateString += " :: " + message;
1893
      //time stamp each entry
1894
      pw.println(dateString);
1895
      pw.flush();
1896
    }
1897
    catch(Exception e)
1898
    {
1899
      System.out.println("error writing to replication log from " +
1900
                         "MetacatReplication.replLog: " + e.getMessage());
1901
      //e.printStackTrace(System.out);
1902
    }
1903
  }
1904 2286 tao
1905 1583 tao
  /**
1906 629 berkley
   * Returns true if the replicate field for server in xml_replication is 1.
1907
   * Returns false otherwise
1908
   */
1909
  public static boolean replToServer(String server)
1910
  {
1911 1217 tao
    DBConnection dbConn = null;
1912
    int serialNumber = -1;
1913 667 berkley
    PreparedStatement pstmt = null;
1914 629 berkley
    try
1915
    {
1916 1217 tao
      dbConn=DBConnectionPool.
1917
                  getDBConnection("MetacatReplication.repltoServer");
1918
      serialNumber=dbConn.getCheckOutSerialNumber();
1919 2286 tao
      pstmt = dbConn.prepareStatement("select replicate from " +
1920 667 berkley
                                    "xml_replication where server like '" +
1921
                                     server + "'");
1922 629 berkley
      pstmt.execute();
1923
      ResultSet rs = pstmt.getResultSet();
1924
      boolean tablehasrows = rs.next();
1925
      if(tablehasrows)
1926
      {
1927
        int i = rs.getInt(1);
1928
        if(i == 1)
1929
        {
1930 667 berkley
          pstmt.close();
1931 1217 tao
          //conn.close();
1932 629 berkley
          return true;
1933
        }
1934
        else
1935
        {
1936 667 berkley
          pstmt.close();
1937 1217 tao
          //conn.close();
1938 629 berkley
          return false;
1939
        }
1940
      }
1941
    }
1942
    catch(Exception e)
1943
    {
1944 2286 tao
      System.out.println("error in MetacatReplication.replToServer: " +
1945 675 berkley
                         e.getMessage());
1946 629 berkley
    }
1947 667 berkley
    finally
1948
    {
1949
      try
1950
      {
1951
        pstmt.close();
1952 1217 tao
        //conn.close();
1953
      }//try
1954 667 berkley
      catch(Exception ee)
1955 1217 tao
      {
1956 2663 sgarg
        logMetacat.error("Error in MetacatReplication.replToServer: "
1957
                                  +ee.getMessage());
1958 1217 tao
      }//catch
1959
      finally
1960
      {
1961
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1962
      }//finally
1963
    }//finally
1964 629 berkley
    return false;
1965
    //the default if this server does not exist is to not replicate to it.
1966
  }
1967 2286 tao
1968
1969 522 berkley
}