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: 2002-05-08 09:28:49 -0700 (Wed, 08 May 2002) $'
11
 * '$Revision: 1061 $'
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 java.util.*;
31
import java.io.*;
32
import java.sql.*;
33
import java.net.*;
34
import java.lang.*;
35
import java.text.*;
36
import javax.servlet.*;
37
import javax.servlet.http.*;
38

    
39
import org.xml.sax.*;
40

    
41
public class MetacatReplication extends HttpServlet implements Runnable
42
{  
43
  private String deltaT;
44
  Timer replicationDaemon;
45
  private static MetaCatUtil util = new MetaCatUtil();
46
  private Vector fileLocks = new Vector();
47
  private Thread lockThread = null;
48
  
49
  /**
50
   * Initialize the servlet by creating appropriate database connections
51
   */
52
  public void init(ServletConfig config) throws ServletException 
53
  {
54
    //initialize db connections to handle any update requests
55
    MetaCatUtil util = new MetaCatUtil();
56
    deltaT = util.getOption("deltaT");
57
    //the default deltaT can be set from metacat.properties
58
    //create a thread to do the delta-T check but don't execute it yet
59
    replicationDaemon = new Timer(true);
60
  }
61
  
62
  public void destroy() 
63
  {
64
    replicationDaemon.cancel();
65
   // System.out.println("Replication daemon cancelled.");
66
  }
67
  
68
  public void doGet (HttpServletRequest request, HttpServletResponse response)
69
                     throws ServletException, IOException 
70
  {
71
    // Process the data and send back the response
72
    handleGetOrPost(request, response);
73
  }
74

    
75
  public void doPost(HttpServletRequest request, HttpServletResponse response)
76
                     throws ServletException, IOException 
77
  {
78
    // Process the data and send back the response
79
    handleGetOrPost(request, response);
80
  }
81
  
82
  private void handleGetOrPost(HttpServletRequest request, 
83
                               HttpServletResponse response) 
84
                               throws ServletException, IOException 
85
  {
86
    //PrintWriter out = response.getWriter();
87
    //ServletOutputStream outPut = response.getOutputStream();
88
    Hashtable params = new Hashtable();
89
    Enumeration paramlist = request.getParameterNames();
90
    
91
    //First check if administrate conifgure the replcation feature on
92
    //This configuration is set in build.xml file
93
    //If it is not on, reject any request.
94
    if (!(util.getOption("replication")).equals("on"))
95
    {
96
     (response.getWriter()).println("MetaCat is not set to handle replication");
97
      (response.getWriter()).close();
98
      return;
99
    }
100
    
101
// NOT NEEDED - doesn't provide enough security because of possible IP spoofing
102
// REPLACED with running replication comminications over HTTPS
103
//    String requestingServerIP = request.getRemoteAddr();
104
//    InetAddress iaddr = InetAddress.getByName(requestingServerIP);
105
//    String requestingServer = iaddr.getHostName();
106
    
107
    while (paramlist.hasMoreElements()) {
108
      String name = (String)paramlist.nextElement();
109
      String[] value = request.getParameterValues(name);
110
      params.put(name, value);  
111
    }
112
    
113
    String action = ((String[])params.get("action"))[0];
114
    String server = null;
115
    
116
    try {
117
      // check if the server is included in the list of replicated servers
118
      if ( !action.equals("servercontrol") && 
119
           !action.equals("stop") &&
120
           !action.equals("start") &&
121
           !action.equals("getall") ) {
122

    
123
        server = ((String[])params.get("server"))[0];
124
        if ( getServerCode(server) == 0 ) {
125
          System.out.println("Action \"" + action + 
126
                             "\" rejected for server: " + server);
127
          return;
128
        } else {
129
          System.out.println("Action \"" + action + 
130
                             "\" accepted for server: " + server);
131
        }
132
      }
133
    } catch (Exception e) {
134
      System.out.println("Error in MetacatReplication.handleGetOrPost: " +
135
                         e.getMessage() );
136
      return;
137
    }
138
    if ( action.equals("readdata") ) 
139
    {
140
      OutputStream out=response.getOutputStream();
141
      //to get the data file.
142
      handleGetDataFileRequest(out, params, response);
143
      out.close();
144
    }
145
    else if ( action.equals("forcereplicatedatafile") ) 
146
    {
147
     
148
      //OutputStream out=response.getOutputStream();
149
      //read a specific docid from remote host, and store it into local host
150
      handleForceReplicateDataFileRequest(params);
151
      //out.close();
152
    }
153
    else
154
    {
155
    PrintWriter out = response.getWriter();
156
    if ( action.equals("stop") ) {
157
      //stop the replication server
158
      replicationDaemon.cancel();
159
      replicationDaemon = new Timer(true);
160
      out.println("Replication Handler Stopped");
161
      MetacatReplication.replLog("deltaT handler stopped");
162
    
163

    
164
    } else if ( action.equals("start") ) {
165
      
166
      //start the replication server
167
      int rate;
168
      if ( params.containsKey("rate") ) {
169
        rate = new Integer(
170
               new String(((String[])params.get("rate"))[0])).intValue();
171
        if(rate < 30) {
172
            out.println("Replication deltaT rate cannot be less than 30!");
173
            //deltaT<30 is a timing mess!
174
            rate = 1000;
175
        }
176
      } else {
177
        rate = 1000;
178
      }
179
      out.println("New rate is: " + rate + " seconds.");
180
      replicationDaemon.cancel();
181
      replicationDaemon = new Timer(true);
182
      replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(out), 0, 
183
                                            rate * 1000);
184
      out.println("Replication Handler Started");
185
      MetacatReplication.replLog("deltaT handler started with rate=" + 
186
                                    rate + " seconds");
187
     
188

    
189
    } else if ( action.equals("getall") ) {
190
      //updates this server exactly once
191
      replicationDaemon.schedule(new ReplicationHandler(out), 0);
192
      response.setContentType("text/html");
193
      out.println("<html><body>\"Get All\" Done</body></html>");
194

    
195
    } else if ( action.equals("forcereplicate") ) {
196
      //read a specific docid from remote host, and store it into local host
197
      handleForceReplicateRequest(out, params, response);
198
   
199
    } else if ( action.equals("update") ) {
200
      //request an update list from the server
201
      handleUpdateRequest(out, params, response);
202

    
203
    } else if ( action.equals("read") ) {
204
      //request a specific document from the server
205
      //note that this could be replaced by a call to metacatServlet
206
      //handleGetDocumentAction().
207
      handleGetDocumentRequest(out, params, response);
208
    } else if ( action.equals("getlock") ) {
209
      handleGetLockRequest(out, params, response);
210

    
211
    } else if ( action.equals("getdocumentinfo") ) {
212
      handleGetDocumentInfoRequest(out, params, response);
213

    
214
    } else if ( action.equals("gettime") ) {
215
      handleGetTimeRequest(out, params, response);
216

    
217
    } else if ( action.equals("getcatalog") ) {
218
      handleGetCatalogRequest(out, params, response, true);
219

    
220
    } else if ( action.equals("servercontrol") ) {
221
      handleServerControlRequest(out, params, response);
222
    }
223
    
224
    out.close();
225
    }//else
226
  }
227
  
228
  /** 
229
   * This method can add, delete and list the servers currently included in
230
   * xml_replication.
231
   * action           subaction            other needed params
232
   * ---------------------------------------------------------
233
   * servercontrol    add                  server
234
   * servercontrol    delete               server
235
   * servercontrol    list                 
236
   */
237
  private void handleServerControlRequest(PrintWriter out, Hashtable params,
238
                                          HttpServletResponse response)
239
  {
240
    String subaction = ((String[])params.get("subaction"))[0];
241
    Connection conn = null;
242

    
243
    try {
244
      conn = util.openDBConnection();
245
      PreparedStatement pstmt = null;
246

    
247
      // add server to server list
248
      if ( subaction.equals("add") ) {
249
        String replicate = ((String[])params.get("replicate"))[0];
250
        String server = ((String[])params.get("server"))[0];
251
        pstmt = conn.prepareStatement("INSERT INTO xml_replication " +
252
                                      "(server, last_checked, replicate) " +
253
                                      "VALUES ('" + server + "', to_date(" +
254
                                      "'01/01/00', 'MM/DD/YY'), '" +
255
                                      replicate + "')");
256
        pstmt.execute();
257
        pstmt.close();
258
        conn.commit();
259
        out.println("Server " + server + " added"); 
260
        response.setContentType("text/html");
261
        out.println("<html><body><table border=\"1\">");
262
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
263
        out.println("<b>replicate</b></td></tr>");
264
        pstmt = conn.prepareStatement("SELECT * FROM xml_replication");
265
        pstmt.execute();
266
        ResultSet rs = pstmt.getResultSet();
267
        boolean tablehasrows = rs.next();
268
        while(tablehasrows) {
269
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
270
          out.println(rs.getString(3) + "</td><td>");
271
          out.println(rs.getString(4) + "</td></tr>");
272
          tablehasrows = rs.next();
273
        }
274
        out.println("</table></body></html>");
275
        
276
        // download certificate with the public key on this server
277
        // and import it as a trusted certificate
278
        String certURL = ((String[])params.get("certificate"))[0];
279
        downloadCertificate(certURL);
280
        
281
      // delete server from server list
282
      } else if ( subaction.equals("delete") ) {
283
        String server = ((String[])params.get("server"))[0];
284
        pstmt = conn.prepareStatement("DELETE FROM xml_replication " +
285
                                      "WHERE server LIKE '" + server + "'");
286
        pstmt.execute();
287
        pstmt.close();
288
        conn.commit();
289
        out.println("Server " + server + " deleted");
290
        response.setContentType("text/html");
291
        out.println("<html><body><table border=\"1\">");
292
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
293
        out.println("<b>replicate</b></td></tr>");
294
        pstmt = conn.prepareStatement("SELECT * FROM xml_replication");
295
        pstmt.execute();
296
        ResultSet rs = pstmt.getResultSet();
297
        boolean tablehasrows = rs.next();
298
        while(tablehasrows)
299
        {
300
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
301
          out.println(rs.getString(3) + "</td><td>");
302
          out.println(rs.getString(4) + "</td></tr>");
303
          tablehasrows = rs.next();
304
        }
305
        out.println("</table></body></html>");
306

    
307
      // list servers in server list
308
      } else if ( subaction.equals("list") ) {
309
        response.setContentType("text/html");
310
        out.println("<html><body><table border=\"1\">");
311
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
312
        out.println("<b>replicate</b></td></tr>");
313
        pstmt = conn.prepareStatement("SELECT * FROM xml_replication");
314
        pstmt.execute();
315
        ResultSet rs = pstmt.getResultSet();
316
        boolean tablehasrows = rs.next();
317
        while(tablehasrows) {
318
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
319
          out.println(rs.getString(3) + "</td><td>");
320
          out.println(rs.getString(4) + "</td></tr>");
321
          tablehasrows = rs.next();
322
        }
323
        out.println("</table></body></html>");
324
      }
325
      pstmt.close();
326
      conn.close();
327

    
328
    } catch(Exception e) {
329
      System.out.println("Error in " + 
330
                         "MetacatReplication.handleServerControlRequest " + 
331
                         e.getMessage());
332
      e.printStackTrace(System.out);
333
    }
334
  }
335
  
336
  // download certificate with the public key from certURL and 
337
  // upload it onto this server; it then must be imported as a 
338
  // trusted certificate 
339
  private void downloadCertificate (String certURL)
340
                throws FileNotFoundException, IOException, MalformedURLException
341
  {
342
    MetaCatUtil util = new MetaCatUtil();
343
    String certPath = util.getOption("certPath"); //the path to be uploaded to
344
    
345
    // get filename from the URL of the certificate
346
    String filename = certURL;
347
    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
348
    if ( slash > -1 ) {
349
      filename = filename.substring(slash + 1);
350
    }
351
    
352
    // open file output strem to write the input into it
353
    File f = new File(certPath, filename);
354
    synchronized (f) { 
355
      try {
356
        if ( f.exists() ) {
357
          throw new IOException("File already exist: " + f.getCanonicalFile());
358
          //if ( f.exists() && !f.canWrite() ) {
359
          //  throw new IOException("Not writable: " + f.getCanonicalFile());
360
        }
361
      } catch (SecurityException se) {
362
        // if a security manager exists,
363
        // its checkRead method is called for f.exist()
364
        // or checkWrite method is called for f.canWrite()
365
        throw se;
366
      }
367
      
368
      // create a buffered byte output stream
369
      // that uses a default-sized output buffer
370
      FileOutputStream fos = new FileOutputStream(f);
371
      BufferedOutputStream out = new BufferedOutputStream(fos);
372

    
373
      // this should be http url
374
      URL url = new URL(certURL);
375
      BufferedInputStream bis = null;
376
      try {
377
        bis = new BufferedInputStream(url.openStream());
378
        byte[] buf = new byte[4 * 1024]; // 4K buffer
379
        int b = bis.read(buf);
380
        while (b != -1) {
381
          out.write(buf, 0, b);
382
          b = bis.read(buf);
383
        }
384
      } finally {
385
        if (bis != null) bis.close();
386
      }
387
      // the input and the output streams must be closed
388
      bis.close();
389
	    out.flush();
390
	    out.close();
391
	    fos.close();
392
    } // end of synchronized(f)
393
  }
394
  
395
  /**
396
   * when a forcereplication request comes in, local host sends a read request
397
   * to the requesting server (remote server) for the specified docid.
398
   * Then store it in local database.
399
   */
400
  private void handleForceReplicateRequest(PrintWriter out, Hashtable params,
401
                                           HttpServletResponse response)
402
  {
403
    String server = ((String[])params.get("server"))[0]; // the server that
404
    String docid = ((String[])params.get("docid"))[0]; // sent the document
405
    String dbaction = "UPDATE"; // the default action is UPDATE
406
    boolean override = false;
407
    int serverCode = 1;
408
   
409
    try {
410
      //if the url contains a dbaction then the default action is overridden
411
      if(params.containsKey("dbaction")) {
412
        dbaction = ((String[])params.get("dbaction"))[0];
413
        //serverCode = MetacatReplication.getServerCode(server);
414
        //override = true; //we are now overriding the default action
415
      }
416
      MetacatReplication.replLog("force replication request from " + server); 
417
      util.debugMessage("Force replication docid: "+docid, 20);
418
      util.debugMessage("Force replication action: "+dbaction, 20);
419
      // sending back read request to server
420
     
421
      URL u = new URL("https://" + server + "?server="
422
                +util.getLocalReplicationServerName()
423
                +"&action=read&docid=" + docid);
424
      String xmldoc = MetacatReplication.getURLContent(u);
425
    
426
      // get the document info from server
427
      URL docinfourl = new URL("https://" + server + 
428
                               "?server="+util.getLocalReplicationServerName()
429
                               +"&action=getdocumentinfo&docid=" + docid);
430
    
431
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
432
  
433
      //dih is the parser for the docinfo xml format
434
      DocInfoHandler dih = new DocInfoHandler();
435
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
436
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
437
      Hashtable docinfoHash = dih.getDocInfo();
438
      String user = (String)docinfoHash.get("user_owner");
439
      
440
      String homeServer=(String)docinfoHash.get("home_server");
441
      util.debugMessage("homeServer: "+homeServer,20);
442
      // write the document here
443
      Connection conn = util.openDBConnection();
444
      DocumentImpl.writeReplication(conn, new StringReader(xmldoc), null, null,
445
              dbaction, docid, user, null, homeServer, true);
446
              
447
       
448
      conn.close();
449

    
450
      MetacatReplication.replLog("document " + docid + " added to DB with " +
451
                                 "action " + dbaction);
452
    } catch(Exception e) {
453
      
454
      System.out.println("ERROR in MetacatReplication.handleForceReplicate" +
455
                         "Request(): " + e.getMessage());
456
       e.printStackTrace();
457
    }
458
  }
459
  
460
  /**
461
   * when a forcereplication data file request comes in, local host sends a 
462
   * readdata request to the requesting server (remote server) for the specified 
463
   * docid. Then store it in local database and file system
464
   */
465
  private void handleForceReplicateDataFileRequest(Hashtable params)
466
  {
467
    //check if the metacat was configured to handle replication 
468
    if (!(util.getOption("replicationdata")).equals("on"))
469
    {
470
      return;
471
    }
472
    //make sure there is some parameters
473
    if(params.isEmpty())
474
    {
475
      return;
476
    }
477
    String server = ((String[])params.get("server"))[0]; // the server that
478
    //docid should include rev number
479
    String docid = ((String[])params.get("docid"))[0]; // sent the document
480
    if (docid==null)
481
    {
482
      util.debugMessage("Didn't specify docid for replication", 10);
483
      return;
484
    }
485
    //docid was switch to two parts
486
    boolean override = false;
487
    int serverCode = 1;
488
    String dbaction=null;
489
    Connection conn=null;
490
    
491
    try 
492
    {
493
      //docid was switch to two parts
494
      String uniqueCode=MetaCatUtil.getDocIdFromString(docid);
495
      int rev=MetaCatUtil.getVersionFromString(docid);
496
      if(params.containsKey("dbaction")) 
497
      {
498
        dbaction = ((String[])params.get("dbaction"))[0];
499
      }
500
      else//default value is update
501
      {
502
        dbaction = "update";
503
      }
504
      serverCode = MetacatReplication.getServerCode(server);
505
      MetacatReplication.replLog("force replication request from " + server); 
506
      
507
      // get the document info from server
508
      URL docinfourl = new URL("https://" + server + 
509
                               "?server="+util.getLocalReplicationServerName()
510
                               +"&action=getdocumentinfo&docid=" + uniqueCode);
511
     
512
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
513

    
514
      //dih is the parser for the docinfo xml format
515
      DocInfoHandler dih = new DocInfoHandler();
516
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
517
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
518
      Hashtable docinfoHash = dih.getDocInfo();
519
      String user = (String)docinfoHash.get("user_owner");
520
     
521
      String docName = (String)docinfoHash.get("docname");
522
     
523
      String docType = (String)docinfoHash.get("doctype");
524
     
525
      
526
      conn = util.getConnection();
527
      
528
      //if action is delete, we don't delete the data file. Just archieve
529
      //the xml_documents
530
      if (dbaction.equals("delete"))
531
      {
532
        DocumentImpl.delete(conn,docid,user,null);
533
      }
534
      //To data file insert or update is same
535
      else if (dbaction.equals("insert")||dbaction.equals("update"))
536
      {
537
        //Get data file and store it into local file system.
538
        // sending back readdata request to server
539
        URL url = new URL("https://" + server + "?server="
540
                +util.getLocalReplicationServerName()
541
                +"&action=readdata&docid=" + docid);
542
        String datafilePath = util.getOption("datafilepath");
543
        //register data file into xml_documents table and wite data file
544
        //into file system
545
        DocumentImpl.writeDataFile(url.openStream(), datafilePath, docName,
546
                              docType, docid, user,serverCode);
547
     }
548
    
549
    util.returnConnection(conn);
550
    
551
    MetacatReplication.replLog("document " + docid + " added to DB with " +
552
                                 "action " + dbaction);
553
    } catch(Exception e) 
554
    {
555
      try
556
      {
557
        conn.close();
558
      }
559
      catch (SQLException sqlE)
560
      {
561
        util.debugMessage(sqlE.getMessage());
562
      }
563
      System.out.println("ERROR in MetacatReplication.handleForceReplicate" +
564
                         "Request(): " + e.getMessage());
565
    }
566
  }
567
  /**
568
   * Grants or denies a lock to a requesting host.
569
   * The servlet parameters of interrest are:
570
   * docid: the docid of the file the lock is being requested for
571
   * currentdate: the timestamp of the document on the remote server
572
   * 
573
   */
574
  private void handleGetLockRequest(PrintWriter out, Hashtable params,
575
                                    HttpServletResponse response)
576
  {
577
    Connection conn = null;
578
    try
579
    {
580
      conn = MetacatReplication.getDBConnection("MetacatReplication." +
581
                                                "handleGetLockRequest");
582
      String docid = ((String[])params.get("docid"))[0];
583
      String remoteRev = ((String[])params.get("updaterev"))[0];
584
      DocumentImpl requestDoc = new DocumentImpl(conn, docid);
585
      MetacatReplication.replLog("lock request for " + docid);
586
      int localRevInt = requestDoc.getRev();
587
      int remoteRevInt = Integer.parseInt(remoteRev);
588
      
589
      if(remoteRevInt >= localRevInt)
590
      {
591
        if(!fileLocks.contains(docid))
592
        { //grant the lock if it is not already locked
593
          fileLocks.add(0, docid); //insert at the beginning of the queue Vector
594
          //send a message back to the the remote host authorizing the insert
595
          out.println("<lockgranted><docid>" +docid+ "</docid></lockgranted>");
596
          lockThread = new Thread(this);
597
          lockThread.setPriority(Thread.MIN_PRIORITY);
598
          lockThread.start();
599
          MetacatReplication.replLog("lock granted for " + docid);
600
        }
601
        else
602
        { //deny the lock
603
          out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
604
          MetacatReplication.replLog("lock denied for " + docid + 
605
                                     "reason: file already locked");
606
        }
607
      }
608
      else
609
      {//deny the lock.
610
        out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
611
        MetacatReplication.replLog("lock denied for " + docid + 
612
                                   "reason: client has outdated file");
613
      }
614
      conn.close();
615
    }
616
    catch(Exception e)
617
    {
618
      System.out.println("error requesting file lock from MetacatReplication." +
619
                         "handleGetLockRequest: " + e.getMessage());
620
      e.printStackTrace(System.out);
621
    }
622
  }
623
  
624
  /**
625
   * Sends all of the xml_documents information encoded in xml to a requestor
626
   * the format is:
627
   * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
628
   *                  user_updated, home_server, public_access, rev)/>
629
   * all of the subelements of document info are #PCDATA
630
   */
631
  private void handleGetDocumentInfoRequest(PrintWriter out, Hashtable params, 
632
                                        HttpServletResponse response)
633
  {
634
    String docid = ((String[])(params.get("docid")))[0];
635
    StringBuffer sb = new StringBuffer();
636
    Connection conn = null;
637
    try
638
    {
639
      conn = MetacatReplication.getDBConnection("MetacatReplication." +
640
                                                "handleGetDocumentInfoRequest");
641
      DocumentImpl doc = new DocumentImpl(conn, docid);
642
      sb.append("<documentinfo><docid>").append(docid);
643
      sb.append("</docid><docname>").append(doc.getDocname());
644
      sb.append("</docname><doctype>").append(doc.getDoctype());
645
      sb.append("</doctype>");
646
      sb.append("<user_owner>").append(doc.getUserowner());
647
      sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
648
      sb.append("</user_updated>");
649
      sb.append("<home_server>");
650
      sb.append(doc.getDocHomeServer());
651
      sb.append("</home_server>");
652
      sb.append("<public_access>").append(doc.getPublicaccess());
653
      sb.append("</public_access><rev>").append(doc.getRev());
654
      sb.append("</rev></documentinfo>");
655
      response.setContentType("text/xml");
656
      out.println(sb.toString());
657
      conn.close();
658
    }
659
    catch (Exception e)
660
    {
661
      System.out.println("error in " +
662
                         "metacatReplication.handlegetdocumentinforequest: " + 
663
                          e.getMessage());
664
    }
665
    
666
  }
667
   
668
  /**
669
   * Sends a datafile to a remote host
670
   */
671
  private void handleGetDataFileRequest(OutputStream outPut, 
672
                            Hashtable params, HttpServletResponse response)
673
                                 
674
  {
675
    //check the metacat was configured to handle data replication
676
    if (!(util.getOption("replicationdata")).equals("on"))
677
    {
678
      return;
679
    }
680
    
681
    String filepath = util.getOption("datafilepath");
682
    String docId = ((String[])(params.get("docid")))[0];
683
    //check if the doicd is null
684
    if (docId==null)
685
    {
686
      util.debugMessage("Didn't specify docid for replication");
687
      return;
688
    }
689
  
690
    if(!filepath.endsWith("/")) 
691
    {
692
          filepath += "/";
693
    }
694
    String filename = filepath + docId;      //MIME type
695
    
696
    String contentType = null;//getServletContext().getMimeType(filename);
697
   
698
    if (contentType == null) 
699
    {
700
       if (filename.endsWith(".xml")) 
701
       {
702
          contentType="text/xml";
703
       } 
704
       else if (filename.endsWith(".css")) 
705
       {
706
          contentType="text/css";
707
       } 
708
       else if (filename.endsWith(".dtd")) 
709
       {
710
          contentType="text/plain";
711
       } 
712
       else if (filename.endsWith(".xsd")) 
713
       {
714
          contentType="text/xml";
715
       } 
716
       else if (filename.endsWith("/")) 
717
       {
718
          contentType="text/html";
719
       } 
720
       else 
721
       {
722
          File f = new File(filename);
723
          if ( f.isDirectory() ) 
724
          {
725
             contentType="text/html";
726
          } 
727
          else
728
          {
729
             contentType="application/octet-stream";
730
          }
731
       }
732
   }
733
  
734
   response.setContentType(contentType);
735
   // if we decide to use "application/octet-stream" for all data returns
736
   // response.setContentType("application/octet-stream");
737
   FileInputStream fin = null;
738
   try 
739
   {
740
      
741
      fin = new FileInputStream(filename);
742
      
743
      byte[] buf = new byte[4 * 1024]; // 4K buffer
744
      int b = fin.read(buf);
745
      while (b != -1) 
746
      {
747
        
748
        outPut.write(buf, 0, b);
749
        b = fin.read(buf);
750
      }
751
    
752
      fin.close();
753
   
754
   }  
755
   catch(Exception e)
756
   {
757
      System.out.println("error getting data file from MetacatReplication." +
758
                         "handlGetDataFileRequest " + e.getMessage());
759
      e.printStackTrace(System.out);
760
   }
761
  
762
}
763
  
764
  
765
  /**
766
   * Sends a document to a remote host
767
   */
768
  private void handleGetDocumentRequest(PrintWriter out, Hashtable params, 
769
                                        HttpServletResponse response)
770
  {
771
    Connection conn = null;
772
    try
773
    {
774
      String docid = ((String[])(params.get("docid")))[0];
775
      conn = MetacatReplication.getDBConnection("MetacatReplication." +
776
                                                "handleGetDocumentRequest");
777
      DocumentImpl di = new DocumentImpl(conn, docid);
778
      response.setContentType("text/xml");
779
      out.print(di.toString());
780
      conn.close();
781
      MetacatReplication.replLog("document " + docid + " sent");
782
    
783
    }
784
    catch(Exception e)
785
    {
786
      System.out.println("error getting document from MetacatReplication." +
787
                         "handlGetDocumentRequest " + e.getMessage());
788
      e.printStackTrace(System.out);
789
    }
790
    
791
  }
792
  
793
  /**
794
   * Sends a list of all of the documents on this sever along with their
795
   * revision numbers.  
796
   * The format is:
797
   * <!ELEMENT replication (server, updates)>
798
   * <!ELEMENT server (#PCDATA)>
799
   * <!ELEMENT updates ((updatedDocument | deleteDocument)*)>
800
   * <!ELEMENT updatedDocument (docid, rev, datafile*)>
801
   * <!ELEMENT deletedDocument (docid, rev)>
802
   * <!ELEMENT docid (#PCDATA)>
803
   * <!ELEMENT rev (#PCDATA)>
804
   * <!ELEMENT datafile (#PCDATA)>
805
   * note that the rev in deletedDocument is always empty.  I just left
806
   * it in there to make the parser implementation easier.
807
   */
808
  private void handleUpdateRequest(PrintWriter out, Hashtable params, 
809
                                    HttpServletResponse response)
810
  {
811
    Connection conn = null;
812
    try
813
    {
814
      
815
      StringBuffer docsql = new StringBuffer();
816
      StringBuffer doclist = new StringBuffer();
817
      Vector packageFiles = new Vector();
818
      
819
      //get all docs that reside on this server
820
      doclist.append("<?xml version=\"1.0\"?><replication>");
821
      doclist.append("<server>").append(util.getOption("server"));
822
      doclist.append(util.getOption("replicationpath"));
823
      doclist.append("</server><updates>");
824
      
825
      docsql.append("select docid, rev, doctype from xml_documents ");
826
      if (!(util.getOption("hub")).equals("super"))
827
      {
828
        docsql.append("where server_location = 1");
829
      }
830
      
831
      //get any deleted documents
832
      StringBuffer delsql = new StringBuffer();
833
      delsql.append("select distinct docid from ");
834
      delsql.append("xml_revisions where docid not in (select docid from ");
835
      delsql.append("xml_documents) ");
836
      if (!(util.getOption("hub")).equals("super"))
837
      {
838
        delsql.append("and server_location = 1");
839
      }
840
     
841
      conn = MetacatReplication.getDBConnection("MetacatReplication." +
842
                                                "handleUpdateRequest");
843
      PreparedStatement pstmt = conn.prepareStatement(docsql.toString());
844
      pstmt.execute();
845
      ResultSet rs = pstmt.getResultSet();
846
      boolean tablehasrows = rs.next();
847
      //If metacat configed to replicate data file
848
      if ((util.getOption("replicationdata")).equals("on"))
849
      {
850
        while(tablehasrows)
851
        {
852
          String recordDoctype = rs.getString(3);
853
          Vector packagedoctypes = MetaCatUtil.getOptionList(
854
                                     MetaCatUtil.getOption("packagedoctype"));
855
          if(!packagedoctypes.contains(recordDoctype))
856
          {   //if this is a package file, put it at the end
857
              //because if a package file is read before all of the files it
858
              //refers to are loaded then there is an error
859
              if (!recordDoctype.equals("BIN"))
860
              {
861
                //for non-data file document
862
                doclist.append("<updatedDocument>");
863
                doclist.append("<docid>").append(rs.getString(1));
864
                doclist.append("</docid><rev>").append(rs.getInt(2));
865
                doclist.append("</rev>");
866
                doclist.append("</updatedDocument>");
867
              }
868
              else
869
              {
870
                //for data file document, in datafile attributes
871
                //we put "datafile" value there
872
                doclist.append("<updatedDocument>");
873
                doclist.append("<docid>").append(rs.getString(1));
874
                doclist.append("</docid><rev>").append(rs.getInt(2));
875
                doclist.append("</rev>");
876
                doclist.append("<datafile>");
877
                doclist.append(MetaCatUtil.getOption("datafileflag"));
878
                doclist.append("</datafile>");
879
                doclist.append("</updatedDocument>");
880
              } 
881
          }
882
          else
883
          { //the package files are saved to be put into the xml later.
884
              Vector v = new Vector();
885
              v.add(new String(rs.getString(1)));
886
              v.add(new Integer(rs.getInt(2)));
887
              packageFiles.add(new Vector(v));
888
          }
889
          tablehasrows = rs.next();
890
        }//while
891
      }//if
892
      else //metacat was configured not to send data file
893
      {
894
        while(tablehasrows)
895
        {
896
          String recordDoctype = rs.getString(3);
897
          if(!recordDoctype.equals("BIN")) 
898
          { //don't replicate data files
899
            Vector packagedoctypes = MetaCatUtil.getOptionList(
900
                                     MetaCatUtil.getOption("packagedoctype"));
901
            if(!packagedoctypes.contains(recordDoctype))
902
            {   //if this is a package file, put it at the end
903
              //because if a package file is read before all of the files it
904
              //refers to are loaded then there is an error
905
              doclist.append("<updatedDocument>");
906
              doclist.append("<docid>").append(rs.getString(1));
907
              doclist.append("</docid><rev>").append(rs.getInt(2));
908
              doclist.append("</rev>");
909
              doclist.append("</updatedDocument>");
910
            }
911
            else
912
            { //the package files are saved to be put into the xml later.
913
              Vector v = new Vector();
914
              v.add(new String(rs.getString(1)));
915
              v.add(new Integer(rs.getInt(2)));
916
              packageFiles.add(new Vector(v));
917
            }
918
         }//if
919
         tablehasrows = rs.next();
920
        }//while
921
      }//else
922
      
923
      pstmt = conn.prepareStatement(delsql.toString());
924
      pstmt.execute();
925
      rs = pstmt.getResultSet();
926
      tablehasrows = rs.next();
927
      while(tablehasrows)
928
      { //handle the deleted documents
929
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
930
        doclist.append("</docid><rev></rev></deletedDocument>");
931
        //note that rev is always empty for deleted docs
932
        tablehasrows = rs.next();
933
      }
934
      
935
      //now we can put the package files into the xml results
936
      for(int i=0; i<packageFiles.size(); i++)
937
      {
938
        Vector v = (Vector)packageFiles.elementAt(i);
939
        doclist.append("<updatedDocument>");
940
        doclist.append("<docid>").append((String)v.elementAt(0));
941
        doclist.append("</docid><rev>");
942
        doclist.append(((Integer)v.elementAt(1)).intValue());
943
        doclist.append("</rev>");
944
        doclist.append("</updatedDocument>");
945
      }
946
      
947
      doclist.append("</updates></replication>");
948
      MetaCatUtil.debugMessage("doclist: " + doclist.toString());
949
      pstmt.close();
950
      conn.close();
951
      response.setContentType("text/xml");
952
      out.println(doclist.toString());
953
     
954
    }
955
    catch(Exception e)
956
    {
957
      System.out.println("error in MetacatReplication.handleupdaterequest: " + 
958
                          e.getMessage());
959
      e.printStackTrace(System.out);
960
    }
961
    
962
  }
963
  
964
  /**
965
   * Returns the xml_catalog table encoded in xml
966
   */
967
  public static String getCatalogXML()
968
  {
969
    return handleGetCatalogRequest(null, null, null, false);
970
  }
971
  
972
  /**
973
   * Sends the contents of the xml_catalog table encoded in xml
974
   * The xml format is:
975
   * <!ELEMENT xml_catalog (row*)>
976
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
977
   *                system_id)>
978
   * All of the sub elements of row are #PCDATA
979
   
980
   * If printFlag == false then do not print to out.
981
   */
982
  private static String handleGetCatalogRequest(PrintWriter out, 
983
                                                Hashtable params,
984
                                                HttpServletResponse response,
985
                                                boolean printFlag)
986
  {
987
    Connection conn = null;
988
    PreparedStatement pstmt = null;
989
    try
990
    { 
991
      conn = MetacatReplication.getDBConnection("MetacatReplication." +
992
                                                "handleGetCatalogRequest");
993
      pstmt = conn.prepareStatement("select entry_type, " +
994
                              "source_doctype, target_doctype, public_id, " +
995
                              "system_id from xml_catalog");
996
      pstmt.execute();
997
      ResultSet rs = pstmt.getResultSet();
998
      boolean tablehasrows = rs.next();
999
      StringBuffer sb = new StringBuffer();
1000
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1001
      while(tablehasrows)
1002
      {
1003
        sb.append("<row><entry_type>").append(rs.getString(1));
1004
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1005
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1006
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1007
        sb.append("</public_id><system_id>").append(rs.getString(5));
1008
        sb.append("</system_id></row>");
1009
      
1010
        tablehasrows = rs.next();
1011
      }
1012
      sb.append("</xml_catalog>");
1013
      conn.close();
1014
      if(printFlag)
1015
      {
1016
        response.setContentType("text/xml");
1017
        out.println(sb.toString());
1018
      }
1019
      pstmt.close();
1020
      return sb.toString();
1021
    }
1022
    catch(Exception e)
1023
    {
1024
      try
1025
      {
1026
        pstmt.close();
1027
        conn.close();
1028
      }
1029
      catch(Exception ee)
1030
      {}
1031
      System.out.println("error in MetacatReplication.handleGetCatalogRequest:"+ 
1032
                          e.getMessage());
1033
      e.printStackTrace(System.out);
1034
    }
1035
    return null;
1036
  }
1037
  
1038
  /**
1039
   * Sends the current system date to the remote server.  Using this action
1040
   * for replication gets rid of any problems with syncronizing clocks 
1041
   * because a time specific to a document is always kept on its home server.
1042
   */
1043
  private void handleGetTimeRequest(PrintWriter out, Hashtable params, 
1044
                                    HttpServletResponse response)
1045
  {
1046
    SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1047
    java.util.Date localtime = new java.util.Date();
1048
    String dateString = formatter.format(localtime);
1049
    response.setContentType("text/xml");
1050
    
1051
    out.println("<timestamp>" + dateString + "</timestamp>");
1052
  }
1053
  
1054
  /**
1055
   * this method handles the timeout for a file lock.  when a lock is 
1056
   * granted it is granted for 30 seconds.  When this thread runs out
1057
   * it deletes the docid from the queue, thus eliminating the lock.
1058
   */
1059
  public void run()
1060
  {
1061
    try
1062
    {
1063
      MetaCatUtil.debugMessage("thread started for docid: " + 
1064
                               (String)fileLocks.elementAt(0));
1065
      System.out.println("thread started for docid: " + 
1066
                               (String)fileLocks.elementAt(0));
1067
      Thread.sleep(30000); //the lock will expire in 30 seconds
1068
      MetaCatUtil.debugMessage("thread for docid: " + 
1069
                             (String)fileLocks.elementAt(fileLocks.size() - 1) + 
1070
                              " exiting.");
1071
      System.out.println("thread for docid: " + 
1072
                         (String)fileLocks.elementAt(fileLocks.size() - 1) + 
1073
                         " exiting.");
1074
      fileLocks.remove(fileLocks.size() - 1);
1075
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1076
      //in the vector, the first one inserted will be removed.
1077
    }
1078
    catch(Exception e)
1079
    {
1080
      System.out.println("error in file lock thread from MetacatReplication." + 
1081
                         "run: " + e.getMessage());
1082
    }
1083
  }
1084
  
1085
  /**
1086
   * Returns the name of a server given a serverCode
1087
   * @param serverCode the serverid of the server
1088
   * @return the servername or null if the specified serverCode does not
1089
   *         exist.
1090
   */
1091
  public static String getServer(int serverCode)
1092
  {
1093
    //System.out.println("serverid: " + serverCode);
1094
    Connection conn = null;
1095
    try
1096
    {
1097
      conn = MetacatReplication.getDBConnection("MetacatReplication." +
1098
                                                "getServer");
1099
      String sql = new String("select server from " +
1100
                              "xml_replication where serverid = " + 
1101
                              serverCode);
1102
      PreparedStatement pstmt = conn.prepareStatement(sql);
1103
      //System.out.println("getserver sql: " + sql);
1104
      pstmt.execute();
1105
      ResultSet rs = pstmt.getResultSet();
1106
      boolean tablehasrows = rs.next();
1107
      if(tablehasrows)
1108
      {
1109
        //System.out.println("server: " + rs.getString(1));
1110
        return rs.getString(1);
1111
      }
1112
      pstmt.close();
1113
      conn.close();
1114
    }
1115
    catch(Exception e)
1116
    {
1117
      System.out.println("Error in MetacatReplication.getServer: " + 
1118
                          e.getMessage());
1119
    }
1120
    return null;
1121
      //return null if the server does not exist
1122
  }
1123
  
1124
  /**
1125
   * Returns a server code given a server name
1126
   * @param server the name of the server
1127
   * @return integer > 0 representing the code of the server, 0 if the server
1128
   *  does not exist.
1129
   */
1130
  public static int getServerCode(String server) throws Exception
1131
  {
1132
    Connection conn = null;
1133
    PreparedStatement pstmt = null;
1134
    int serverCode = 0;
1135

    
1136
    try {
1137

    
1138
      conn = util.openDBConnection();
1139
      pstmt = conn.prepareStatement("SELECT serverid FROM xml_replication " +
1140
                                    "WHERE server LIKE '" + server + "'");
1141
      pstmt.execute();
1142
      ResultSet rs = pstmt.getResultSet();
1143
      boolean tablehasrows = rs.next();
1144
      if ( tablehasrows ) {  
1145
        serverCode = rs.getInt(1);
1146
        pstmt.close();
1147
        conn.close();
1148
        return serverCode;
1149
      }
1150
      
1151
    } catch(Exception e) {
1152
      throw e;
1153

    
1154
    } finally {
1155
      try {
1156
        pstmt.close();
1157
        conn.close();
1158
      } catch(Exception ee) {}
1159
    }
1160
    
1161
    return serverCode;
1162
  }
1163
  
1164
  /**
1165
   * This method returns the content of a url
1166
   * @param u the url to return the content from
1167
   * @return a string representing the content of the url
1168
   * @throws java.io.IOException
1169
   */
1170
  public static String getURLContent(URL u) throws java.io.IOException
1171
  {
1172
    //System.out.println("url: " + u.toString());
1173
    char istreamChar;
1174
    int istreamInt;
1175
    InputStreamReader istream = new InputStreamReader(u.openStream());
1176
    StringBuffer serverResponse = new StringBuffer();
1177
    while((istreamInt = istream.read()) != -1)
1178
    {
1179
      istreamChar = (char)istreamInt;
1180
      serverResponse.append(istreamChar);
1181
    }
1182
    
1183
    return serverResponse.toString();
1184
  }
1185
  
1186
  /**
1187
   * Method for writing replication messages to a log file specified in 
1188
   * metacat.properties
1189
   */
1190
  public static void replLog(String message)
1191
  {
1192
    try
1193
    {
1194
      FileOutputStream fos = new FileOutputStream(
1195
                                 util.getOption("replicationlog"), true);
1196
      PrintWriter pw = new PrintWriter(fos);
1197
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1198
      java.util.Date localtime = new java.util.Date();
1199
      String dateString = formatter.format(localtime);
1200
      dateString += " :: " + message;
1201
      //time stamp each entry
1202
      pw.println(dateString);
1203
      pw.flush();
1204
    }
1205
    catch(Exception e)
1206
    {
1207
      System.out.println("error writing to replication log from " +
1208
                         "MetacatReplication.replLog: " + e.getMessage());
1209
      //e.printStackTrace(System.out);
1210
    }
1211
  }
1212
  
1213
  /**
1214
   * Returns true if the replicate field for server in xml_replication is 1.
1215
   * Returns false otherwise
1216
   */
1217
  public static boolean replToServer(String server)
1218
  {
1219
    Connection conn = null;
1220
    PreparedStatement pstmt = null;
1221
    try
1222
    {
1223
      conn = MetacatReplication.getDBConnection("MetacatReplication.replToServer");
1224
      pstmt = conn.prepareStatement("select replicate from " + 
1225
                                    "xml_replication where server like '" +
1226
                                     server + "'");
1227
      pstmt.execute();
1228
      ResultSet rs = pstmt.getResultSet();
1229
      boolean tablehasrows = rs.next();
1230
      if(tablehasrows)
1231
      {
1232
        int i = rs.getInt(1);
1233
        if(i == 1)
1234
        {
1235
          pstmt.close();
1236
          conn.close();
1237
          return true;
1238
        }
1239
        else
1240
        {
1241
          pstmt.close();
1242
          conn.close();
1243
          return false;
1244
        }
1245
      }
1246
    }
1247
    catch(Exception e)
1248
    {
1249
      System.out.println("error in MetacatReplication.replToServer: " + 
1250
                         e.getMessage());
1251
    }
1252
    finally
1253
    {
1254
      try
1255
      {
1256
        pstmt.close();
1257
        conn.close();
1258
      }
1259
      catch(Exception ee)
1260
      {}
1261
    }
1262
    return false;
1263
    //the default if this server does not exist is to not replicate to it.
1264
  }
1265
  
1266
  /**
1267
   * A method for redundantly trying to connect.  this method will attempt to 
1268
   * connect to the DB 3 times before failing.
1269
   * @param methodname the methodname from which this method is called.
1270
   */
1271
  public static Connection getDBConnection(String methodname) throws Exception
1272
  {
1273
    Connection conn = null;
1274
    try
1275
    {
1276
      try
1277
      { //this connection is prone to error for some reason so we 
1278
        //try to connect it three times before quiting.
1279
        conn = util.openDBConnection();
1280
        return conn;
1281
      }
1282
      catch(SQLException sqle)
1283
      {
1284
        try
1285
        {
1286
          conn = util.openDBConnection();
1287
          return conn;
1288
        }
1289
        catch(SQLException sqlee)
1290
        {
1291
          try
1292
          {
1293
            conn = util.openDBConnection();
1294
            return conn;
1295
          }
1296
          catch(SQLException sqleee)
1297
          {
1298
            System.out.println("error getting db connection in " + 
1299
                               methodname +  ": " +
1300
                               sqleee.getMessage());
1301
            return conn;
1302
          }
1303
        }
1304
      }
1305
    }
1306
    catch(Exception e)
1307
    {
1308
      throw new java.lang.Exception("error in " + methodname + ": " + 
1309
                          e.getMessage());
1310
    }
1311
  }
1312
}
(32-32/41)