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: 2004-09-16 17:04:08 -0700 (Thu, 16 Sep 2004) $'
11
 * '$Revision: 2298 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
31
import java.util.*;
32
import java.io.*;
33
import java.sql.*;
34
import java.net.*;
35
import java.lang.*;
36
import java.text.*;
37
import javax.servlet.*;
38
import javax.servlet.http.*;
39

    
40
import org.xml.sax.*;
41

    
42
public class MetacatReplication extends HttpServlet implements Runnable
43
{
44
  private String deltaT;
45
  Timer replicationDaemon;
46
  private static MetaCatUtil util = new MetaCatUtil();
47
  private Vector fileLocks = new Vector();
48
  private Thread lockThread = null;
49
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
50
  public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
51

    
52
  /**
53
   * Initialize the servlet by creating appropriate database connections
54
   */
55
  public void init(ServletConfig config) throws ServletException
56
  {
57
     //initialize db connections to handle any update requests
58
    MetaCatUtil util = new MetaCatUtil();
59
    deltaT = util.getOption("deltaT");
60
    //the default deltaT can be set from metacat.properties
61
    //create a thread to do the delta-T check but don't execute it yet
62
    replicationDaemon = new Timer(true);
63
    /*java.net.URL.setURLStreamHandlerFactory(
64
       new java.net.URLStreamHandlerFactory()
65
       {
66
          public java.net.URLStreamHandler createURLStreamHandler(
67
                        final String protocol)
68
          {
69
              if ("http".equals(protocol))
70
              {
71
                 try
72
                 {
73
                    URLStreamHandler urlsh = new HTTPClient.http.Handler();
74
                    MetaCatUtil.debugMessage("Using HttpClient Protocol Handler for http", 45);
75
                    return urlsh;
76
                  }
77
                  catch (Exception e)
78
                  {
79
                     MetaCatUtil.debugMessage(
80
                          "Error setting URL StreamHandler!", 30);
81
                     return null;
82
                  }
83
               }//if
84
               else if ("https".equals(protocol))
85
               {
86
                 try
87
                 {
88
                   URLStreamHandler urlsh = new HTTPClient.https.Handler();
89
                   MetaCatUtil.debugMessage("Using HttpClient Protocol Handler for https", 45);
90
                   return urlsh;
91
                 }
92
                 catch (Exception e)
93
                 {
94
                   MetaCatUtil.debugMessage(
95
                              "Error setting URL StreamHandler!", 30);
96
                   return null;
97
                 }
98
              }
99
              return null;
100
         }//createURLStreamHandler
101
     });*/
102

    
103
  }
104

    
105
  public void destroy()
106
  {
107
    replicationDaemon.cancel();
108
   // System.out.println("Replication daemon cancelled.");
109
  }
110

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

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

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

    
134

    
135

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

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

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

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

    
158
        server = ((String[])params.get("server"))[0];
159
        if ( getServerCodeForServerName(server) == 0 ) {
160
          System.out.println("Action \"" + action +
161
                             "\" rejected for server: " + server);
162
          return;
163
        } else {
164
          System.out.println("Action \"" + action +
165
                             "\" accepted for server: " + server);
166
        }
167
      }
168
    } catch (Exception e) {
169
      System.out.println("Error in MetacatReplication.handleGetOrPost: " +
170
                         e.getMessage() );
171
      return;
172
    }
173
    if ( action.equals("readdata") )
174
    {
175
      OutputStream out=response.getOutputStream();
176
      //to get the data file.
177
      handleGetDataFileRequest(out, params, response);
178
      out.close();
179
    }
180
    else if ( action.equals("forcereplicatedatafile") )
181
    {
182
      //read a specific docid from remote host, and store it into local host
183
      handleForceReplicateDataFileRequest(params);
184

    
185
    }
186
    else
187
    {
188
    PrintWriter out = response.getWriter();
189
    if ( action.equals("stop") ) {
190
      //stop the replication server
191
      replicationDaemon.cancel();
192
      replicationDaemon = new Timer(true);
193
      out.println("Replication Handler Stopped");
194
      MetacatReplication.replLog("deltaT handler stopped");
195

    
196

    
197
    } else if ( action.equals("start") ) {
198

    
199
      //start the replication server
200
      int rate;
201
      if ( params.containsKey("rate") ) {
202
        rate = new Integer(
203
               new String(((String[])params.get("rate"))[0])).intValue();
204
        if(rate < 30) {
205
            out.println("Replication deltaT rate cannot be less than 30!");
206
            //deltaT<30 is a timing mess!
207
            rate = 1000;
208
        }
209
      } else {
210
        rate = 1000;
211
      }
212
      out.println("New rate is: " + rate + " seconds.");
213
      replicationDaemon.cancel();
214
      replicationDaemon = new Timer(true);
215
      replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(out), 0,
216
                                            rate * 1000);
217
      out.println("Replication Handler Started");
218
      MetacatReplication.replLog("deltaT handler started with rate=" +
219
                                    rate + " seconds");
220

    
221

    
222
    } else if ( action.equals("getall") ) {
223
      //updates this server exactly once
224
      replicationDaemon.schedule(new ReplicationHandler(out), 0);
225
      response.setContentType("text/html");
226
      out.println("<html><body>\"Get All\" Done</body></html>");
227

    
228
    } else if ( action.equals("forcereplicate") ) {
229
      //read a specific docid from remote host, and store it into local host
230
      handleForceReplicateRequest(out, params, response);
231

    
232
    } else if ( action.equals(FORCEREPLICATEDELETE) ) {
233
      //read a specific docid from remote host, and store it into local host
234
      handleForceReplicateDeleteRequest(out, params, response);
235

    
236
    } else if ( action.equals("update") ) {
237
      //request an update list from the server
238
      handleUpdateRequest(out, params, response);
239

    
240
    } else if ( action.equals("read") ) {
241
      //request a specific document from the server
242
      //note that this could be replaced by a call to metacatServlet
243
      //handleGetDocumentAction().
244
      handleGetDocumentRequest(out, params, response);
245
    } else if ( action.equals("getlock") ) {
246
      handleGetLockRequest(out, params, response);
247

    
248
    } else if ( action.equals("getdocumentinfo") ) {
249
      handleGetDocumentInfoRequest(out, params, response);
250

    
251
    } else if ( action.equals("gettime") ) {
252
      handleGetTimeRequest(out, params, response);
253

    
254
    } else if ( action.equals("getcatalog") ) {
255
      handleGetCatalogRequest(out, params, response, true);
256

    
257
    } else if ( action.equals("servercontrol") ) {
258
      handleServerControlRequest(out, params, response);
259
    } else if ( action.equals("test") ) {
260
      response.setContentType("text/html");
261
      out.println("<html><body>Test successfully</body></html>");
262
    }
263

    
264
    out.close();
265
    }//else
266
  }
267

    
268
  /**
269
   * This method can add, delete and list the servers currently included in
270
   * xml_replication.
271
   * action           subaction            other needed params
272
   * ---------------------------------------------------------
273
   * servercontrol    add                  server
274
   * servercontrol    delete               server
275
   * servercontrol    list
276
   */
277
  private void handleServerControlRequest(PrintWriter out, Hashtable params,
278
                                          HttpServletResponse response)
279
  {
280
    String subaction = ((String[])params.get("subaction"))[0];
281
    DBConnection dbConn = null;
282
    int serialNumber = -1;
283
    PreparedStatement pstmt = null;
284
    String replicate =null;
285
    String server = null;
286
    String dataReplicate = null;
287
    String hub = null;
288
    try {
289
      //conn = util.openDBConnection();
290
      dbConn=DBConnectionPool.
291
               getDBConnection("MetacatReplication.handleServerControlRequest");
292
      serialNumber=dbConn.getCheckOutSerialNumber();
293

    
294
      // add server to server list
295
      if ( subaction.equals("add") ) {
296
        replicate = ((String[])params.get("replicate"))[0];
297
        server = ((String[])params.get("server"))[0];
298

    
299
        //Get data replication value
300
        dataReplicate = ((String[])params.get("datareplicate"))[0];
301
        //Get hub value
302
        hub = ((String[])params.get("hub"))[0];
303

    
304
        /*pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
305
                  "(server, last_checked, replicate, datareplicate, hub) " +
306
                                      "VALUES ('" + server + "', to_date(" +
307
                                      "'01/01/00', 'MM/DD/YY'), '" +
308
                                      replicate +"', '" +dataReplicate+"', '"
309
                                      + hub +"')");*/
310
        pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
311
                  "(server, last_checked, replicate, datareplicate, hub) " +
312
                                      "VALUES ('" + server + "', "+
313
                                      dbAdapter.toDate("01/01/1980", "MM/DD/YYYY")
314
                                      + ", '" +
315
                                      replicate +"', '" +dataReplicate+"', '"
316
                                      + hub +"')");
317

    
318
        pstmt.execute();
319
        pstmt.close();
320
        dbConn.commit();
321
        out.println("Server " + server + " added");
322
        response.setContentType("text/html");
323
        out.println("<html><body><table border=\"1\">");
324
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
325
        out.println("<b>replicate</b></td>");
326
        out.println("<td><b>datareplicate</b></td>");
327
        out.println("<td><b>hub</b></td></tr>");
328
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
329
        //increase dbconnection usage
330
        dbConn.increaseUsageCount(1);
331

    
332
        pstmt.execute();
333
        ResultSet rs = pstmt.getResultSet();
334
        boolean tablehasrows = rs.next();
335
        while(tablehasrows) {
336
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
337
          out.println(rs.getString(3) + "</td><td>");
338
          out.println(rs.getString(4) + "</td><td>");
339
          out.println(rs.getString(5) + "</td><td>");
340
          out.println(rs.getString(6) + "</td></tr>");
341

    
342
          tablehasrows = rs.next();
343
        }
344
        out.println("</table></body></html>");
345

    
346
        // download certificate with the public key on this server
347
        // and import it as a trusted certificate
348
        String certURL = ((String[])params.get("certificate"))[0];
349
        downloadCertificate(certURL);
350

    
351
      // delete server from server list
352
      } else if ( subaction.equals("delete") ) {
353
        server = ((String[])params.get("server"))[0];
354
        pstmt = dbConn.prepareStatement("DELETE FROM xml_replication " +
355
                                      "WHERE server LIKE '" + server + "'");
356
        pstmt.execute();
357
        pstmt.close();
358
        dbConn.commit();
359
        out.println("Server " + server + " deleted");
360
        response.setContentType("text/html");
361
        out.println("<html><body><table border=\"1\">");
362
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
363
        out.println("<b>replicate</b></td>");
364
        out.println("<td><b>datareplicate</b></td>");
365
        out.println("<td><b>hub</b></td></tr>");
366

    
367
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
368
        //increase dbconnection usage
369
        dbConn.increaseUsageCount(1);
370
        pstmt.execute();
371
        ResultSet rs = pstmt.getResultSet();
372
        boolean tablehasrows = rs.next();
373
        while(tablehasrows)
374
        {
375
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
376
          out.println(rs.getString(3) + "</td><td>");
377
          out.println(rs.getString(4) + "</td><td>");
378
          out.println(rs.getString(5) + "</td><td>");
379
          out.println(rs.getString(6) + "</td></tr>");
380
          tablehasrows = rs.next();
381
        }
382
        out.println("</table></body></html>");
383

    
384
      // list servers in server list
385
      } else if ( subaction.equals("list") ) {
386
        response.setContentType("text/html");
387
        out.println("<html><body><table border=\"1\">");
388
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
389
        out.println("<b>replicate</b></td>");
390
        out.println("<td><b>datareplicate</b></td>");
391
        out.println("<td><b>hub</b></td></tr>");
392
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
393
        pstmt.execute();
394
        ResultSet rs = pstmt.getResultSet();
395
        boolean tablehasrows = rs.next();
396
        while(tablehasrows) {
397
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
398
          out.println(rs.getString(3) + "</td><td>");
399
          out.println(rs.getString(4) + "</td><td>");
400
          out.println(rs.getString(5) + "</td><td>");
401
          out.println(rs.getString(6) + "</td></tr>");
402
          tablehasrows = rs.next();
403
        }
404
        out.println("</table></body></html>");
405
      }
406
      else
407
      {
408

    
409
        out.println("<error>Unkonwn subaction</error>");
410

    
411
      }
412
      pstmt.close();
413
      //conn.close();
414

    
415
    } catch(Exception e) {
416
      System.out.println("Error in " +
417
                         "MetacatReplication.handleServerControlRequest " +
418
                         e.getMessage());
419
      e.printStackTrace(System.out);
420
    }
421
    finally
422
    {
423
      try
424
      {
425
        pstmt.close();
426
      }//try
427
      catch (SQLException ee)
428
      {
429
        MetaCatUtil.debugMessage("Error in " +
430
                "MetacatReplication.handleServerControlRequest to close pstmt "
431
                 + ee.getMessage(), 30);
432
      }//catch
433
      finally
434
      {
435
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
436
      }//finally
437
    }//finally
438

    
439
  }
440

    
441
  // download certificate with the public key from certURL and
442
  // upload it onto this server; it then must be imported as a
443
  // trusted certificate
444
  private void downloadCertificate (String certURL)
445
                throws FileNotFoundException, IOException, MalformedURLException
446
  {
447
    MetaCatUtil util = new MetaCatUtil();
448
    String certPath = util.getOption("certPath"); //the path to be uploaded to
449

    
450
    // get filename from the URL of the certificate
451
    String filename = certURL;
452
    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
453
    if ( slash > -1 ) {
454
      filename = filename.substring(slash + 1);
455
    }
456

    
457
    // open file output strem to write the input into it
458
    File f = new File(certPath, filename);
459
    synchronized (f) {
460
      try {
461
        if ( f.exists() ) {
462
          throw new IOException("File already exist: " + f.getCanonicalFile());
463
          //if ( f.exists() && !f.canWrite() ) {
464
          //  throw new IOException("Not writable: " + f.getCanonicalFile());
465
        }
466
      } catch (SecurityException se) {
467
        // if a security manager exists,
468
        // its checkRead method is called for f.exist()
469
        // or checkWrite method is called for f.canWrite()
470
        throw se;
471
      }
472

    
473
      // create a buffered byte output stream
474
      // that uses a default-sized output buffer
475
      FileOutputStream fos = new FileOutputStream(f);
476
      BufferedOutputStream out = new BufferedOutputStream(fos);
477

    
478
      // this should be http url
479
      URL url = new URL(certURL);
480
      BufferedInputStream bis = null;
481
      try {
482
        bis = new BufferedInputStream(url.openStream());
483
        byte[] buf = new byte[4 * 1024]; // 4K buffer
484
        int b = bis.read(buf);
485
        while (b != -1) {
486
          out.write(buf, 0, b);
487
          b = bis.read(buf);
488
        }
489
      } finally {
490
        if (bis != null) bis.close();
491
      }
492
      // the input and the output streams must be closed
493
      bis.close();
494
            out.flush();
495
            out.close();
496
            fos.close();
497
    } // end of synchronized(f)
498
  }
499

    
500
  /**
501
   * when a forcereplication request comes in, local host sends a read request
502
   * to the requesting server (remote server) for the specified docid.
503
   * Then store it in local database.
504
   */
505
  private void handleForceReplicateRequest(PrintWriter out, Hashtable params,
506
                                           HttpServletResponse response)
507
  {
508
    String server = ((String[])params.get("server"))[0]; // the server that
509
    String docid = ((String[])params.get("docid"))[0]; // sent the document
510
    String dbaction = "UPDATE"; // the default action is UPDATE
511
    boolean override = false;
512
    int serverCode = 1;
513
    DBConnection dbConn = null;
514
    int serialNumber = -1;
515

    
516
    try {
517
      //if the url contains a dbaction then the default action is overridden
518
      if(params.containsKey("dbaction")) {
519
        dbaction = ((String[])params.get("dbaction"))[0];
520
        //serverCode = MetacatReplication.getServerCode(server);
521
        //override = true; //we are now overriding the default action
522
      }
523
      MetacatReplication.replLog("force replication request from " + server);
524
      MetaCatUtil.debugMessage("Force replication request from: "+ server, 34);
525
      MetaCatUtil.debugMessage("Force replication docid: "+docid, 34);
526
      MetaCatUtil.debugMessage("Force replication action: "+dbaction, 34);
527
      // sending back read request to remote server
528
      URL u = new URL("https://" + server + "?server="
529
                +util.getLocalReplicationServerName()
530
                +"&action=read&docid=" + docid);
531
      String xmldoc = MetacatReplication.getURLContent(u);
532

    
533
      // get the document info from server
534
      URL docinfourl = new URL("https://" + server +
535
                               "?server="+util.getLocalReplicationServerName()
536
                               +"&action=getdocumentinfo&docid=" + docid);
537

    
538
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
539

    
540
      //dih is the parser for the docinfo xml format
541
      DocInfoHandler dih = new DocInfoHandler();
542
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
543
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
544
      Hashtable docinfoHash = dih.getDocInfo();
545

    
546
      // Get user owner of this docid
547
      String user = (String)docinfoHash.get("user_owner");
548
      // Get home server of this docid
549
      String homeServer=(String)docinfoHash.get("home_server");
550
      MetaCatUtil.debugMessage("homeServer: "+homeServer, 34);
551
      // Get Document type
552
      String docType = (String)docinfoHash.get("doctype");
553
      MetaCatUtil.debugMessage("docType: "+docType, 34);
554
      String parserBase = null;
555
      // this for eml2 and we need user eml2 parser
556
      if (docType != null &&
557
          (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
558
      {
559
         MetaCatUtil.debugMessage("This is an eml200 document!", 30);
560
         parserBase = DocumentImpl.EML200;
561
      }
562
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
563
      {
564
         MetaCatUtil.debugMessage("This is an eml2.0.1 document!", 30);
565
         parserBase = DocumentImpl.EML200;
566
      }
567
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
568
      {
569
         MetaCatUtil.debugMessage("This is an eml2.1.0 document!", 30);
570
         parserBase = DocumentImpl.EML210;
571
      }
572
      MetaCatUtil.debugMessage("The parserBase is: "+parserBase, 30);
573

    
574
      // Get DBConnection from pool
575
      dbConn=DBConnectionPool.
576
              getDBConnection("MetacatReplication.handleForceReplicateRequest");
577
      serialNumber=dbConn.getCheckOutSerialNumber();
578
      // write the document to local database
579
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
580
      wrapper.writeReplication(dbConn, new StringReader(xmldoc), null, null,
581
                               dbaction, docid, user, null, homeServer, server);
582

    
583
      MetacatReplication.replLog("document " + docid + " added to DB with " +
584
                                 "action " + dbaction);
585
    }//try
586
    catch(Exception e)
587
    {
588
      MetacatReplication.replErrorLog("document " + docid +
589
                                      " failed to added to DB with " +
590
                                      "action " + dbaction + " because "+
591
                                       e.getMessage());
592
      MetaCatUtil.debugMessage("ERROR in MetacatReplication.handleForceReplicate" +
593
                         "Request(): " + e.getMessage(), 30);
594

    
595
    }//catch
596
    finally
597
    {
598
      // Return the checked out DBConnection
599
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
600
    }//finally
601
  }
602

    
603
/*
604
 * when a forcereplication delete request comes in, local host will delete this
605
 * document
606
 */
607
private void handleForceReplicateDeleteRequest(PrintWriter out, Hashtable params,
608
                                         HttpServletResponse response)
609
{
610
  String server = ((String[])params.get("server"))[0]; // the server that
611
  String docid = ((String[])params.get("docid"))[0]; // sent the document
612
  try
613
  {
614
    MetacatReplication.replLog("force replication delete request from " + server);
615
    MetacatReplication.replLog("force replication delete docid " + docid);
616
    MetaCatUtil.debugMessage("Force replication delete request from: "+ server, 34);
617
    MetaCatUtil.debugMessage("Force replication delete docid: "+docid, 34);
618
    DocumentImpl.delete(docid, null, null, server);
619
    MetacatReplication.replLog("document " + docid + " was successfully deleted ");
620
    MetaCatUtil.debugMessage("document " + docid + " was successfully deleted ", 34);
621
  }
622
  catch(Exception e)
623
  {
624
    MetacatReplication.replErrorLog("document " + docid +
625
                                    " failed to delete because "+
626
                                     e.getMessage());
627
    MetaCatUtil.debugMessage("ERROR in MetacatReplication.handleForceDeleteReplicate" +
628
                       "Request(): " + e.getMessage(), 30);
629

    
630
  }//catch
631

    
632
}
633

    
634

    
635
  /**
636
   * when a forcereplication data file request comes in, local host sends a
637
   * readdata request to the requesting server (remote server) for the specified
638
   * docid. Then store it in local database and file system
639
   */
640
  private void handleForceReplicateDataFileRequest(Hashtable params)
641
  {
642

    
643
    //make sure there is some parameters
644
    if(params.isEmpty())
645
    {
646
      return;
647
    }
648
    // Get remote server
649
    String server = ((String[])params.get("server"))[0];
650
    // the docid should include rev number
651
    String docid = ((String[])params.get("docid"))[0];
652
    // Make sure there is a docid and server
653
    if (docid==null || server==null || server.equals(""))
654
    {
655
      MetaCatUtil.debugMessage("Didn't specify docid or server for replication"
656
                              , 20);
657
      return;
658
    }
659

    
660
    // Overide or not
661
    boolean override = false;
662
    // dbaction - update or insert
663
    String dbaction=null;
664

    
665
    try
666
    {
667
      //docid was switch to two parts uinque code and rev
668
      String uniqueCode=MetaCatUtil.getDocIdFromString(docid);
669
      int rev=MetaCatUtil.getVersionFromString(docid);
670
      if(params.containsKey("dbaction"))
671
      {
672
        dbaction = ((String[])params.get("dbaction"))[0];
673
      }
674
      else//default value is update
675
      {
676
        dbaction = "update";
677
      }
678

    
679
      MetacatReplication.replLog("force replication request from " + server);
680
      MetaCatUtil.debugMessage("Force replication request from: "+ server, 34);
681
      MetaCatUtil.debugMessage("Force replication docid: "+docid, 34);
682
      MetaCatUtil.debugMessage("Force replication action: "+dbaction, 34);
683
      // get the document info from server
684
      URL docinfourl = new URL("https://" + server +
685
                               "?server="+util.getLocalReplicationServerName()
686
                               +"&action=getdocumentinfo&docid=" + uniqueCode);
687

    
688
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
689

    
690
      //dih is the parser for the docinfo xml format
691
      DocInfoHandler dih = new DocInfoHandler();
692
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
693
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
694
      Hashtable docinfoHash = dih.getDocInfo();
695
      String user = (String)docinfoHash.get("user_owner");
696

    
697
      String docName = (String)docinfoHash.get("docname");
698

    
699
      String docType = (String)docinfoHash.get("doctype");
700

    
701
      String docHomeServer= (String)docinfoHash.get("home_server");
702
      MetaCatUtil.debugMessage("docHomeServer of datafile: "+docHomeServer, 34);
703

    
704

    
705

    
706
      //if action is delete, we don't delete the data file. Just archieve
707
      //the xml_documents
708
      /*if (dbaction.equals("delete"))
709
      {
710
        //conn = util.getConnection();
711
        DocumentImpl.delete(docid,user,null);
712
        //util.returnConnection(conn);
713
      }*/
714
      //To data file insert or update is same
715
      if (dbaction.equals("insert")||dbaction.equals("update"))
716
      {
717
        //Get data file and store it into local file system.
718
        // sending back readdata request to server
719
        URL url = new URL("https://" + server + "?server="
720
                +util.getLocalReplicationServerName()
721
                +"&action=readdata&docid=" + docid);
722
        String datafilePath = util.getOption("datafilepath");
723
        //register data file into xml_documents table and wite data file
724
        //into file system
725
        DocumentImpl.writeDataFileInReplication(url.openStream(), datafilePath,
726
                            docName, docType, docid, user,docHomeServer,server);
727
     }
728

    
729

    
730

    
731
    MetacatReplication.replLog("datafile " + docid + " added to DB with " +
732
                                 "action " + dbaction);
733
    }
734
    catch(Exception e)
735
    {
736

    
737
      MetacatReplication.replErrorLog("Datafile " + docid +
738
                                      " failed to added to DB with " +
739
                                      "action " + dbaction + " because "+
740
                                       e.getMessage());
741
      MetaCatUtil.debugMessage
742
              ("ERROR in MetacatReplication.handleForceDataFileReplicate" +
743
                         "Request(): " + e.getMessage(), 30);
744
    }
745
  }
746
  /**
747
   * Grants or denies a lock to a requesting host.
748
   * The servlet parameters of interrest are:
749
   * docid: the docid of the file the lock is being requested for
750
   * currentdate: the timestamp of the document on the remote server
751
   *
752
   */
753
  private void handleGetLockRequest(PrintWriter out, Hashtable params,
754
                                    HttpServletResponse response)
755
  {
756

    
757
    try
758
    {
759

    
760
      String docid = ((String[])params.get("docid"))[0];
761
      String remoteRev = ((String[])params.get("updaterev"))[0];
762
      DocumentImpl requestDoc = new DocumentImpl(docid);
763
      MetacatReplication.replLog("lock request for " + docid);
764
      int localRevInt = requestDoc.getRev();
765
      int remoteRevInt = Integer.parseInt(remoteRev);
766

    
767
      if(remoteRevInt >= localRevInt)
768
      {
769
        if(!fileLocks.contains(docid))
770
        { //grant the lock if it is not already locked
771
          fileLocks.add(0, docid); //insert at the beginning of the queue Vector
772
          //send a message back to the the remote host authorizing the insert
773
          out.println("<lockgranted><docid>" +docid+ "</docid></lockgranted>");
774
          lockThread = new Thread(this);
775
          lockThread.setPriority(Thread.MIN_PRIORITY);
776
          lockThread.start();
777
          MetacatReplication.replLog("lock granted for " + docid);
778
        }
779
        else
780
        { //deny the lock
781
          out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
782
          MetacatReplication.replLog("lock denied for " + docid +
783
                                     "reason: file already locked");
784
        }
785
      }
786
      else
787
      {//deny the lock.
788
        out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
789
        MetacatReplication.replLog("lock denied for " + docid +
790
                                   "reason: client has outdated file");
791
      }
792
      //conn.close();
793
    }
794
    catch(Exception e)
795
    {
796
      System.out.println("error requesting file lock from MetacatReplication." +
797
                         "handleGetLockRequest: " + e.getMessage());
798
      e.printStackTrace(System.out);
799
    }
800
  }
801

    
802
  /**
803
   * Sends all of the xml_documents information encoded in xml to a requestor
804
   * the format is:
805
   * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
806
   *                  user_updated, home_server, public_access, rev)/>
807
   * all of the subelements of document info are #PCDATA
808
   */
809
  private void handleGetDocumentInfoRequest(PrintWriter out, Hashtable params,
810
                                        HttpServletResponse response)
811
  {
812
    String docid = ((String[])(params.get("docid")))[0];
813
    StringBuffer sb = new StringBuffer();
814

    
815
    try
816
    {
817

    
818
      DocumentImpl doc = new DocumentImpl(docid);
819
      sb.append("<documentinfo><docid>").append(docid);
820
      sb.append("</docid><docname>").append(doc.getDocname());
821
      sb.append("</docname><doctype>").append(doc.getDoctype());
822
      sb.append("</doctype>");
823
      sb.append("<user_owner>").append(doc.getUserowner());
824
      sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
825
      sb.append("</user_updated>");
826
      sb.append("<home_server>");
827
      sb.append(doc.getDocHomeServer());
828
      sb.append("</home_server>");
829
      sb.append("<public_access>").append(doc.getPublicaccess());
830
      sb.append("</public_access><rev>").append(doc.getRev());
831
      sb.append("</rev></documentinfo>");
832
      response.setContentType("text/xml");
833
      out.println(sb.toString());
834

    
835
    }
836
    catch (Exception e)
837
    {
838
      System.out.println("error in " +
839
                         "metacatReplication.handlegetdocumentinforequest: " +
840
                          e.getMessage());
841
    }
842

    
843
  }
844

    
845
  /**
846
   * Sends a datafile to a remote host
847
   */
848
  private void handleGetDataFileRequest(OutputStream outPut,
849
                            Hashtable params, HttpServletResponse response)
850

    
851
  {
852
    // File path for data file
853
    String filepath = util.getOption("datafilepath");
854
    // Request docid
855
    String docId = ((String[])(params.get("docid")))[0];
856
    //check if the doicd is null
857
    if (docId==null)
858
    {
859
      util.debugMessage("Didn't specify docid for replication", 20);
860
      return;
861
    }
862

    
863
    //try to open a https stream to test if the request server's public key
864
    //in the key store, this is security issue
865
    try
866
    {
867
      String server = ((String[])params.get("server"))[0];
868
      URL u = new URL("https://" + server + "?server="
869
                +util.getLocalReplicationServerName()
870
                +"&action=test");
871
      String test = MetacatReplication.getURLContent(u);
872
      //couldn't pass the test
873
      if (test.indexOf("successfully")==-1)
874
      {
875
        //response.setContentType("text/xml");
876
        //outPut.println("<error>Couldn't pass the trust test</error>");
877
        MetaCatUtil.debugMessage("Couldn't pass the trust test", 20);
878
        return;
879
      }
880
    }//try
881
    catch (Exception ee)
882
    {
883
      return;
884
    }//catch
885

    
886
    if(!filepath.endsWith("/"))
887
    {
888
          filepath += "/";
889
    }
890
    // Get file aboslute file name
891
    String filename = filepath + docId;
892

    
893
    //MIME type
894
    String contentType = null;
895
    if (filename.endsWith(".xml"))
896
    {
897
        contentType="text/xml";
898
    }
899
    else if (filename.endsWith(".css"))
900
    {
901
        contentType="text/css";
902
    }
903
    else if (filename.endsWith(".dtd"))
904
    {
905
        contentType="text/plain";
906
    }
907
    else if (filename.endsWith(".xsd"))
908
    {
909
        contentType="text/xml";
910
    }
911
    else if (filename.endsWith("/"))
912
    {
913
        contentType="text/html";
914
    }
915
    else
916
    {
917
        File f = new File(filename);
918
        if ( f.isDirectory() )
919
        {
920
           contentType="text/html";
921
        }
922
        else
923
        {
924
           contentType="application/octet-stream";
925
        }
926
     }
927

    
928
   // Set the mime type
929
   response.setContentType(contentType);
930

    
931
   // Get the content of the file
932
   FileInputStream fin = null;
933
   try
934
   {
935
      // FileInputStream to metacat
936
      fin = new FileInputStream(filename);
937
      // 4K buffer
938
      byte[] buf = new byte[4 * 1024];
939
      // Read data from file input stream to byte array
940
      int b = fin.read(buf);
941
      // Write to outStream from byte array
942
      while (b != -1)
943
      {
944
        outPut.write(buf, 0, b);
945
        b = fin.read(buf);
946
      }
947
      // close file input stream
948
      fin.close();
949

    
950
   }//try
951
   catch(Exception e)
952
   {
953
      System.out.println("error getting data file from MetacatReplication." +
954
                         "handlGetDataFileRequest " + e.getMessage());
955
      e.printStackTrace(System.out);
956
   }//catch
957

    
958
}
959

    
960

    
961
  /**
962
   * Sends a document to a remote host
963
   */
964
  private void handleGetDocumentRequest(PrintWriter out, Hashtable params,
965
                                        HttpServletResponse response)
966
  {
967

    
968
    try
969
    {
970
      //try to open a https stream to test if the request server's public key
971
      //in the key store, this is security issue
972
      String server = ((String[])params.get("server"))[0];
973
      URL u = new URL("https://" + server + "?server="
974
                +util.getLocalReplicationServerName()
975
                +"&action=test");
976
      String test = MetacatReplication.getURLContent(u);
977
      //couldn't pass the test
978
      if (test.indexOf("successfully")==-1)
979
      {
980
        response.setContentType("text/xml");
981
        out.println("<error>Couldn't pass the trust test</error>");
982
        out.close();
983
        return;
984
      }
985

    
986
      String docid = ((String[])(params.get("docid")))[0];
987

    
988
      DocumentImpl di = new DocumentImpl(docid);
989
      response.setContentType("text/xml");
990
      out.print(di.toString(null, null, true));
991

    
992
      MetacatReplication.replLog("document " + docid + " sent");
993

    
994
    }
995
    catch(Exception e)
996
    {
997
      MetaCatUtil.debugMessage("error getting document from MetacatReplication."
998
                          +"handlGetDocumentRequest " + e.getMessage(), 30);
999
      //e.printStackTrace(System.out);
1000
      response.setContentType("text/xml");
1001
      out.println("<error>"+e.getMessage()+"</error>");
1002
    }
1003

    
1004
  }
1005

    
1006
  /**
1007
   * Sends a list of all of the documents on this sever along with their
1008
   * revision numbers.
1009
   * The format is:
1010
   * <!ELEMENT replication (server, updates)>
1011
   * <!ELEMENT server (#PCDATA)>
1012
   * <!ELEMENT updates ((updatedDocument | deleteDocument)*)>
1013
   * <!ELEMENT updatedDocument (docid, rev, datafile*)>
1014
   * <!ELEMENT deletedDocument (docid, rev)>
1015
   * <!ELEMENT docid (#PCDATA)>
1016
   * <!ELEMENT rev (#PCDATA)>
1017
   * <!ELEMENT datafile (#PCDATA)>
1018
   * note that the rev in deletedDocument is always empty.  I just left
1019
   * it in there to make the parser implementation easier.
1020
   */
1021
  private void handleUpdateRequest(PrintWriter out, Hashtable params,
1022
                                    HttpServletResponse response)
1023
  {
1024
    // Checked out DBConnection
1025
    DBConnection dbConn = null;
1026
    // DBConenction serial number when checked it out
1027
    int serialNumber = -1;
1028
    PreparedStatement pstmt = null;
1029
    // Server list to store server info of xml_replication table
1030
    ReplicationServerList serverList = null;
1031

    
1032
    try
1033
    {
1034
      // Check out a DBConnection from pool
1035
      dbConn=DBConnectionPool.
1036
                  getDBConnection("MetacatReplication.handleUpdateRequest");
1037
      serialNumber=dbConn.getCheckOutSerialNumber();
1038
      // Create a server list from xml_replication table
1039
      serverList = new ReplicationServerList();
1040

    
1041
      // Get remote server name from param
1042
      String server = ((String[])params.get("server"))[0];
1043
      // If no servr name in param, return a error
1044
      if ( server == null || server.equals(""))
1045
      {
1046
        response.setContentType("text/xml");
1047
        out.println("<error>Request didn't specify server name</error>");
1048
        out.close();
1049
        return;
1050
      }//if
1051

    
1052
      //try to open a https stream to test if the request server's public key
1053
      //in the key store, this is security issue
1054
      URL u = new URL("https://" + server + "?server="
1055
                +util.getLocalReplicationServerName()
1056
                +"&action=test");
1057
      String test = MetacatReplication.getURLContent(u);
1058
      //couldn't pass the test
1059
      if (test.indexOf("successfully")==-1)
1060
      {
1061
        response.setContentType("text/xml");
1062
        out.println("<error>Couldn't pass the trust test</error>");
1063
        out.close();
1064
        return;
1065
      }
1066

    
1067

    
1068
      // Check if local host configure to replicate xml documents to remote
1069
      // server. If not send back a error message
1070
      if (!serverList.getReplicationValue(server))
1071
      {
1072
        response.setContentType("text/xml");
1073
        out.println
1074
        ("<error>Configuration not allow to replicate document to you</error>");
1075
        out.close();
1076
        return;
1077
      }//if
1078

    
1079
      // Store the sql command
1080
      StringBuffer docsql = new StringBuffer();
1081
      // Stroe the docid list
1082
      StringBuffer doclist = new StringBuffer();
1083
      // Store the deleted docid list
1084
      StringBuffer delsql = new StringBuffer();
1085
      // Store the data set file
1086
      Vector packageFiles = new Vector();
1087

    
1088
      // Append local server's name and replication servlet to doclist
1089
      doclist.append("<?xml version=\"1.0\"?><replication>");
1090
      doclist.append("<server>").append(util.getOption("server"));
1091
      doclist.append(util.getOption("replicationpath"));
1092
      doclist.append("</server><updates>");
1093

    
1094
      // Get correct docid that reside on this server according the requesting
1095
      // server's replicate and data replicate value in xml_replication table
1096
      docsql.append("select docid, rev, doctype from xml_documents ");
1097
      // If the localhost is not a hub to the remote server, only replicate
1098
      // the docid' which home server is local host (server_location =1)
1099
      if (!serverList.getHubValue(server))
1100
      {
1101
        docsql.append("where server_location = 1");
1102
      }
1103
      MetaCatUtil.debugMessage("Doc sql: "+docsql.toString(), 30);
1104

    
1105
      // Get any deleted documents
1106
      delsql.append("select distinct docid from ");
1107
      delsql.append("xml_revisions where docid not in (select docid from ");
1108
      delsql.append("xml_documents) ");
1109
      // If the localhost is not a hub to the remote server, only replicate
1110
      // the docid' which home server is local host (server_location =1)
1111
      if (!serverList.getHubValue(server))
1112
      {
1113
        delsql.append("and server_location = 1");
1114
      }
1115
      MetaCatUtil.debugMessage("Deleted sql: "+delsql.toString(), 30);
1116

    
1117

    
1118

    
1119
      // Get docid list of local host
1120
      pstmt = dbConn.prepareStatement(docsql.toString());
1121
      pstmt.execute();
1122
      ResultSet rs = pstmt.getResultSet();
1123
      boolean tablehasrows = rs.next();
1124
      //If metacat configed to replicate data file
1125
      //if ((util.getOption("replicationsenddata")).equals("on"))
1126
      if (serverList.getDataReplicationValue(server))
1127
      {
1128
        while(tablehasrows)
1129
        {
1130
          String recordDoctype = rs.getString(3);
1131
          Vector packagedoctypes = MetaCatUtil.getOptionList(
1132
                                     MetaCatUtil.getOption("packagedoctype"));
1133
          //if this is a package file, put it at the end
1134
          //because if a package file is read before all of the files it
1135
          //refers to are loaded then there is an error
1136
          if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1137
          {
1138
              //If this is not data file
1139
              if (!recordDoctype.equals("BIN"))
1140
              {
1141
                //for non-data file document
1142
                doclist.append("<updatedDocument>");
1143
                doclist.append("<docid>").append(rs.getString(1));
1144
                doclist.append("</docid><rev>").append(rs.getInt(2));
1145
                doclist.append("</rev>");
1146
                doclist.append("</updatedDocument>");
1147
              }//if
1148
              else
1149
              {
1150
                //for data file document, in datafile attributes
1151
                //we put "datafile" value there
1152
                doclist.append("<updatedDocument>");
1153
                doclist.append("<docid>").append(rs.getString(1));
1154
                doclist.append("</docid><rev>").append(rs.getInt(2));
1155
                doclist.append("</rev>");
1156
                doclist.append("<datafile>");
1157
                doclist.append(MetaCatUtil.getOption("datafileflag"));
1158
                doclist.append("</datafile>");
1159
                doclist.append("</updatedDocument>");
1160
              }//else
1161
          }//if packagedoctpes
1162
          else
1163
          { //the package files are saved to be put into the xml later.
1164
              Vector v = new Vector();
1165
              v.add(new String(rs.getString(1)));
1166
              v.add(new Integer(rs.getInt(2)));
1167
              packageFiles.add(new Vector(v));
1168
          }//esle
1169
          tablehasrows = rs.next();
1170
        }//while
1171
      }//if
1172
      else //metacat was configured not to send data file
1173
      {
1174
        while(tablehasrows)
1175
        {
1176
          String recordDoctype = rs.getString(3);
1177
          if(!recordDoctype.equals("BIN"))
1178
          { //don't replicate data files
1179
            Vector packagedoctypes = MetaCatUtil.getOptionList(
1180
                                     MetaCatUtil.getOption("packagedoctype"));
1181
            if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1182
            {   //if this is a package file, put it at the end
1183
              //because if a package file is read before all of the files it
1184
              //refers to are loaded then there is an error
1185
              doclist.append("<updatedDocument>");
1186
              doclist.append("<docid>").append(rs.getString(1));
1187
              doclist.append("</docid><rev>").append(rs.getInt(2));
1188
              doclist.append("</rev>");
1189
              doclist.append("</updatedDocument>");
1190
            }
1191
            else
1192
            { //the package files are saved to be put into the xml later.
1193
              Vector v = new Vector();
1194
              v.add(new String(rs.getString(1)));
1195
              v.add(new Integer(rs.getInt(2)));
1196
              packageFiles.add(new Vector(v));
1197
            }
1198
         }//if
1199
         tablehasrows = rs.next();
1200
        }//while
1201
      }//else
1202

    
1203
      pstmt = dbConn.prepareStatement(delsql.toString());
1204
      //usage count should increas 1
1205
      dbConn.increaseUsageCount(1);
1206

    
1207
      pstmt.execute();
1208
      rs = pstmt.getResultSet();
1209
      tablehasrows = rs.next();
1210
      while(tablehasrows)
1211
      { //handle the deleted documents
1212
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1213
        doclist.append("</docid><rev></rev></deletedDocument>");
1214
        //note that rev is always empty for deleted docs
1215
        tablehasrows = rs.next();
1216
      }
1217

    
1218
      //now we can put the package files into the xml results
1219
      for(int i=0; i<packageFiles.size(); i++)
1220
      {
1221
        Vector v = (Vector)packageFiles.elementAt(i);
1222
        doclist.append("<updatedDocument>");
1223
        doclist.append("<docid>").append((String)v.elementAt(0));
1224
        doclist.append("</docid><rev>");
1225
        doclist.append(((Integer)v.elementAt(1)).intValue());
1226
        doclist.append("</rev>");
1227
        doclist.append("</updatedDocument>");
1228
      }
1229

    
1230
      doclist.append("</updates></replication>");
1231
      MetaCatUtil.debugMessage("doclist: " + doclist.toString(), 40);
1232
      pstmt.close();
1233
      //conn.close();
1234
      response.setContentType("text/xml");
1235
      out.println(doclist.toString());
1236

    
1237
    }
1238
    catch(Exception e)
1239
    {
1240
      MetaCatUtil.debugMessage("error in MetacatReplication." +
1241
                         "handleupdaterequest: " + e.getMessage(), 30);
1242
      //e.printStackTrace(System.out);
1243
      response.setContentType("text/xml");
1244
      out.println("<error>"+e.getMessage()+"</error>");
1245
    }
1246
    finally
1247
    {
1248
      try
1249
      {
1250
        pstmt.close();
1251
      }//try
1252
      catch (SQLException ee)
1253
      {
1254
        MetaCatUtil.debugMessage("Error in MetacatReplication." +
1255
                "handleUpdaterequest to close pstmt: "+ee.getMessage(), 30);
1256
      }//catch
1257
      finally
1258
      {
1259
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1260
      }//finally
1261
    }//finally
1262

    
1263
  }//handlUpdateRequest
1264

    
1265
  /**
1266
   * Returns the xml_catalog table encoded in xml
1267
   */
1268
  public static String getCatalogXML()
1269
  {
1270
    return handleGetCatalogRequest(null, null, null, false);
1271
  }
1272

    
1273
  /**
1274
   * Sends the contents of the xml_catalog table encoded in xml
1275
   * The xml format is:
1276
   * <!ELEMENT xml_catalog (row*)>
1277
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1278
   *                system_id)>
1279
   * All of the sub elements of row are #PCDATA
1280

    
1281
   * If printFlag == false then do not print to out.
1282
   */
1283
  private static String handleGetCatalogRequest(PrintWriter out,
1284
                                                Hashtable params,
1285
                                                HttpServletResponse response,
1286
                                                boolean printFlag)
1287
  {
1288
    DBConnection dbConn = null;
1289
    int serialNumber = -1;
1290
    PreparedStatement pstmt = null;
1291
    try
1292
    {
1293
      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1294
                                                "handleGetCatalogRequest");*/
1295
      dbConn=DBConnectionPool.
1296
                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
1297
      serialNumber=dbConn.getCheckOutSerialNumber();
1298
      pstmt = dbConn.prepareStatement("select entry_type, " +
1299
                              "source_doctype, target_doctype, public_id, " +
1300
                              "system_id from xml_catalog");
1301
      pstmt.execute();
1302
      ResultSet rs = pstmt.getResultSet();
1303
      boolean tablehasrows = rs.next();
1304
      StringBuffer sb = new StringBuffer();
1305
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1306
      while(tablehasrows)
1307
      {
1308
        sb.append("<row><entry_type>").append(rs.getString(1));
1309
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1310
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1311
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1312
        sb.append("</public_id><system_id>").append(rs.getString(5));
1313
        sb.append("</system_id></row>");
1314

    
1315
        tablehasrows = rs.next();
1316
      }
1317
      sb.append("</xml_catalog>");
1318
      //conn.close();
1319
      if(printFlag)
1320
      {
1321
        response.setContentType("text/xml");
1322
        out.println(sb.toString());
1323
      }
1324
      pstmt.close();
1325
      return sb.toString();
1326
    }
1327
    catch(Exception e)
1328
    {
1329

    
1330
      System.out.println("error in MetacatReplication.handleGetCatalogRequest:"+
1331
                          e.getMessage());
1332
      e.printStackTrace(System.out);
1333
      if(printFlag)
1334
      {
1335
        out.println("<error>"+e.getMessage()+"</error>");
1336
      }
1337
    }
1338
    finally
1339
    {
1340
      try
1341
      {
1342
        pstmt.close();
1343
      }//try
1344
      catch (SQLException ee)
1345
      {
1346
        MetaCatUtil.
1347
           debugMessage("Error in MetacatReplication.handleGetCatalogRequest: "
1348
           +ee.getMessage(), 30);
1349
      }//catch
1350
      finally
1351
      {
1352
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1353
      }//finally
1354
    }//finally
1355

    
1356
    return null;
1357
  }
1358

    
1359
  /**
1360
   * Sends the current system date to the remote server.  Using this action
1361
   * for replication gets rid of any problems with syncronizing clocks
1362
   * because a time specific to a document is always kept on its home server.
1363
   */
1364
  private void handleGetTimeRequest(PrintWriter out, Hashtable params,
1365
                                    HttpServletResponse response)
1366
  {
1367
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
1368
    java.util.Date localtime = new java.util.Date();
1369
    String dateString = formatter.format(localtime);
1370
    response.setContentType("text/xml");
1371

    
1372
    out.println("<timestamp>" + dateString + "</timestamp>");
1373
  }
1374

    
1375
  /**
1376
   * this method handles the timeout for a file lock.  when a lock is
1377
   * granted it is granted for 30 seconds.  When this thread runs out
1378
   * it deletes the docid from the queue, thus eliminating the lock.
1379
   */
1380
  public void run()
1381
  {
1382
    try
1383
    {
1384
      MetaCatUtil.debugMessage("thread started for docid: " +
1385
                               (String)fileLocks.elementAt(0), 45);
1386

    
1387
      Thread.sleep(30000); //the lock will expire in 30 seconds
1388
      MetaCatUtil.debugMessage("thread for docid: " +
1389
                             (String)fileLocks.elementAt(fileLocks.size() - 1) +
1390
                              " exiting.", 45);
1391

    
1392
      fileLocks.remove(fileLocks.size() - 1);
1393
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1394
      //in the vector, the first one inserted will be removed.
1395
    }
1396
    catch(Exception e)
1397
    {
1398
      MetaCatUtil.debugMessage("error in file lock thread from " +
1399
                                "MetacatReplication.run: " + e.getMessage(), 30);
1400
    }
1401
  }
1402

    
1403
  /**
1404
   * Returns the name of a server given a serverCode
1405
   * @param serverCode the serverid of the server
1406
   * @return the servername or null if the specified serverCode does not
1407
   *         exist.
1408
   */
1409
  public static String getServerNameForServerCode(int serverCode)
1410
  {
1411
    //System.out.println("serverid: " + serverCode);
1412
    DBConnection dbConn = null;
1413
    int serialNumber = -1;
1414
    PreparedStatement pstmt = null;
1415
    try
1416
    {
1417
      dbConn=DBConnectionPool.
1418
                  getDBConnection("MetacatReplication.getServer");
1419
      serialNumber=dbConn.getCheckOutSerialNumber();
1420
      String sql = new String("select server from " +
1421
                              "xml_replication where serverid = " +
1422
                              serverCode);
1423
      pstmt = dbConn.prepareStatement(sql);
1424
      //System.out.println("getserver sql: " + sql);
1425
      pstmt.execute();
1426
      ResultSet rs = pstmt.getResultSet();
1427
      boolean tablehasrows = rs.next();
1428
      if(tablehasrows)
1429
      {
1430
        //System.out.println("server: " + rs.getString(1));
1431
        return rs.getString(1);
1432
      }
1433

    
1434
      //conn.close();
1435
    }
1436
    catch(Exception e)
1437
    {
1438
      System.out.println("Error in MetacatReplication.getServer: " +
1439
                          e.getMessage());
1440
    }
1441
    finally
1442
    {
1443
      try
1444
      {
1445
        pstmt.close();
1446
      }//try
1447
      catch (SQLException ee)
1448
      {
1449
        MetaCatUtil.debugMessage("Error in MetacactReplication.getserver: "+
1450
                                    ee.getMessage(), 30);
1451
      }//catch
1452
      finally
1453
      {
1454
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1455
      }//fianlly
1456
    }//finally
1457

    
1458

    
1459

    
1460
    return null;
1461
      //return null if the server does not exist
1462
  }
1463

    
1464
  /**
1465
   * Returns a server code given a server name
1466
   * @param server the name of the server
1467
   * @return integer > 0 representing the code of the server, 0 if the server
1468
   *  does not exist.
1469
   */
1470
  public static int getServerCodeForServerName(String server) throws Exception
1471
  {
1472
    DBConnection dbConn = null;
1473
    int serialNumber = -1;
1474
    PreparedStatement pstmt = null;
1475
    int serverCode = 0;
1476

    
1477
    try {
1478

    
1479
      //conn = util.openDBConnection();
1480
      dbConn=DBConnectionPool.
1481
                  getDBConnection("MetacatReplication.getServerCode");
1482
      serialNumber=dbConn.getCheckOutSerialNumber();
1483
      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
1484
                                    "WHERE server LIKE '" + server + "'");
1485
      pstmt.execute();
1486
      ResultSet rs = pstmt.getResultSet();
1487
      boolean tablehasrows = rs.next();
1488
      if ( tablehasrows ) {
1489
        serverCode = rs.getInt(1);
1490
        pstmt.close();
1491
        //conn.close();
1492
        return serverCode;
1493
      }
1494

    
1495
    } catch(Exception e) {
1496
      throw e;
1497

    
1498
    } finally {
1499
      try
1500
      {
1501
        pstmt.close();
1502
        //conn.close();
1503
       }//try
1504
       catch(Exception ee)
1505
       {
1506
         MetaCatUtil.debugMessage("Error in MetacatReplicatio.getServerCode: "
1507
                                  +ee.getMessage(), 30);
1508

    
1509
       }//catch
1510
       finally
1511
       {
1512
         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1513
       }//finally
1514
    }//finally
1515

    
1516
    return serverCode;
1517
  }
1518

    
1519
  /**
1520
   * Method to get a host server information for given docid
1521
   * @param conn a connection to the database
1522
   */
1523
  public static Hashtable getHomeServerInfoForDocId(String docId)
1524
  {
1525
    Hashtable sl = new Hashtable();
1526
    DBConnection dbConn = null;
1527
    int serialNumber = -1;
1528
    //MetaCatUtil ut=new MetaCatUtil();
1529
    docId=MetaCatUtil.getDocIdFromString(docId);
1530
    PreparedStatement pstmt=null;
1531
    int serverLocation;
1532
    try
1533
    {
1534
      //get conection
1535
      dbConn=DBConnectionPool.
1536
                  getDBConnection("ReplicationHandler.getHomeServer");
1537
      serialNumber=dbConn.getCheckOutSerialNumber();
1538
      //get a server location from xml_document table
1539
      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
1540
                                            +"where docid = ?");
1541
      pstmt.setString(1, docId);
1542
      pstmt.execute();
1543
      ResultSet serverName = pstmt.getResultSet();
1544
      //get a server location
1545
      if(serverName.next())
1546
      {
1547
        serverLocation=serverName.getInt(1);
1548
        pstmt.close();
1549
      }
1550
      else
1551
      {
1552
        pstmt.close();
1553
        //ut.returnConnection(conn);
1554
        return null;
1555
      }
1556
      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
1557
                        "from xml_replication where serverid = ?");
1558
      //increase usage count
1559
      dbConn.increaseUsageCount(1);
1560
      pstmt.setInt(1, serverLocation);
1561
      pstmt.execute();
1562
      ResultSet rs = pstmt.getResultSet();
1563
      boolean tableHasRows = rs.next();
1564
      if (tableHasRows)
1565
      {
1566

    
1567
          String server = rs.getString(1);
1568
          String last_checked = rs.getString(2);
1569
          if(!server.equals("localhost"))
1570
          {
1571
            sl.put(server, last_checked);
1572
          }
1573

    
1574
      }
1575
      else
1576
      {
1577
        pstmt.close();
1578
        //ut.returnConnection(conn);
1579
        return null;
1580
      }
1581
      pstmt.close();
1582
    }
1583
    catch(Exception e)
1584
    {
1585
      System.out.println("error in replicationHandler.getHomeServer(): " +
1586
                         e.getMessage());
1587
    }
1588
    finally
1589
    {
1590
      try
1591
      {
1592
        pstmt.close();
1593
        //ut.returnConnection(conn);
1594
      }
1595
      catch (Exception ee)
1596
      {
1597
        MetaCatUtil.debugMessage("Eror irn rplicationHandler.getHomeServer() "+
1598
                          "to close pstmt: "+ee.getMessage(), 30);
1599
      }
1600
      finally
1601
      {
1602
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1603
      }
1604

    
1605
    }//finally
1606
    return sl;
1607
  }
1608

    
1609
  /**
1610
   * Returns a home server location  given a accnum
1611
   * @param accNum , given accNum for a document
1612
   *
1613
   */
1614
  public static int getHomeServerCodeForDocId(String accNum) throws Exception
1615
  {
1616
    DBConnection dbConn = null;
1617
    int serialNumber = -1;
1618
    PreparedStatement pstmt = null;
1619
    int serverCode = 1;
1620
    //MetaCatUtil ut = new MetaCatUtil();
1621
    String docId=MetaCatUtil.getDocIdFromString(accNum);
1622

    
1623
    try
1624
    {
1625

    
1626
      // Get DBConnection
1627
      dbConn=DBConnectionPool.
1628
                  getDBConnection("ReplicationHandler.getServerLocation");
1629
      serialNumber=dbConn.getCheckOutSerialNumber();
1630
      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1631
                              + "WHERE docid LIKE '" + docId + "'");
1632
      pstmt.execute();
1633
      ResultSet rs = pstmt.getResultSet();
1634
      boolean tablehasrows = rs.next();
1635
      //If a document is find, return the server location for it
1636
      if ( tablehasrows )
1637
      {
1638
        serverCode = rs.getInt(1);
1639
        pstmt.close();
1640
        //conn.close();
1641
        return serverCode;
1642
      }
1643
      //if couldn't find in xml_documents table, we think server code is 1
1644
      //(this is new document)
1645
      else
1646
      {
1647
        pstmt.close();
1648
        //conn.close();
1649
        return serverCode;
1650
      }
1651

    
1652
    }
1653
    catch(Exception e)
1654
    {
1655

    
1656
      throw e;
1657

    
1658
    }
1659
    finally
1660
    {
1661
      try
1662
      {
1663
        pstmt.close();
1664
        //conn.close();
1665

    
1666
      }
1667
      catch(Exception ee)
1668
      {
1669
        MetaCatUtil.debugMessage("Erorr in Replication.getServerLocation "+
1670
                     "to close pstmt"+ee.getMessage(), 30);
1671
      }
1672
      finally
1673
      {
1674
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1675
      }//finally
1676
    }//finally
1677
   //return serverCode;
1678
  }
1679

    
1680

    
1681

    
1682
  /**
1683
   * This method returns the content of a url
1684
   * @param u the url to return the content from
1685
   * @return a string representing the content of the url
1686
   * @throws java.io.IOException
1687
   */
1688
  public static String getURLContent(URL u) throws java.io.IOException
1689
  {
1690
    char istreamChar;
1691
    int istreamInt;
1692
    MetaCatUtil.debugMessage("Before open the stream"+u.toString(), 50);
1693
    InputStream input = u.openStream();
1694
    MetaCatUtil.debugMessage("Afetr open the stream"+u.toString(), 50);
1695
    InputStreamReader istream = new InputStreamReader(input);
1696
    StringBuffer serverResponse = new StringBuffer();
1697
    while((istreamInt = istream.read()) != -1)
1698
    {
1699
      istreamChar = (char)istreamInt;
1700
      serverResponse.append(istreamChar);
1701
    }
1702
    istream.close();
1703
    input.close();
1704

    
1705
    return serverResponse.toString();
1706
  }
1707

    
1708
  /**
1709
   * Method for writing replication messages to a log file specified in
1710
   * metacat.properties
1711
   */
1712
  public static void replLog(String message)
1713
  {
1714
    try
1715
    {
1716
      FileOutputStream fos = new FileOutputStream(
1717
                                 util.getOption("replicationlog"), true);
1718
      PrintWriter pw = new PrintWriter(fos);
1719
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1720
      java.util.Date localtime = new java.util.Date();
1721
      String dateString = formatter.format(localtime);
1722
      dateString += " :: " + message;
1723
      //time stamp each entry
1724
      pw.println(dateString);
1725
      pw.flush();
1726
    }
1727
    catch(Exception e)
1728
    {
1729
      System.out.println("error writing to replication log from " +
1730
                         "MetacatReplication.replLog: " + e.getMessage());
1731
      //e.printStackTrace(System.out);
1732
    }
1733
  }
1734

    
1735
  /**
1736
   * Method for writing replication messages to a log file specified in
1737
   * metacat.properties
1738
   */
1739
  public static void replErrorLog(String message)
1740
  {
1741
    try
1742
    {
1743
      FileOutputStream fos = new FileOutputStream(
1744
                                 util.getOption("replicationerrorlog"), true);
1745
      PrintWriter pw = new PrintWriter(fos);
1746
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1747
      java.util.Date localtime = new java.util.Date();
1748
      String dateString = formatter.format(localtime);
1749
      dateString += " :: " + message;
1750
      //time stamp each entry
1751
      pw.println(dateString);
1752
      pw.flush();
1753
    }
1754
    catch(Exception e)
1755
    {
1756
      System.out.println("error writing to replication log from " +
1757
                         "MetacatReplication.replLog: " + e.getMessage());
1758
      //e.printStackTrace(System.out);
1759
    }
1760
  }
1761

    
1762
  /**
1763
   * Returns true if the replicate field for server in xml_replication is 1.
1764
   * Returns false otherwise
1765
   */
1766
  public static boolean replToServer(String server)
1767
  {
1768
    DBConnection dbConn = null;
1769
    int serialNumber = -1;
1770
    PreparedStatement pstmt = null;
1771
    try
1772
    {
1773
      dbConn=DBConnectionPool.
1774
                  getDBConnection("MetacatReplication.repltoServer");
1775
      serialNumber=dbConn.getCheckOutSerialNumber();
1776
      pstmt = dbConn.prepareStatement("select replicate from " +
1777
                                    "xml_replication where server like '" +
1778
                                     server + "'");
1779
      pstmt.execute();
1780
      ResultSet rs = pstmt.getResultSet();
1781
      boolean tablehasrows = rs.next();
1782
      if(tablehasrows)
1783
      {
1784
        int i = rs.getInt(1);
1785
        if(i == 1)
1786
        {
1787
          pstmt.close();
1788
          //conn.close();
1789
          return true;
1790
        }
1791
        else
1792
        {
1793
          pstmt.close();
1794
          //conn.close();
1795
          return false;
1796
        }
1797
      }
1798
    }
1799
    catch(Exception e)
1800
    {
1801
      System.out.println("error in MetacatReplication.replToServer: " +
1802
                         e.getMessage());
1803
    }
1804
    finally
1805
    {
1806
      try
1807
      {
1808
        pstmt.close();
1809
        //conn.close();
1810
      }//try
1811
      catch(Exception ee)
1812
      {
1813
        MetaCatUtil.debugMessage("Error in MetacatReplication.replToServer: "
1814
                                  +ee.getMessage(), 30);
1815
      }//catch
1816
      finally
1817
      {
1818
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1819
      }//finally
1820
    }//finally
1821
    return false;
1822
    //the default if this server does not exist is to not replicate to it.
1823
  }
1824

    
1825

    
1826
}
(44-44/63)