Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements replication for metacat
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: tao $'
10
 *     '$Date: 2005-09-09 13:10:00 -0700 (Fri, 09 Sep 2005) $'
11
 * '$Revision: 2586 $'
12
 *
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
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
31
import java.util.*;
32
import java.util.Date;
33
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

    
41
import org.xml.sax.*;
42

    
43
public class MetacatReplication extends HttpServlet implements Runnable
44
{
45
  private long timeInterval;
46
  private Date firstTime;
47
  private boolean timedReplicationIsOn = false;
48
  Timer replicationDaemon;
49
  private static MetaCatUtil util = new MetaCatUtil();
50
  private Vector fileLocks = new Vector();
51
  private Thread lockThread = null;
52
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
53
  public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
54
  private static final String TIMEREPLICATION = "timedreplication";
55
  private static final String TIMEREPLICATIONINTERVAl = "timedreplicationinterval";
56
  private static final String FIRSTTIME  = "firsttimedreplication";
57
  private static final int    TIMEINTERVALLIMIT = 7200000;
58
  
59
  /**
60
   * Initialize the servlet by creating appropriate database connections
61
   */
62
  public void init(ServletConfig config) throws ServletException
63
  {
64
     //initialize db connections to handle any update requests
65
    MetaCatUtil util = new MetaCatUtil();
66
    //deltaT = util.getOption("deltaT");
67
    //the default deltaT can be set from metacat.properties
68
    //create a thread to do the delta-T check but don't execute it yet
69
    replicationDaemon = new Timer(true);
70
    try
71
    {
72
       timedReplicationIsOn = (new Boolean(util.getOption(TIMEREPLICATION ).trim())).booleanValue();
73
       MetaCatUtil.debugMessage("The timed replication on is"+timedReplicationIsOn, 30);
74
       timeInterval = (new Long(util.getOption(TIMEREPLICATIONINTERVAl).trim())).longValue();
75
       MetaCatUtil.debugMessage("The timed replication time Inerval is "+ timeInterval, 20);
76
       String firstTimeStr = util.getOption(FIRSTTIME);
77
       MetaCatUtil.debugMessage("first replication time form property is "+firstTimeStr, 20);
78
       firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
79
       MetaCatUtil.debugMessage("After combine current time, the real first time is "
80
                                +firstTime.toString()+" minisec", 20);
81
       // set up time replication if it is on
82
       if (timedReplicationIsOn)
83
       {
84
           replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime, timeInterval);
85
           MetacatReplication.replLog("deltaT handler started with rate=" +
86
                   timeInterval + " mini seconds at " +firstTime.toString());
87
       }
88
    }
89
    catch (Exception e)
90
    {
91
        // the timed replication in Metacat.properties file has problem
92
        // so timed replication is setting to false;
93
        MetaCatUtil.debugMessage("Couldn't set up timed replication "+
94
                     " in Metacat replication servlet init because " +
95
                 e.getMessage(), 20);
96
        MetacatReplication.replErrorLog("Couldn't set up timed replication "+
97
                " in Metacat replication servlet init because " +
98
                e.getMessage());
99
        timedReplicationIsOn = false;
100
    }
101
    
102
  }
103

    
104
  public void destroy()
105
  {
106
    replicationDaemon.cancel();
107
   
108
  }
109

    
110
  public void doGet (HttpServletRequest request, HttpServletResponse response)
111
                     throws ServletException, IOException
112
  {
113
    // Process the data and send back the response
114
    handleGetOrPost(request, response);
115
  }
116

    
117
  public void doPost(HttpServletRequest request, HttpServletResponse response)
118
                     throws ServletException, IOException
119
  {
120
    // Process the data and send back the response
121
    handleGetOrPost(request, response);
122
  }
123

    
124
  private void handleGetOrPost(HttpServletRequest request,
125
                               HttpServletResponse response)
126
                               throws ServletException, IOException
127
  {
128
    //PrintWriter out = response.getWriter();
129
    //ServletOutputStream outPut = response.getOutputStream();
130
    Hashtable params = new Hashtable();
131
    Enumeration paramlist = request.getParameterNames();
132

    
133

    
134

    
135
// NOT NEEDED - doesn't provide enough security because of possible IP spoofing
136
// REPLACED with running replication comminications over HTTPS
137
//    String requestingServerIP = request.getRemoteAddr();
138
//    InetAddress iaddr = InetAddress.getByName(requestingServerIP);
139
//    String requestingServer = iaddr.getHostName();
140

    
141
    while (paramlist.hasMoreElements()) {
142
      String name = (String)paramlist.nextElement();
143
      String[] value = request.getParameterValues(name);
144
      params.put(name, value);
145
    }
146

    
147
    String action = ((String[])params.get("action"))[0];
148
    String server = null;
149

    
150
    try {
151
      // check if the server is included in the list of replicated servers
152
      if ( !action.equals("servercontrol") &&
153
           !action.equals("stop") &&
154
           !action.equals("start") &&
155
           !action.equals("getall") ) {
156

    
157
        server = ((String[])params.get("server"))[0];
158
        if ( getServerCodeForServerName(server) == 0 ) {
159
          System.out.println("Action \"" + action +
160
                             "\" rejected for server: " + server);
161
          return;
162
        } else {
163
          System.out.println("Action \"" + action +
164
                             "\" accepted for server: " + server);
165
        }
166
      }
167
      else
168
      {
169
          // start, stop, getall and servercontrol need to check
170
          // if user is administor
171
          HttpSession sess = request.getSession(true);
172
          String sess_id = "";
173
          String username = "";
174
          String[] groupnames = {""};
175
          Hashtable sessionHash = MetaCatServlet.getSessionHash();
176
          if (params.containsKey("sessionid")) 
177
          {
178
             sess_id = ((String[]) params.get("sessionid"))[0];
179
             MetaCatUtil.debugMessage("in has sessionid "+ sess_id, 40);
180
             if (sessionHash.containsKey(sess_id)) 
181
             {
182
                  MetaCatUtil.debugMessage("find the id " + sess_id + " in hash table", 40);
183
                  sess = (HttpSession) sessionHash.get(sess_id);
184
             }
185
           } 
186
           username = (String) sess.getAttribute("username");
187
           MetaCatUtil.debugMessage("The user name from session is: "+ username, 20);
188
           groupnames = (String[]) sess.getAttribute("groupnames");
189
           if (!MetaCatUtil.isAdministrator(username, groupnames)) 
190
           {
191
               PrintWriter out = response.getWriter();
192
               out.print("<error>");
193
               out.print("The user \"" + username +
194
                       "\" is not authorized for this action.");
195
               out.print("</error>");
196
               out.close();
197
               MetaCatUtil.debugMessage("The user \"" + username +
198
                       "\" is not authorized for this action: " +action, 30);
199
               replErrorLog("The user \"" + username +
200
                       "\" is not authorized for this action: " +action);
201
               return;
202
           }
203
                        
204
      }// this is final else
205
    } catch (Exception e) {
206
      System.out.println("Error in MetacatReplication.handleGetOrPost: " +
207
                         e.getMessage() );
208
      return;
209
    }
210
    
211
    if ( action.equals("readdata") )
212
    {
213
      OutputStream outStream = response.getOutputStream();
214
      //to get the data file.
215
      handleGetDataFileRequest(outStream, params, response);
216
      outStream.close();
217
    }
218
    else if ( action.equals("forcereplicatedatafile") )
219
    {
220
      //read a specific docid from remote host, and store it into local host
221
      handleForceReplicateDataFileRequest(params);
222

    
223
    }
224
    else
225
    {
226
    PrintWriter out = response.getWriter();
227
    if ( action.equals("stop") ) {
228
      //stop the replication server
229
      replicationDaemon.cancel();
230
      replicationDaemon = new Timer(true);
231
      timedReplicationIsOn = false;
232
      MetaCatUtil.setOption(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
233
      out.println("Replication Handler Stopped");
234
      MetacatReplication.replLog("deltaT handler stopped");
235

    
236

    
237
    } else if ( action.equals("start") ) {
238
       String firstTimeStr = "";
239
      //start the replication server
240
       if ( params.containsKey("rate") ) {
241
        timeInterval = new Long(
242
               new String(((String[])params.get("rate"))[0])).longValue();
243
        if(timeInterval < TIMEINTERVALLIMIT) {
244
            out.println("Replication deltaT rate cannot be less than "+
245
                    TIMEINTERVALLIMIT + " millisecs and system automatically setup the rate to "+TIMEINTERVALLIMIT);
246
            //deltaT<30 is a timing mess!
247
            timeInterval = TIMEINTERVALLIMIT;
248
        }
249
      } else {
250
        timeInterval = TIMEINTERVALLIMIT ;
251
      }
252
      MetaCatUtil.debugMessage("New rate is: " + timeInterval + " mini seconds.", 30);
253
      if ( params.containsKey("firsttime"))
254
      {
255
         firstTimeStr = ((String[])params.get("firsttime"))[0];
256
         try
257
         {
258
           firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
259
           MetaCatUtil.debugMessage("The first time setting is "+firstTime.toString(), 30);
260
         }
261
         catch (Exception e)
262
         {
263
            throw new ServletException(e.getMessage());
264
         }
265
         MetaCatUtil.debugMessage("After combine current time, the real first time is "
266
                                  +firstTime.toString()+" minisec", 20);
267
      }
268
      else
269
      {
270
          MetacatReplication.replErrorLog("You should specify the first time " +
271
                                          "to start a time replication");
272
          MetaCatUtil.debugMessage("You should specify the first time " +
273
                                  "to start a time replication", 30);
274
          return;
275
      }
276
      
277
      timedReplicationIsOn = true;
278
      // save settings to property file
279
      MetaCatUtil.setOption(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
280
      // note we couldn't use firstTime object because it has date info
281
      // we only need time info such as 10:00 PM
282
      MetaCatUtil.setOption(FIRSTTIME, firstTimeStr);
283
      MetaCatUtil.setOption(TIMEREPLICATIONINTERVAl, (new Long(timeInterval)).toString());
284
      replicationDaemon.cancel();
285
      replicationDaemon = new Timer(true);
286
      replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime,
287
                                            timeInterval);
288
      out.println("Replication Handler Started");
289
      MetacatReplication.replLog("deltaT handler started with rate=" +
290
                                    timeInterval + " milliseconds at " +firstTime.toString());
291

    
292

    
293
    } else if ( action.equals("getall") ) {
294
      //updates this server exactly once
295
      replicationDaemon.schedule(new ReplicationHandler(), 0);
296
      response.setContentType("text/html");
297
      out.println("<html><body>\"Get All\" Done</body></html>");
298

    
299
    } else if ( action.equals("forcereplicate") ) {
300
      //read a specific docid from remote host, and store it into local host
301
      handleForceReplicateRequest(out, params, response);
302

    
303
    } else if ( action.equals(FORCEREPLICATEDELETE) ) {
304
      //read a specific docid from remote host, and store it into local host
305
      handleForceReplicateDeleteRequest(out, params, response);
306

    
307
    } else if ( action.equals("update") ) {
308
      //request an update list from the server
309
      handleUpdateRequest(out, params, response);
310

    
311
    } else if ( action.equals("read") ) {
312
      //request a specific document from the server
313
      //note that this could be replaced by a call to metacatServlet
314
      //handleGetDocumentAction().
315
      handleGetDocumentRequest(out, params, response);
316
    } else if ( action.equals("getlock") ) {
317
      handleGetLockRequest(out, params, response);
318

    
319
    } else if ( action.equals("getdocumentinfo") ) {
320
      handleGetDocumentInfoRequest(out, params, response);
321

    
322
    } else if ( action.equals("gettime") ) {
323
      handleGetTimeRequest(out, params, response);
324

    
325
    } else if ( action.equals("getcatalog") ) {
326
      handleGetCatalogRequest(out, params, response, true);
327

    
328
    } else if ( action.equals("servercontrol") ) {
329
      handleServerControlRequest(out, params, response);
330
    } else if ( action.equals("test") ) {
331
      response.setContentType("text/html");
332
      out.println("<html><body>Test successfully</body></html>");
333
    }
334

    
335
    out.close();
336
    }//else
337
  }
338

    
339
  /**
340
   * This method can add, delete and list the servers currently included in
341
   * xml_replication.
342
   * action           subaction            other needed params
343
   * ---------------------------------------------------------
344
   * servercontrol    add                  server
345
   * servercontrol    delete               server
346
   * servercontrol    list
347
   */
348
  private void handleServerControlRequest(PrintWriter out, Hashtable params,
349
                                          HttpServletResponse response)
350
  {
351
    String subaction = ((String[])params.get("subaction"))[0];
352
    DBConnection dbConn = null;
353
    int serialNumber = -1;
354
    PreparedStatement pstmt = null;
355
    String replicate =null;
356
    String server = null;
357
    String dataReplicate = null;
358
    String hub = null;
359
    try {
360
      //conn = util.openDBConnection();
361
      dbConn=DBConnectionPool.
362
               getDBConnection("MetacatReplication.handleServerControlRequest");
363
      serialNumber=dbConn.getCheckOutSerialNumber();
364

    
365
      // add server to server list
366
      if ( subaction.equals("add") ) {
367
        replicate = ((String[])params.get("replicate"))[0];
368
        server = ((String[])params.get("server"))[0];
369

    
370
        //Get data replication value
371
        dataReplicate = ((String[])params.get("datareplicate"))[0];
372
        //Get hub value
373
        hub = ((String[])params.get("hub"))[0];
374

    
375
        /*pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
376
                  "(server, last_checked, replicate, datareplicate, hub) " +
377
                                      "VALUES ('" + server + "', to_date(" +
378
                                      "'01/01/00', 'MM/DD/YY'), '" +
379
                                      replicate +"', '" +dataReplicate+"', '"
380
                                      + hub +"')");*/
381
        pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
382
                  "(server, last_checked, replicate, datareplicate, hub) " +
383
                                      "VALUES ('" + server + "', "+
384
                                      dbAdapter.toDate("01/01/1980", "MM/DD/YYYY")
385
                                      + ", '" +
386
                                      replicate +"', '" +dataReplicate+"', '"
387
                                      + hub +"')");
388

    
389
        pstmt.execute();
390
        pstmt.close();
391
        dbConn.commit();
392
        out.println("Server " + server + " added");
393
        response.setContentType("text/html");
394
        out.println("<html><body><table border=\"1\">");
395
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
396
        out.println("<b>replicate</b></td>");
397
        out.println("<td><b>datareplicate</b></td>");
398
        out.println("<td><b>hub</b></td></tr>");
399
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
400
        //increase dbconnection usage
401
        dbConn.increaseUsageCount(1);
402

    
403
        pstmt.execute();
404
        ResultSet rs = pstmt.getResultSet();
405
        boolean tablehasrows = rs.next();
406
        while(tablehasrows) {
407
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
408
          out.println(rs.getString(3) + "</td><td>");
409
          out.println(rs.getString(4) + "</td><td>");
410
          out.println(rs.getString(5) + "</td><td>");
411
          out.println(rs.getString(6) + "</td></tr>");
412

    
413
          tablehasrows = rs.next();
414
        }
415
        out.println("</table></body></html>");
416

    
417
        // download certificate with the public key on this server
418
        // and import it as a trusted certificate
419
        String certURL = ((String[])params.get("certificate"))[0];
420
        downloadCertificate(certURL);
421

    
422
      // delete server from server list
423
      } else if ( subaction.equals("delete") ) {
424
        server = ((String[])params.get("server"))[0];
425
        pstmt = dbConn.prepareStatement("DELETE FROM xml_replication " +
426
                                      "WHERE server LIKE '" + server + "'");
427
        pstmt.execute();
428
        pstmt.close();
429
        dbConn.commit();
430
        out.println("Server " + server + " deleted");
431
        response.setContentType("text/html");
432
        out.println("<html><body><table border=\"1\">");
433
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
434
        out.println("<b>replicate</b></td>");
435
        out.println("<td><b>datareplicate</b></td>");
436
        out.println("<td><b>hub</b></td></tr>");
437

    
438
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
439
        //increase dbconnection usage
440
        dbConn.increaseUsageCount(1);
441
        pstmt.execute();
442
        ResultSet rs = pstmt.getResultSet();
443
        boolean tablehasrows = rs.next();
444
        while(tablehasrows)
445
        {
446
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
447
          out.println(rs.getString(3) + "</td><td>");
448
          out.println(rs.getString(4) + "</td><td>");
449
          out.println(rs.getString(5) + "</td><td>");
450
          out.println(rs.getString(6) + "</td></tr>");
451
          tablehasrows = rs.next();
452
        }
453
        out.println("</table></body></html>");
454

    
455
      // list servers in server list
456
      } else if ( subaction.equals("list") ) {
457
        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
        out.println("<b>replicate</b></td>");
461
        out.println("<td><b>datareplicate</b></td>");
462
        out.println("<td><b>hub</b></td></tr>");
463
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
464
        pstmt.execute();
465
        ResultSet rs = pstmt.getResultSet();
466
        boolean tablehasrows = rs.next();
467
        while(tablehasrows) {
468
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
469
          out.println(rs.getString(3) + "</td><td>");
470
          out.println(rs.getString(4) + "</td><td>");
471
          out.println(rs.getString(5) + "</td><td>");
472
          out.println(rs.getString(6) + "</td></tr>");
473
          tablehasrows = rs.next();
474
        }
475
        out.println("</table></body></html>");
476
      }
477
      else
478
      {
479

    
480
        out.println("<error>Unkonwn subaction</error>");
481

    
482
      }
483
      pstmt.close();
484
      //conn.close();
485

    
486
    } catch(Exception e) {
487
      System.out.println("Error in " +
488
                         "MetacatReplication.handleServerControlRequest " +
489
                         e.getMessage());
490
      e.printStackTrace(System.out);
491
    }
492
    finally
493
    {
494
      try
495
      {
496
        pstmt.close();
497
      }//try
498
      catch (SQLException ee)
499
      {
500
        MetaCatUtil.debugMessage("Error in " +
501
                "MetacatReplication.handleServerControlRequest to close pstmt "
502
                 + ee.getMessage(), 30);
503
      }//catch
504
      finally
505
      {
506
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
507
      }//finally
508
    }//finally
509

    
510
  }
511

    
512
  // download certificate with the public key from certURL and
513
  // upload it onto this server; it then must be imported as a
514
  // trusted certificate
515
  private void downloadCertificate (String certURL)
516
                throws FileNotFoundException, IOException, MalformedURLException
517
  {
518
    MetaCatUtil util = new MetaCatUtil();
519
    String certPath = util.getOption("certPath"); //the path to be uploaded to
520

    
521
    // get filename from the URL of the certificate
522
    String filename = certURL;
523
    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
524
    if ( slash > -1 ) {
525
      filename = filename.substring(slash + 1);
526
    }
527

    
528
    // open file output strem to write the input into it
529
    File f = new File(certPath, filename);
530
    synchronized (f) {
531
      try {
532
        if ( f.exists() ) {
533
          throw new IOException("File already exist: " + f.getCanonicalFile());
534
          //if ( f.exists() && !f.canWrite() ) {
535
          //  throw new IOException("Not writable: " + f.getCanonicalFile());
536
        }
537
      } catch (SecurityException se) {
538
        // if a security manager exists,
539
        // its checkRead method is called for f.exist()
540
        // or checkWrite method is called for f.canWrite()
541
        throw se;
542
      }
543

    
544
      // create a buffered byte output stream
545
      // that uses a default-sized output buffer
546
      FileOutputStream fos = new FileOutputStream(f);
547
      BufferedOutputStream out = new BufferedOutputStream(fos);
548

    
549
      // this should be http url
550
      URL url = new URL(certURL);
551
      BufferedInputStream bis = null;
552
      try {
553
        bis = new BufferedInputStream(url.openStream());
554
        byte[] buf = new byte[4 * 1024]; // 4K buffer
555
        int b = bis.read(buf);
556
        while (b != -1) {
557
          out.write(buf, 0, b);
558
          b = bis.read(buf);
559
        }
560
      } finally {
561
        if (bis != null) bis.close();
562
      }
563
      // the input and the output streams must be closed
564
      bis.close();
565
            out.flush();
566
            out.close();
567
            fos.close();
568
    } // end of synchronized(f)
569
  }
570

    
571
  /**
572
   * when a forcereplication request comes in, local host sends a read request
573
   * to the requesting server (remote server) for the specified docid.
574
   * Then store it in local database.
575
   */
576
  private void handleForceReplicateRequest(PrintWriter out, Hashtable params,
577
                                           HttpServletResponse response)
578
  {
579
    String server = ((String[])params.get("server"))[0]; // the server that
580
    String docid = ((String[])params.get("docid"))[0]; // sent the document
581
    String dbaction = "UPDATE"; // the default action is UPDATE
582
    boolean override = false;
583
    int serverCode = 1;
584
    DBConnection dbConn = null;
585
    int serialNumber = -1;
586

    
587
    try {
588
      //if the url contains a dbaction then the default action is overridden
589
      if(params.containsKey("dbaction")) {
590
        dbaction = ((String[])params.get("dbaction"))[0];
591
        //serverCode = MetacatReplication.getServerCode(server);
592
        //override = true; //we are now overriding the default action
593
      }
594
      MetacatReplication.replLog("force replication request from " + server);
595
      MetaCatUtil.debugMessage("Force replication request from: "+ server, 34);
596
      MetaCatUtil.debugMessage("Force replication docid: "+docid, 34);
597
      MetaCatUtil.debugMessage("Force replication action: "+dbaction, 34);
598
      // sending back read request to remote server
599
      URL u = new URL("https://" + server + "?server="
600
                +util.getLocalReplicationServerName()
601
                +"&action=read&docid=" + docid);
602
      String xmldoc = MetacatReplication.getURLContent(u);
603

    
604
      // get the document info from server
605
      URL docinfourl = new URL("https://" + server +
606
                               "?server="+util.getLocalReplicationServerName()
607
                               +"&action=getdocumentinfo&docid=" + docid);
608

    
609
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
610

    
611
      //dih is the parser for the docinfo xml format
612
      DocInfoHandler dih = new DocInfoHandler();
613
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
614
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
615
      Hashtable docinfoHash = dih.getDocInfo();
616

    
617
      // Get user owner of this docid
618
      String user = (String)docinfoHash.get("user_owner");
619
      // Get home server of this docid
620
      String homeServer=(String)docinfoHash.get("home_server");
621
      MetaCatUtil.debugMessage("homeServer: "+homeServer, 34);
622
      // Get Document type
623
      String docType = (String)docinfoHash.get("doctype");
624
      MetaCatUtil.debugMessage("docType: "+docType, 34);
625
      String parserBase = null;
626
      // this for eml2 and we need user eml2 parser
627
      if (docType != null &&
628
          (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
629
      {
630
         MetaCatUtil.debugMessage("This is an eml200 document!", 30);
631
         parserBase = DocumentImpl.EML200;
632
      }
633
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
634
      {
635
         MetaCatUtil.debugMessage("This is an eml2.0.1 document!", 30);
636
         parserBase = DocumentImpl.EML200;
637
      }
638
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
639
      {
640
         MetaCatUtil.debugMessage("This is an eml2.1.0 document!", 30);
641
         parserBase = DocumentImpl.EML210;
642
      }
643
      MetaCatUtil.debugMessage("The parserBase is: "+parserBase, 30);
644

    
645
      // Get DBConnection from pool
646
      dbConn=DBConnectionPool.
647
              getDBConnection("MetacatReplication.handleForceReplicateRequest");
648
      serialNumber=dbConn.getCheckOutSerialNumber();
649
      // write the document to local database
650
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
651
      wrapper.writeReplication(dbConn, new StringReader(xmldoc), null, null,
652
                               dbaction, docid, user, null, homeServer, server);
653

    
654
      MetacatReplication.replLog("document " + docid + " added to DB with " +
655
                                 "action " + dbaction);
656
    }//try
657
    catch(Exception e)
658
    {
659
      MetacatReplication.replErrorLog("document " + docid +
660
                                      " failed to added to DB with " +
661
                                      "action " + dbaction + " because "+
662
                                       e.getMessage());
663
      MetaCatUtil.debugMessage("ERROR in MetacatReplication.handleForceReplicate" +
664
                         "Request(): " + e.getMessage(), 30);
665

    
666
    }//catch
667
    finally
668
    {
669
      // Return the checked out DBConnection
670
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
671
    }//finally
672
  }
673

    
674
/*
675
 * when a forcereplication delete request comes in, local host will delete this
676
 * document
677
 */
678
private void handleForceReplicateDeleteRequest(PrintWriter out, Hashtable params,
679
                                         HttpServletResponse response)
680
{
681
  String server = ((String[])params.get("server"))[0]; // the server that
682
  String docid = ((String[])params.get("docid"))[0]; // sent the document
683
  try
684
  {
685
    MetacatReplication.replLog("force replication delete request from " + server);
686
    MetacatReplication.replLog("force replication delete docid " + docid);
687
    MetaCatUtil.debugMessage("Force replication delete request from: "+ server, 34);
688
    MetaCatUtil.debugMessage("Force replication delete docid: "+docid, 34);
689
    DocumentImpl.delete(docid, null, null, server);
690
    MetacatReplication.replLog("document " + docid + " was successfully deleted ");
691
    MetaCatUtil.debugMessage("document " + docid + " was successfully deleted ", 34);
692
  }
693
  catch(Exception e)
694
  {
695
    MetacatReplication.replErrorLog("document " + docid +
696
                                    " failed to delete because "+
697
                                     e.getMessage());
698
    MetaCatUtil.debugMessage("ERROR in MetacatReplication.handleForceDeleteReplicate" +
699
                       "Request(): " + e.getMessage(), 30);
700

    
701
  }//catch
702

    
703
}
704

    
705

    
706
  /**
707
   * when a forcereplication data file request comes in, local host sends a
708
   * readdata request to the requesting server (remote server) for the specified
709
   * docid. Then store it in local database and file system
710
   */
711
  private void handleForceReplicateDataFileRequest(Hashtable params)
712
  {
713

    
714
    //make sure there is some parameters
715
    if(params.isEmpty())
716
    {
717
      return;
718
    }
719
    // Get remote server
720
    String server = ((String[])params.get("server"))[0];
721
    // the docid should include rev number
722
    String docid = ((String[])params.get("docid"))[0];
723
    // Make sure there is a docid and server
724
    if (docid==null || server==null || server.equals(""))
725
    {
726
      MetaCatUtil.debugMessage("Didn't specify docid or server for replication"
727
                              , 20);
728
      return;
729
    }
730

    
731
    // Overide or not
732
    boolean override = false;
733
    // dbaction - update or insert
734
    String dbaction=null;
735

    
736
    try
737
    {
738
      //docid was switch to two parts uinque code and rev
739
      String uniqueCode=MetaCatUtil.getDocIdFromString(docid);
740
      int rev=MetaCatUtil.getVersionFromString(docid);
741
      if(params.containsKey("dbaction"))
742
      {
743
        dbaction = ((String[])params.get("dbaction"))[0];
744
      }
745
      else//default value is update
746
      {
747
        dbaction = "update";
748
      }
749

    
750
      MetacatReplication.replLog("force replication request from " + server);
751
      MetaCatUtil.debugMessage("Force replication request from: "+ server, 34);
752
      MetaCatUtil.debugMessage("Force replication docid: "+docid, 34);
753
      MetaCatUtil.debugMessage("Force replication action: "+dbaction, 34);
754
      // get the document info from server
755
      URL docinfourl = new URL("https://" + server +
756
                               "?server="+util.getLocalReplicationServerName()
757
                               +"&action=getdocumentinfo&docid=" + uniqueCode);
758

    
759
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
760

    
761
      //dih is the parser for the docinfo xml format
762
      DocInfoHandler dih = new DocInfoHandler();
763
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
764
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
765
      Hashtable docinfoHash = dih.getDocInfo();
766
      String user = (String)docinfoHash.get("user_owner");
767

    
768
      String docName = (String)docinfoHash.get("docname");
769

    
770
      String docType = (String)docinfoHash.get("doctype");
771

    
772
      String docHomeServer= (String)docinfoHash.get("home_server");
773
      MetaCatUtil.debugMessage("docHomeServer of datafile: "+docHomeServer, 34);
774

    
775

    
776

    
777
      //if action is delete, we don't delete the data file. Just archieve
778
      //the xml_documents
779
      /*if (dbaction.equals("delete"))
780
      {
781
        //conn = util.getConnection();
782
        DocumentImpl.delete(docid,user,null);
783
        //util.returnConnection(conn);
784
      }*/
785
      //To data file insert or update is same
786
      if (dbaction.equals("insert")||dbaction.equals("update"))
787
      {
788
        //Get data file and store it into local file system.
789
        // sending back readdata request to server
790
        URL url = new URL("https://" + server + "?server="
791
                +util.getLocalReplicationServerName()
792
                +"&action=readdata&docid=" + docid);
793
        String datafilePath = util.getOption("datafilepath");
794
        //register data file into xml_documents table and wite data file
795
        //into file system
796
        DocumentImpl.writeDataFileInReplication(url.openStream(), datafilePath,
797
                            docName, docType, docid, user,docHomeServer,server);
798
     }
799

    
800

    
801

    
802
    MetacatReplication.replLog("datafile " + docid + " added to DB with " +
803
                                 "action " + dbaction);
804
    }
805
    catch(Exception e)
806
    {
807

    
808
      MetacatReplication.replErrorLog("Datafile " + docid +
809
                                      " failed to added to DB with " +
810
                                      "action " + dbaction + " because "+
811
                                       e.getMessage());
812
      MetaCatUtil.debugMessage
813
              ("ERROR in MetacatReplication.handleForceDataFileReplicate" +
814
                         "Request(): " + e.getMessage(), 30);
815
    }
816
  }
817
  /**
818
   * Grants or denies a lock to a requesting host.
819
   * The servlet parameters of interrest are:
820
   * docid: the docid of the file the lock is being requested for
821
   * currentdate: the timestamp of the document on the remote server
822
   *
823
   */
824
  private void handleGetLockRequest(PrintWriter out, Hashtable params,
825
                                    HttpServletResponse response)
826
  {
827

    
828
    try
829
    {
830

    
831
      String docid = ((String[])params.get("docid"))[0];
832
      String remoteRev = ((String[])params.get("updaterev"))[0];
833
      DocumentImpl requestDoc = new DocumentImpl(docid);
834
      MetacatReplication.replLog("lock request for " + docid);
835
      int localRevInt = requestDoc.getRev();
836
      int remoteRevInt = Integer.parseInt(remoteRev);
837

    
838
      if(remoteRevInt >= localRevInt)
839
      {
840
        if(!fileLocks.contains(docid))
841
        { //grant the lock if it is not already locked
842
          fileLocks.add(0, docid); //insert at the beginning of the queue Vector
843
          //send a message back to the the remote host authorizing the insert
844
          out.println("<lockgranted><docid>" +docid+ "</docid></lockgranted>");
845
          lockThread = new Thread(this);
846
          lockThread.setPriority(Thread.MIN_PRIORITY);
847
          lockThread.start();
848
          MetacatReplication.replLog("lock granted for " + docid);
849
        }
850
        else
851
        { //deny the lock
852
          out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
853
          MetacatReplication.replLog("lock denied for " + docid +
854
                                     "reason: file already locked");
855
        }
856
      }
857
      else
858
      {//deny the lock.
859
        out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
860
        MetacatReplication.replLog("lock denied for " + docid +
861
                                   "reason: client has outdated file");
862
      }
863
      //conn.close();
864
    }
865
    catch(Exception e)
866
    {
867
      System.out.println("error requesting file lock from MetacatReplication." +
868
                         "handleGetLockRequest: " + e.getMessage());
869
      e.printStackTrace(System.out);
870
    }
871
  }
872

    
873
  /**
874
   * Sends all of the xml_documents information encoded in xml to a requestor
875
   * the format is:
876
   * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
877
   *                  user_updated, home_server, public_access, rev)/>
878
   * all of the subelements of document info are #PCDATA
879
   */
880
  private void handleGetDocumentInfoRequest(PrintWriter out, Hashtable params,
881
                                        HttpServletResponse response)
882
  {
883
    String docid = ((String[])(params.get("docid")))[0];
884
    StringBuffer sb = new StringBuffer();
885

    
886
    try
887
    {
888

    
889
      DocumentImpl doc = new DocumentImpl(docid);
890
      sb.append("<documentinfo><docid>").append(docid);
891
      sb.append("</docid><docname>").append(doc.getDocname());
892
      sb.append("</docname><doctype>").append(doc.getDoctype());
893
      sb.append("</doctype>");
894
      sb.append("<user_owner>").append(doc.getUserowner());
895
      sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
896
      sb.append("</user_updated>");
897
      sb.append("<home_server>");
898
      sb.append(doc.getDocHomeServer());
899
      sb.append("</home_server>");
900
      sb.append("<public_access>").append(doc.getPublicaccess());
901
      sb.append("</public_access><rev>").append(doc.getRev());
902
      sb.append("</rev></documentinfo>");
903
      response.setContentType("text/xml");
904
      out.println(sb.toString());
905

    
906
    }
907
    catch (Exception e)
908
    {
909
      System.out.println("error in " +
910
                         "metacatReplication.handlegetdocumentinforequest: " +
911
                          e.getMessage());
912
    }
913

    
914
  }
915

    
916
  /**
917
   * Sends a datafile to a remote host
918
   */
919
  private void handleGetDataFileRequest(OutputStream outPut,
920
                            Hashtable params, HttpServletResponse response)
921

    
922
  {
923
    // File path for data file
924
    String filepath = util.getOption("datafilepath");
925
    // Request docid
926
    String docId = ((String[])(params.get("docid")))[0];
927
    //check if the doicd is null
928
    if (docId==null)
929
    {
930
      util.debugMessage("Didn't specify docid for replication", 20);
931
      return;
932
    }
933

    
934
    //try to open a https stream to test if the request server's public key
935
    //in the key store, this is security issue
936
    try
937
    {
938
      String server = ((String[])params.get("server"))[0];
939
      URL u = new URL("https://" + server + "?server="
940
                +util.getLocalReplicationServerName()
941
                +"&action=test");
942
      String test = MetacatReplication.getURLContent(u);
943
      //couldn't pass the test
944
      if (test.indexOf("successfully")==-1)
945
      {
946
        //response.setContentType("text/xml");
947
        //outPut.println("<error>Couldn't pass the trust test</error>");
948
        MetaCatUtil.debugMessage("Couldn't pass the trust test", 20);
949
        return;
950
      }
951
    }//try
952
    catch (Exception ee)
953
    {
954
      return;
955
    }//catch
956

    
957
    if(!filepath.endsWith("/"))
958
    {
959
          filepath += "/";
960
    }
961
    // Get file aboslute file name
962
    String filename = filepath + docId;
963

    
964
    //MIME type
965
    String contentType = null;
966
    if (filename.endsWith(".xml"))
967
    {
968
        contentType="text/xml";
969
    }
970
    else if (filename.endsWith(".css"))
971
    {
972
        contentType="text/css";
973
    }
974
    else if (filename.endsWith(".dtd"))
975
    {
976
        contentType="text/plain";
977
    }
978
    else if (filename.endsWith(".xsd"))
979
    {
980
        contentType="text/xml";
981
    }
982
    else if (filename.endsWith("/"))
983
    {
984
        contentType="text/html";
985
    }
986
    else
987
    {
988
        File f = new File(filename);
989
        if ( f.isDirectory() )
990
        {
991
           contentType="text/html";
992
        }
993
        else
994
        {
995
           contentType="application/octet-stream";
996
        }
997
     }
998

    
999
   // Set the mime type
1000
   response.setContentType(contentType);
1001

    
1002
   // Get the content of the file
1003
   FileInputStream fin = null;
1004
   try
1005
   {
1006
      // FileInputStream to metacat
1007
      fin = new FileInputStream(filename);
1008
      // 4K buffer
1009
      byte[] buf = new byte[4 * 1024];
1010
      // Read data from file input stream to byte array
1011
      int b = fin.read(buf);
1012
      // Write to outStream from byte array
1013
      while (b != -1)
1014
      {
1015
        outPut.write(buf, 0, b);
1016
        b = fin.read(buf);
1017
      }
1018
      // close file input stream
1019
      fin.close();
1020

    
1021
   }//try
1022
   catch(Exception e)
1023
   {
1024
      System.out.println("error getting data file from MetacatReplication." +
1025
                         "handlGetDataFileRequest " + e.getMessage());
1026
      e.printStackTrace(System.out);
1027
   }//catch
1028

    
1029
}
1030

    
1031

    
1032
  /**
1033
   * Sends a document to a remote host
1034
   */
1035
  private void handleGetDocumentRequest(PrintWriter out, Hashtable params,
1036
                                        HttpServletResponse response)
1037
  {
1038

    
1039
    try
1040
    {
1041
      //try to open a https stream to test if the request server's public key
1042
      //in the key store, this is security issue
1043
      String server = ((String[])params.get("server"))[0];
1044
      URL u = new URL("https://" + server + "?server="
1045
                +util.getLocalReplicationServerName()
1046
                +"&action=test");
1047
      String test = MetacatReplication.getURLContent(u);
1048
      //couldn't pass the test
1049
      if (test.indexOf("successfully")==-1)
1050
      {
1051
        response.setContentType("text/xml");
1052
        out.println("<error>Couldn't pass the trust test</error>");
1053
        out.close();
1054
        return;
1055
      }
1056

    
1057
      String docid = ((String[])(params.get("docid")))[0];
1058

    
1059
      DocumentImpl di = new DocumentImpl(docid);
1060
      response.setContentType("text/xml");
1061
      out.print(di.toString(null, null, true));
1062

    
1063
      MetacatReplication.replLog("document " + docid + " sent");
1064

    
1065
    }
1066
    catch(Exception e)
1067
    {
1068
      MetaCatUtil.debugMessage("error getting document from MetacatReplication."
1069
                          +"handlGetDocumentRequest " + e.getMessage(), 30);
1070
      //e.printStackTrace(System.out);
1071
      response.setContentType("text/xml");
1072
      out.println("<error>"+e.getMessage()+"</error>");
1073
    }
1074

    
1075
  }
1076

    
1077
  /**
1078
   * Sends a list of all of the documents on this sever along with their
1079
   * revision numbers.
1080
   * The format is:
1081
   * <!ELEMENT replication (server, updates)>
1082
   * <!ELEMENT server (#PCDATA)>
1083
   * <!ELEMENT updates ((updatedDocument | deleteDocument)*)>
1084
   * <!ELEMENT updatedDocument (docid, rev, datafile*)>
1085
   * <!ELEMENT deletedDocument (docid, rev)>
1086
   * <!ELEMENT docid (#PCDATA)>
1087
   * <!ELEMENT rev (#PCDATA)>
1088
   * <!ELEMENT datafile (#PCDATA)>
1089
   * note that the rev in deletedDocument is always empty.  I just left
1090
   * it in there to make the parser implementation easier.
1091
   */
1092
  private void handleUpdateRequest(PrintWriter out, Hashtable params,
1093
                                    HttpServletResponse response)
1094
  {
1095
    // Checked out DBConnection
1096
    DBConnection dbConn = null;
1097
    // DBConenction serial number when checked it out
1098
    int serialNumber = -1;
1099
    PreparedStatement pstmt = null;
1100
    // Server list to store server info of xml_replication table
1101
    ReplicationServerList serverList = null;
1102

    
1103
    try
1104
    {
1105
      // Check out a DBConnection from pool
1106
      dbConn=DBConnectionPool.
1107
                  getDBConnection("MetacatReplication.handleUpdateRequest");
1108
      serialNumber=dbConn.getCheckOutSerialNumber();
1109
      // Create a server list from xml_replication table
1110
      serverList = new ReplicationServerList();
1111

    
1112
      // Get remote server name from param
1113
      String server = ((String[])params.get("server"))[0];
1114
      // If no servr name in param, return a error
1115
      if ( server == null || server.equals(""))
1116
      {
1117
        response.setContentType("text/xml");
1118
        out.println("<error>Request didn't specify server name</error>");
1119
        out.close();
1120
        return;
1121
      }//if
1122

    
1123
      //try to open a https stream to test if the request server's public key
1124
      //in the key store, this is security issue
1125
      URL u = new URL("https://" + server + "?server="
1126
                +util.getLocalReplicationServerName()
1127
                +"&action=test");
1128
      String test = MetacatReplication.getURLContent(u);
1129
      //couldn't pass the test
1130
      if (test.indexOf("successfully")==-1)
1131
      {
1132
        response.setContentType("text/xml");
1133
        out.println("<error>Couldn't pass the trust test</error>");
1134
        out.close();
1135
        return;
1136
      }
1137

    
1138

    
1139
      // Check if local host configure to replicate xml documents to remote
1140
      // server. If not send back a error message
1141
      if (!serverList.getReplicationValue(server))
1142
      {
1143
        response.setContentType("text/xml");
1144
        out.println
1145
        ("<error>Configuration not allow to replicate document to you</error>");
1146
        out.close();
1147
        return;
1148
      }//if
1149

    
1150
      // Store the sql command
1151
      StringBuffer docsql = new StringBuffer();
1152
      // Stroe the docid list
1153
      StringBuffer doclist = new StringBuffer();
1154
      // Store the deleted docid list
1155
      StringBuffer delsql = new StringBuffer();
1156
      // Store the data set file
1157
      Vector packageFiles = new Vector();
1158

    
1159
      // Append local server's name and replication servlet to doclist
1160
      doclist.append("<?xml version=\"1.0\"?><replication>");
1161
      doclist.append("<server>").append(util.getLocalReplicationServerName());
1162
      //doclist.append(util.getOption("replicationpath"));
1163
      doclist.append("</server><updates>");
1164

    
1165
      // Get correct docid that reside on this server according the requesting
1166
      // server's replicate and data replicate value in xml_replication table
1167
      docsql.append("select docid, rev, doctype from xml_documents ");
1168
      // If the localhost is not a hub to the remote server, only replicate
1169
      // the docid' which home server is local host (server_location =1)
1170
      if (!serverList.getHubValue(server))
1171
      {
1172
        docsql.append("where server_location = 1");
1173
      }
1174
      MetaCatUtil.debugMessage("Doc sql: "+docsql.toString(), 30);
1175

    
1176
      // Get any deleted documents
1177
      delsql.append("select distinct docid from ");
1178
      delsql.append("xml_revisions where docid not in (select docid from ");
1179
      delsql.append("xml_documents) ");
1180
      // If the localhost is not a hub to the remote server, only replicate
1181
      // the docid' which home server is local host (server_location =1)
1182
      if (!serverList.getHubValue(server))
1183
      {
1184
        delsql.append("and server_location = 1");
1185
      }
1186
      MetaCatUtil.debugMessage("Deleted sql: "+delsql.toString(), 30);
1187

    
1188

    
1189

    
1190
      // Get docid list of local host
1191
      pstmt = dbConn.prepareStatement(docsql.toString());
1192
      pstmt.execute();
1193
      ResultSet rs = pstmt.getResultSet();
1194
      boolean tablehasrows = rs.next();
1195
      //If metacat configed to replicate data file
1196
      //if ((util.getOption("replicationsenddata")).equals("on"))
1197
      if (serverList.getDataReplicationValue(server))
1198
      {
1199
        while(tablehasrows)
1200
        {
1201
          String recordDoctype = rs.getString(3);
1202
          Vector packagedoctypes = MetaCatUtil.getOptionList(
1203
                                     MetaCatUtil.getOption("packagedoctype"));
1204
          //if this is a package file, put it at the end
1205
          //because if a package file is read before all of the files it
1206
          //refers to are loaded then there is an error
1207
          if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1208
          {
1209
              //If this is not data file
1210
              if (!recordDoctype.equals("BIN"))
1211
              {
1212
                //for non-data file document
1213
                doclist.append("<updatedDocument>");
1214
                doclist.append("<docid>").append(rs.getString(1));
1215
                doclist.append("</docid><rev>").append(rs.getInt(2));
1216
                doclist.append("</rev>");
1217
                doclist.append("</updatedDocument>");
1218
              }//if
1219
              else
1220
              {
1221
                //for data file document, in datafile attributes
1222
                //we put "datafile" value there
1223
                doclist.append("<updatedDocument>");
1224
                doclist.append("<docid>").append(rs.getString(1));
1225
                doclist.append("</docid><rev>").append(rs.getInt(2));
1226
                doclist.append("</rev>");
1227
                doclist.append("<datafile>");
1228
                doclist.append(MetaCatUtil.getOption("datafileflag"));
1229
                doclist.append("</datafile>");
1230
                doclist.append("</updatedDocument>");
1231
              }//else
1232
          }//if packagedoctpes
1233
          else
1234
          { //the package files are saved to be put into the xml later.
1235
              Vector v = new Vector();
1236
              v.add(new String(rs.getString(1)));
1237
              v.add(new Integer(rs.getInt(2)));
1238
              packageFiles.add(new Vector(v));
1239
          }//esle
1240
          tablehasrows = rs.next();
1241
        }//while
1242
      }//if
1243
      else //metacat was configured not to send data file
1244
      {
1245
        while(tablehasrows)
1246
        {
1247
          String recordDoctype = rs.getString(3);
1248
          if(!recordDoctype.equals("BIN"))
1249
          { //don't replicate data files
1250
            Vector packagedoctypes = MetaCatUtil.getOptionList(
1251
                                     MetaCatUtil.getOption("packagedoctype"));
1252
            if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1253
            {   //if this is a package file, put it at the end
1254
              //because if a package file is read before all of the files it
1255
              //refers to are loaded then there is an error
1256
              doclist.append("<updatedDocument>");
1257
              doclist.append("<docid>").append(rs.getString(1));
1258
              doclist.append("</docid><rev>").append(rs.getInt(2));
1259
              doclist.append("</rev>");
1260
              doclist.append("</updatedDocument>");
1261
            }
1262
            else
1263
            { //the package files are saved to be put into the xml later.
1264
              Vector v = new Vector();
1265
              v.add(new String(rs.getString(1)));
1266
              v.add(new Integer(rs.getInt(2)));
1267
              packageFiles.add(new Vector(v));
1268
            }
1269
         }//if
1270
         tablehasrows = rs.next();
1271
        }//while
1272
      }//else
1273

    
1274
      pstmt = dbConn.prepareStatement(delsql.toString());
1275
      //usage count should increas 1
1276
      dbConn.increaseUsageCount(1);
1277

    
1278
      pstmt.execute();
1279
      rs = pstmt.getResultSet();
1280
      tablehasrows = rs.next();
1281
      while(tablehasrows)
1282
      { //handle the deleted documents
1283
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1284
        doclist.append("</docid><rev></rev></deletedDocument>");
1285
        //note that rev is always empty for deleted docs
1286
        tablehasrows = rs.next();
1287
      }
1288

    
1289
      //now we can put the package files into the xml results
1290
      for(int i=0; i<packageFiles.size(); i++)
1291
      {
1292
        Vector v = (Vector)packageFiles.elementAt(i);
1293
        doclist.append("<updatedDocument>");
1294
        doclist.append("<docid>").append((String)v.elementAt(0));
1295
        doclist.append("</docid><rev>");
1296
        doclist.append(((Integer)v.elementAt(1)).intValue());
1297
        doclist.append("</rev>");
1298
        doclist.append("</updatedDocument>");
1299
      }
1300

    
1301
      doclist.append("</updates></replication>");
1302
      MetaCatUtil.debugMessage("doclist: " + doclist.toString(), 40);
1303
      pstmt.close();
1304
      //conn.close();
1305
      response.setContentType("text/xml");
1306
      out.println(doclist.toString());
1307

    
1308
    }
1309
    catch(Exception e)
1310
    {
1311
      MetaCatUtil.debugMessage("error in MetacatReplication." +
1312
                         "handleupdaterequest: " + e.getMessage(), 30);
1313
      //e.printStackTrace(System.out);
1314
      response.setContentType("text/xml");
1315
      out.println("<error>"+e.getMessage()+"</error>");
1316
    }
1317
    finally
1318
    {
1319
      try
1320
      {
1321
        pstmt.close();
1322
      }//try
1323
      catch (SQLException ee)
1324
      {
1325
        MetaCatUtil.debugMessage("Error in MetacatReplication." +
1326
                "handleUpdaterequest to close pstmt: "+ee.getMessage(), 30);
1327
      }//catch
1328
      finally
1329
      {
1330
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1331
      }//finally
1332
    }//finally
1333

    
1334
  }//handlUpdateRequest
1335

    
1336
  /**
1337
   * Returns the xml_catalog table encoded in xml
1338
   */
1339
  public static String getCatalogXML()
1340
  {
1341
    return handleGetCatalogRequest(null, null, null, false);
1342
  }
1343

    
1344
  /**
1345
   * Sends the contents of the xml_catalog table encoded in xml
1346
   * The xml format is:
1347
   * <!ELEMENT xml_catalog (row*)>
1348
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1349
   *                system_id)>
1350
   * All of the sub elements of row are #PCDATA
1351

    
1352
   * If printFlag == false then do not print to out.
1353
   */
1354
  private static String handleGetCatalogRequest(PrintWriter out,
1355
                                                Hashtable params,
1356
                                                HttpServletResponse response,
1357
                                                boolean printFlag)
1358
  {
1359
    DBConnection dbConn = null;
1360
    int serialNumber = -1;
1361
    PreparedStatement pstmt = null;
1362
    try
1363
    {
1364
      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1365
                                                "handleGetCatalogRequest");*/
1366
      dbConn=DBConnectionPool.
1367
                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
1368
      serialNumber=dbConn.getCheckOutSerialNumber();
1369
      pstmt = dbConn.prepareStatement("select entry_type, " +
1370
                              "source_doctype, target_doctype, public_id, " +
1371
                              "system_id from xml_catalog");
1372
      pstmt.execute();
1373
      ResultSet rs = pstmt.getResultSet();
1374
      boolean tablehasrows = rs.next();
1375
      StringBuffer sb = new StringBuffer();
1376
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1377
      while(tablehasrows)
1378
      {
1379
        sb.append("<row><entry_type>").append(rs.getString(1));
1380
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1381
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1382
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1383
        sb.append("</public_id><system_id>").append(rs.getString(5));
1384
        sb.append("</system_id></row>");
1385

    
1386
        tablehasrows = rs.next();
1387
      }
1388
      sb.append("</xml_catalog>");
1389
      //conn.close();
1390
      if(printFlag)
1391
      {
1392
        response.setContentType("text/xml");
1393
        out.println(sb.toString());
1394
      }
1395
      pstmt.close();
1396
      return sb.toString();
1397
    }
1398
    catch(Exception e)
1399
    {
1400

    
1401
      System.out.println("error in MetacatReplication.handleGetCatalogRequest:"+
1402
                          e.getMessage());
1403
      e.printStackTrace(System.out);
1404
      if(printFlag)
1405
      {
1406
        out.println("<error>"+e.getMessage()+"</error>");
1407
      }
1408
    }
1409
    finally
1410
    {
1411
      try
1412
      {
1413
        pstmt.close();
1414
      }//try
1415
      catch (SQLException ee)
1416
      {
1417
        MetaCatUtil.
1418
           debugMessage("Error in MetacatReplication.handleGetCatalogRequest: "
1419
           +ee.getMessage(), 30);
1420
      }//catch
1421
      finally
1422
      {
1423
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1424
      }//finally
1425
    }//finally
1426

    
1427
    return null;
1428
  }
1429

    
1430
  /**
1431
   * Sends the current system date to the remote server.  Using this action
1432
   * for replication gets rid of any problems with syncronizing clocks
1433
   * because a time specific to a document is always kept on its home server.
1434
   */
1435
  private void handleGetTimeRequest(PrintWriter out, Hashtable params,
1436
                                    HttpServletResponse response)
1437
  {
1438
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
1439
    java.util.Date localtime = new java.util.Date();
1440
    String dateString = formatter.format(localtime);
1441
    response.setContentType("text/xml");
1442

    
1443
    out.println("<timestamp>" + dateString + "</timestamp>");
1444
  }
1445

    
1446
  /**
1447
   * this method handles the timeout for a file lock.  when a lock is
1448
   * granted it is granted for 30 seconds.  When this thread runs out
1449
   * it deletes the docid from the queue, thus eliminating the lock.
1450
   */
1451
  public void run()
1452
  {
1453
    try
1454
    {
1455
      MetaCatUtil.debugMessage("thread started for docid: " +
1456
                               (String)fileLocks.elementAt(0), 45);
1457

    
1458
      Thread.sleep(30000); //the lock will expire in 30 seconds
1459
      MetaCatUtil.debugMessage("thread for docid: " +
1460
                             (String)fileLocks.elementAt(fileLocks.size() - 1) +
1461
                              " exiting.", 45);
1462

    
1463
      fileLocks.remove(fileLocks.size() - 1);
1464
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1465
      //in the vector, the first one inserted will be removed.
1466
    }
1467
    catch(Exception e)
1468
    {
1469
      MetaCatUtil.debugMessage("error in file lock thread from " +
1470
                                "MetacatReplication.run: " + e.getMessage(), 30);
1471
    }
1472
  }
1473

    
1474
  /**
1475
   * Returns the name of a server given a serverCode
1476
   * @param serverCode the serverid of the server
1477
   * @return the servername or null if the specified serverCode does not
1478
   *         exist.
1479
   */
1480
  public static String getServerNameForServerCode(int serverCode)
1481
  {
1482
    //System.out.println("serverid: " + serverCode);
1483
    DBConnection dbConn = null;
1484
    int serialNumber = -1;
1485
    PreparedStatement pstmt = null;
1486
    try
1487
    {
1488
      dbConn=DBConnectionPool.
1489
                  getDBConnection("MetacatReplication.getServer");
1490
      serialNumber=dbConn.getCheckOutSerialNumber();
1491
      String sql = new String("select server from " +
1492
                              "xml_replication where serverid = " +
1493
                              serverCode);
1494
      pstmt = dbConn.prepareStatement(sql);
1495
      //System.out.println("getserver sql: " + sql);
1496
      pstmt.execute();
1497
      ResultSet rs = pstmt.getResultSet();
1498
      boolean tablehasrows = rs.next();
1499
      if(tablehasrows)
1500
      {
1501
        //System.out.println("server: " + rs.getString(1));
1502
        return rs.getString(1);
1503
      }
1504

    
1505
      //conn.close();
1506
    }
1507
    catch(Exception e)
1508
    {
1509
      System.out.println("Error in MetacatReplication.getServer: " +
1510
                          e.getMessage());
1511
    }
1512
    finally
1513
    {
1514
      try
1515
      {
1516
        pstmt.close();
1517
      }//try
1518
      catch (SQLException ee)
1519
      {
1520
        MetaCatUtil.debugMessage("Error in MetacactReplication.getserver: "+
1521
                                    ee.getMessage(), 30);
1522
      }//catch
1523
      finally
1524
      {
1525
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1526
      }//fianlly
1527
    }//finally
1528

    
1529

    
1530

    
1531
    return null;
1532
      //return null if the server does not exist
1533
  }
1534

    
1535
  /**
1536
   * Returns a server code given a server name
1537
   * @param server the name of the server
1538
   * @return integer > 0 representing the code of the server, 0 if the server
1539
   *  does not exist.
1540
   */
1541
  public static int getServerCodeForServerName(String server) throws Exception
1542
  {
1543
    DBConnection dbConn = null;
1544
    int serialNumber = -1;
1545
    PreparedStatement pstmt = null;
1546
    int serverCode = 0;
1547

    
1548
    try {
1549

    
1550
      //conn = util.openDBConnection();
1551
      dbConn=DBConnectionPool.
1552
                  getDBConnection("MetacatReplication.getServerCode");
1553
      serialNumber=dbConn.getCheckOutSerialNumber();
1554
      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
1555
                                    "WHERE server LIKE '" + server + "'");
1556
      pstmt.execute();
1557
      ResultSet rs = pstmt.getResultSet();
1558
      boolean tablehasrows = rs.next();
1559
      if ( tablehasrows ) {
1560
        serverCode = rs.getInt(1);
1561
        pstmt.close();
1562
        //conn.close();
1563
        return serverCode;
1564
      }
1565

    
1566
    } catch(Exception e) {
1567
      throw e;
1568

    
1569
    } finally {
1570
      try
1571
      {
1572
        pstmt.close();
1573
        //conn.close();
1574
       }//try
1575
       catch(Exception ee)
1576
       {
1577
         MetaCatUtil.debugMessage("Error in MetacatReplicatio.getServerCode: "
1578
                                  +ee.getMessage(), 30);
1579

    
1580
       }//catch
1581
       finally
1582
       {
1583
         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1584
       }//finally
1585
    }//finally
1586

    
1587
    return serverCode;
1588
  }
1589

    
1590
  /**
1591
   * Method to get a host server information for given docid
1592
   * @param conn a connection to the database
1593
   */
1594
  public static Hashtable getHomeServerInfoForDocId(String docId)
1595
  {
1596
    Hashtable sl = new Hashtable();
1597
    DBConnection dbConn = null;
1598
    int serialNumber = -1;
1599
    //MetaCatUtil ut=new MetaCatUtil();
1600
    docId=MetaCatUtil.getDocIdFromString(docId);
1601
    PreparedStatement pstmt=null;
1602
    int serverLocation;
1603
    try
1604
    {
1605
      //get conection
1606
      dbConn=DBConnectionPool.
1607
                  getDBConnection("ReplicationHandler.getHomeServer");
1608
      serialNumber=dbConn.getCheckOutSerialNumber();
1609
      //get a server location from xml_document table
1610
      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
1611
                                            +"where docid = ?");
1612
      pstmt.setString(1, docId);
1613
      pstmt.execute();
1614
      ResultSet serverName = pstmt.getResultSet();
1615
      //get a server location
1616
      if(serverName.next())
1617
      {
1618
        serverLocation=serverName.getInt(1);
1619
        pstmt.close();
1620
      }
1621
      else
1622
      {
1623
        pstmt.close();
1624
        //ut.returnConnection(conn);
1625
        return null;
1626
      }
1627
      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
1628
                        "from xml_replication where serverid = ?");
1629
      //increase usage count
1630
      dbConn.increaseUsageCount(1);
1631
      pstmt.setInt(1, serverLocation);
1632
      pstmt.execute();
1633
      ResultSet rs = pstmt.getResultSet();
1634
      boolean tableHasRows = rs.next();
1635
      if (tableHasRows)
1636
      {
1637

    
1638
          String server = rs.getString(1);
1639
          String last_checked = rs.getString(2);
1640
          if(!server.equals("localhost"))
1641
          {
1642
            sl.put(server, last_checked);
1643
          }
1644

    
1645
      }
1646
      else
1647
      {
1648
        pstmt.close();
1649
        //ut.returnConnection(conn);
1650
        return null;
1651
      }
1652
      pstmt.close();
1653
    }
1654
    catch(Exception e)
1655
    {
1656
      System.out.println("error in replicationHandler.getHomeServer(): " +
1657
                         e.getMessage());
1658
    }
1659
    finally
1660
    {
1661
      try
1662
      {
1663
        pstmt.close();
1664
        //ut.returnConnection(conn);
1665
      }
1666
      catch (Exception ee)
1667
      {
1668
        MetaCatUtil.debugMessage("Eror irn rplicationHandler.getHomeServer() "+
1669
                          "to close pstmt: "+ee.getMessage(), 30);
1670
      }
1671
      finally
1672
      {
1673
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1674
      }
1675

    
1676
    }//finally
1677
    return sl;
1678
  }
1679

    
1680
  /**
1681
   * Returns a home server location  given a accnum
1682
   * @param accNum , given accNum for a document
1683
   *
1684
   */
1685
  public static int getHomeServerCodeForDocId(String accNum) throws Exception
1686
  {
1687
    DBConnection dbConn = null;
1688
    int serialNumber = -1;
1689
    PreparedStatement pstmt = null;
1690
    int serverCode = 1;
1691
    //MetaCatUtil ut = new MetaCatUtil();
1692
    String docId=MetaCatUtil.getDocIdFromString(accNum);
1693

    
1694
    try
1695
    {
1696

    
1697
      // Get DBConnection
1698
      dbConn=DBConnectionPool.
1699
                  getDBConnection("ReplicationHandler.getServerLocation");
1700
      serialNumber=dbConn.getCheckOutSerialNumber();
1701
      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1702
                              + "WHERE docid LIKE '" + docId + "'");
1703
      pstmt.execute();
1704
      ResultSet rs = pstmt.getResultSet();
1705
      boolean tablehasrows = rs.next();
1706
      //If a document is find, return the server location for it
1707
      if ( tablehasrows )
1708
      {
1709
        serverCode = rs.getInt(1);
1710
        pstmt.close();
1711
        //conn.close();
1712
        return serverCode;
1713
      }
1714
      //if couldn't find in xml_documents table, we think server code is 1
1715
      //(this is new document)
1716
      else
1717
      {
1718
        pstmt.close();
1719
        //conn.close();
1720
        return serverCode;
1721
      }
1722

    
1723
    }
1724
    catch(Exception e)
1725
    {
1726

    
1727
      throw e;
1728

    
1729
    }
1730
    finally
1731
    {
1732
      try
1733
      {
1734
        pstmt.close();
1735
        //conn.close();
1736

    
1737
      }
1738
      catch(Exception ee)
1739
      {
1740
        MetaCatUtil.debugMessage("Erorr in Replication.getServerLocation "+
1741
                     "to close pstmt"+ee.getMessage(), 30);
1742
      }
1743
      finally
1744
      {
1745
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1746
      }//finally
1747
    }//finally
1748
   //return serverCode;
1749
  }
1750

    
1751

    
1752

    
1753
  /**
1754
   * This method returns the content of a url
1755
   * @param u the url to return the content from
1756
   * @return a string representing the content of the url
1757
   * @throws java.io.IOException
1758
   */
1759
  public static String getURLContent(URL u) throws java.io.IOException
1760
  {
1761
    char istreamChar;
1762
    int istreamInt;
1763
    MetaCatUtil.debugMessage("Before open the stream"+u.toString(), 50);
1764
    InputStream input = u.openStream();
1765
    MetaCatUtil.debugMessage("Afetr open the stream"+u.toString(), 50);
1766
    InputStreamReader istream = new InputStreamReader(input);
1767
    StringBuffer serverResponse = new StringBuffer();
1768
    while((istreamInt = istream.read()) != -1)
1769
    {
1770
      istreamChar = (char)istreamInt;
1771
      serverResponse.append(istreamChar);
1772
    }
1773
    istream.close();
1774
    input.close();
1775

    
1776
    return serverResponse.toString();
1777
  }
1778

    
1779
  /**
1780
   * Method for writing replication messages to a log file specified in
1781
   * metacat.properties
1782
   */
1783
  public static void replLog(String message)
1784
  {
1785
    try
1786
    {
1787
      FileOutputStream fos = new FileOutputStream(
1788
                                 util.getOption("replicationlog"), true);
1789
      PrintWriter pw = new PrintWriter(fos);
1790
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1791
      java.util.Date localtime = new java.util.Date();
1792
      String dateString = formatter.format(localtime);
1793
      dateString += " :: " + message;
1794
      //time stamp each entry
1795
      pw.println(dateString);
1796
      pw.flush();
1797
    }
1798
    catch(Exception e)
1799
    {
1800
      System.out.println("error writing to replication log from " +
1801
                         "MetacatReplication.replLog: " + e.getMessage());
1802
      //e.printStackTrace(System.out);
1803
    }
1804
  }
1805

    
1806
  /**
1807
   * Method for writing replication messages to a log file specified in
1808
   * metacat.properties
1809
   */
1810
  public static void replErrorLog(String message)
1811
  {
1812
    try
1813
    {
1814
      FileOutputStream fos = new FileOutputStream(
1815
                                 util.getOption("replicationerrorlog"), true);
1816
      PrintWriter pw = new PrintWriter(fos);
1817
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1818
      java.util.Date localtime = new java.util.Date();
1819
      String dateString = formatter.format(localtime);
1820
      dateString += " :: " + message;
1821
      //time stamp each entry
1822
      pw.println(dateString);
1823
      pw.flush();
1824
    }
1825
    catch(Exception e)
1826
    {
1827
      System.out.println("error writing to replication log from " +
1828
                         "MetacatReplication.replLog: " + e.getMessage());
1829
      //e.printStackTrace(System.out);
1830
    }
1831
  }
1832

    
1833
  /**
1834
   * Returns true if the replicate field for server in xml_replication is 1.
1835
   * Returns false otherwise
1836
   */
1837
  public static boolean replToServer(String server)
1838
  {
1839
    DBConnection dbConn = null;
1840
    int serialNumber = -1;
1841
    PreparedStatement pstmt = null;
1842
    try
1843
    {
1844
      dbConn=DBConnectionPool.
1845
                  getDBConnection("MetacatReplication.repltoServer");
1846
      serialNumber=dbConn.getCheckOutSerialNumber();
1847
      pstmt = dbConn.prepareStatement("select replicate from " +
1848
                                    "xml_replication where server like '" +
1849
                                     server + "'");
1850
      pstmt.execute();
1851
      ResultSet rs = pstmt.getResultSet();
1852
      boolean tablehasrows = rs.next();
1853
      if(tablehasrows)
1854
      {
1855
        int i = rs.getInt(1);
1856
        if(i == 1)
1857
        {
1858
          pstmt.close();
1859
          //conn.close();
1860
          return true;
1861
        }
1862
        else
1863
        {
1864
          pstmt.close();
1865
          //conn.close();
1866
          return false;
1867
        }
1868
      }
1869
    }
1870
    catch(Exception e)
1871
    {
1872
      System.out.println("error in MetacatReplication.replToServer: " +
1873
                         e.getMessage());
1874
    }
1875
    finally
1876
    {
1877
      try
1878
      {
1879
        pstmt.close();
1880
        //conn.close();
1881
      }//try
1882
      catch(Exception ee)
1883
      {
1884
        MetaCatUtil.debugMessage("Error in MetacatReplication.replToServer: "
1885
                                  +ee.getMessage(), 30);
1886
      }//catch
1887
      finally
1888
      {
1889
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1890
      }//finally
1891
    }//finally
1892
    return false;
1893
    //the default if this server does not exist is to not replicate to it.
1894
  }
1895

    
1896

    
1897
}
(44-44/63)