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