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-04-26 17:30:00 -0700 (Fri, 26 Apr 2002) $'
11
 * '$Revision: 1035 $'
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
      
418
      // sending back read request to server
419
      URL u = new URL("https://" + server + "?server="
420
                +util.getLocalReplicationServerName()
421
                +"&action=read&docid=" + docid);
422
      String xmldoc = MetacatReplication.getURLContent(u);
423

    
424
      // get the document info from server
425
      URL docinfourl = new URL("https://" + server + 
426
                               "?server="+util.getLocalReplicationServerName()
427
                               +"&action=getdocumentinfo&docid=" + docid);
428
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
429

    
430
      //dih is the parser for the docinfo xml format
431
      DocInfoHandler dih = new DocInfoHandler();
432
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
433
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
434
      Hashtable docinfoHash = dih.getDocInfo();
435
      String user = (String)docinfoHash.get("user_owner");
436

    
437
      // write the document here
438
      Connection conn = util.openDBConnection();
439
      DocumentImpl.write(conn, new StringReader(xmldoc), null, dbaction, docid, 
440
                         user, null, serverCode, override);
441
      conn.close();
442

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

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

    
1118
    try {
1119

    
1120
      conn = util.openDBConnection();
1121
      pstmt = conn.prepareStatement("SELECT serverid FROM xml_replication " +
1122
                                    "WHERE server LIKE '" + server + "'");
1123
      pstmt.execute();
1124
      ResultSet rs = pstmt.getResultSet();
1125
      boolean tablehasrows = rs.next();
1126
      if ( tablehasrows ) {  
1127
        serverCode = rs.getInt(1);
1128
        pstmt.close();
1129
        conn.close();
1130
        return serverCode;
1131
      }
1132
      
1133
    } catch(Exception e) {
1134
      throw e;
1135

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