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

    
27
package edu.ucsb.nceas.metacat;
28

    
29
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
30
import java.util.*;
31
import java.util.Date;
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.apache.log4j.Logger;
41
import org.xml.sax.*;
42

    
43
public class MetacatReplication extends HttpServlet implements Runnable
44
{
45
  private long timeInterval;
46
  private Date firstTime;
47
  private boolean timedReplicationIsOn = false;
48
  Timer replicationDaemon;
49
  private static MetaCatUtil util = new MetaCatUtil();
50
  private Vector fileLocks = new Vector();
51
  private Thread lockThread = null;
52
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
53
  public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
54
  private static final String TIMEREPLICATION = "timedreplication";
55
  private static final String TIMEREPLICATIONINTERVAl = "timedreplicationinterval";
56
  private static final String FIRSTTIME  = "firsttimedreplication";
57
  private static final int    TIMEINTERVALLIMIT = 7200000;
58
  private static Logger logMetacat = Logger.getLogger(MetacatReplication.class);
59

    
60
  /**
61
   * Initialize the servlet by creating appropriate database connections
62
   */
63
  public void init(ServletConfig config) throws ServletException
64
  {
65
     //initialize db connections to handle any update requests
66
    MetaCatUtil util = new MetaCatUtil();
67
    //deltaT = util.getOption("deltaT");
68
    //the default deltaT can be set from metacat.properties
69
    //create a thread to do the delta-T check but don't execute it yet
70
    replicationDaemon = new Timer(true);
71
    try
72
    {
73
       timedReplicationIsOn = (new Boolean(util.getOption(TIMEREPLICATION ).trim())).booleanValue();
74
       logMetacat.info("The timed replication on is"+timedReplicationIsOn);
75
       timeInterval = (new Long(util.getOption(TIMEREPLICATIONINTERVAl).trim())).longValue();
76
       logMetacat.warn("The timed replication time Inerval is "+ timeInterval);
77
       String firstTimeStr = util.getOption(FIRSTTIME);
78
       logMetacat.warn("first replication time form property is "+firstTimeStr);
79
       firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
80
       logMetacat.warn("After combine current time, the real first time is "
81
                                +firstTime.toString()+" minisec");
82
       // set up time replication if it is on
83
       if (timedReplicationIsOn)
84
       {
85
           replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime, timeInterval);
86
           MetacatReplication.replLog("deltaT handler started with rate=" +
87
                   timeInterval + " mini seconds at " +firstTime.toString());
88
       }
89
    }
90
    catch (Exception e)
91
    {
92
        // the timed replication in Metacat.properties file has problem
93
        // so timed replication is setting to false;
94
        logMetacat.error("Couldn't set up timed replication "+
95
                     " in Metacat replication servlet init because " +
96
                 e.getMessage());
97
        MetacatReplication.replErrorLog("Couldn't set up timed replication "+
98
                " in Metacat replication servlet init because " +
99
                e.getMessage());
100
        timedReplicationIsOn = false;
101
    }
102
    
103
  }
104

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

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

    
237

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

    
293

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
511
  }
512

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

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

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

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

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

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

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

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

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

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

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

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

    
658
      MetacatReplication.replLog("document " + docid + " added to DB with " +
659
                                 "action " + dbaction);
660
    }//try
661
    catch(Exception e)
662
    {
663
      MetacatReplication.replErrorLog("document " + docid +
664
                                      " failed to added to DB with " +
665
                                      "action " + dbaction + " because "+
666
                                       e.getMessage());
667
      logMetacat.error("ERROR in MetacatReplication.handleForceReplicate" +
668
                         "Request(): " + e.getMessage());
669

    
670
    }//catch
671
    finally
672
    {
673
      // Return the checked out DBConnection
674
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
675
    }//finally
676
  }
677

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

    
705
  }//catch
706

    
707
}
708

    
709

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

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

    
734
    // Overide or not
735
    boolean override = false;
736
    // dbaction - update or insert
737
    String dbaction=null;
738

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

    
753
      MetacatReplication.replLog("force replication request from " + server);
754
      logMetacat.info("Force replication request from: "+ server);
755
      logMetacat.info("Force replication docid: "+docid);
756
      logMetacat.info("Force replication action: "+dbaction);
757
      // get the document info from server
758
      URL docinfourl = new URL("https://" + server +
759
                               "?server="+util.getLocalReplicationServerName()
760
                               +"&action=getdocumentinfo&docid=" + docid);
761

    
762
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
763

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

    
771
      String docName = (String)docinfoHash.get("docname");
772

    
773
      String docType = (String)docinfoHash.get("doctype");
774

    
775
      String docHomeServer= (String)docinfoHash.get("home_server");
776
      
777
      String createdDate = (String)docinfoHash.get("date_created");
778
      
779
      String updatedDate = (String)docinfoHash.get("date_updated");
780
      logMetacat.info("docHomeServer of datafile: "+docHomeServer);
781

    
782

    
783

    
784
      //if action is delete, we don't delete the data file. Just archieve
785
      //the xml_documents
786
      /*if (dbaction.equals("delete"))
787
      {
788
        //conn = util.getConnection();
789
        DocumentImpl.delete(docid,user,null);
790
        //util.returnConnection(conn);
791
      }*/
792
      //To data file insert or update is same
793
      if (dbaction.equals("insert")||dbaction.equals("update"))
794
      {
795
        //Get data file and store it into local file system.
796
        // sending back readdata request to server
797
        URL url = new URL("https://" + server + "?server="
798
                +util.getLocalReplicationServerName()
799
                +"&action=readdata&docid=" + docid);
800
        String datafilePath = util.getOption("datafilepath");
801
        //register data file into xml_documents table and wite data file
802
        //into file system
803
        DocumentImpl.writeDataFileInReplication(url.openStream(), datafilePath,
804
                            docName, docType, docid, user,docHomeServer,server, 
805
                            DocumentImpl.DOCUMENTTABLE, false, createdDate, updatedDate);
806
                            //false means non-timed replication
807
     }
808

    
809

    
810

    
811
    MetacatReplication.replLog("datafile " + docid + " added to DB with " +
812
                                 "action " + dbaction);
813
    }
814
    catch(Exception e)
815
    {
816

    
817
      MetacatReplication.replErrorLog("Datafile " + docid +
818
                                      " failed to added to DB with " +
819
                                      "action " + dbaction + " because "+
820
                                       e.getMessage());
821
      logMetacat.error
822
              ("ERROR in MetacatReplication.handleForceDataFileReplicate" +
823
                         "Request(): " + e.getMessage());
824
    }
825
  }
826
  /**
827
   * Grants or denies a lock to a requesting host.
828
   * The servlet parameters of interrest are:
829
   * docid: the docid of the file the lock is being requested for
830
   * currentdate: the timestamp of the document on the remote server
831
   *
832
   */
833
  private void handleGetLockRequest(PrintWriter out, Hashtable params,
834
                                    HttpServletResponse response)
835
  {
836

    
837
    try
838
    {
839

    
840
      String docid = ((String[])params.get("docid"))[0];
841
      String remoteRev = ((String[])params.get("updaterev"))[0];
842
      DocumentImpl requestDoc = new DocumentImpl(docid);
843
      MetacatReplication.replLog("lock request for " + docid);
844
      int localRevInt = requestDoc.getRev();
845
      int remoteRevInt = Integer.parseInt(remoteRev);
846

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

    
882
  /**
883
   * Sends all of the xml_documents information encoded in xml to a requestor
884
   * the format is:
885
   * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
886
   *                  user_updated, home_server, public_access, rev)/>
887
   * all of the subelements of document info are #PCDATA
888
   */
889
  private void handleGetDocumentInfoRequest(PrintWriter out, Hashtable params,
890
                                        HttpServletResponse response)
891
  {
892
    String docid = ((String[])(params.get("docid")))[0];
893
    StringBuffer sb = new StringBuffer();
894

    
895
    try
896
    {
897

    
898
      DocumentImpl doc = new DocumentImpl(docid);
899
      sb.append("<documentinfo><docid>").append(docid);
900
      sb.append("</docid><docname>").append(doc.getDocname());
901
      sb.append("</docname><doctype>").append(doc.getDoctype());
902
      sb.append("</doctype>");
903
      sb.append("<user_owner>").append(doc.getUserowner());
904
      sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
905
      sb.append("</user_updated>");
906
      sb.append("<date_created>");
907
      sb.append(doc.getCreateDate());
908
      sb.append("</date_created>");
909
      sb.append("<date_updated>");
910
      sb.append(doc.getUpdateDate());
911
      sb.append("</date_updated>");
912
      sb.append("<home_server>");
913
      sb.append(doc.getDocHomeServer());
914
      sb.append("</home_server>");
915
      sb.append("<public_access>").append(doc.getPublicaccess());
916
      sb.append("</public_access><rev>").append(doc.getRev());
917
      sb.append("</rev></documentinfo>");
918
      response.setContentType("text/xml");
919
      out.println(sb.toString());
920

    
921
    }
922
    catch (Exception e)
923
    {
924
      System.out.println("error in " +
925
                         "metacatReplication.handlegetdocumentinforequest: " +
926
                          e.getMessage());
927
    }
928

    
929
  }
930

    
931
  /**
932
   * Sends a datafile to a remote host
933
   */
934
  private void handleGetDataFileRequest(OutputStream outPut,
935
                            Hashtable params, HttpServletResponse response)
936

    
937
  {
938
    // File path for data file
939
    String filepath = util.getOption("datafilepath");
940
    // Request docid
941
    String docId = ((String[])(params.get("docid")))[0];
942
    //check if the doicd is null
943
    if (docId==null)
944
    {
945
      logMetacat.error("Didn't specify docid for replication");
946
      return;
947
    }
948

    
949
    //try to open a https stream to test if the request server's public key
950
    //in the key store, this is security issue
951
    try
952
    {
953
      String server = ((String[])params.get("server"))[0];
954
      URL u = new URL("https://" + server + "?server="
955
                +util.getLocalReplicationServerName()
956
                +"&action=test");
957
      String test = MetacatReplication.getURLContent(u);
958
      //couldn't pass the test
959
      if (test.indexOf("successfully")==-1)
960
      {
961
        //response.setContentType("text/xml");
962
        //outPut.println("<error>Couldn't pass the trust test</error>");
963
        logMetacat.error("Couldn't pass the trust test");
964
        return;
965
      }
966
    }//try
967
    catch (Exception ee)
968
    {
969
      return;
970
    }//catch
971

    
972
    if(!filepath.endsWith("/"))
973
    {
974
          filepath += "/";
975
    }
976
    // Get file aboslute file name
977
    String filename = filepath + docId;
978

    
979
    //MIME type
980
    String contentType = null;
981
    if (filename.endsWith(".xml"))
982
    {
983
        contentType="text/xml";
984
    }
985
    else if (filename.endsWith(".css"))
986
    {
987
        contentType="text/css";
988
    }
989
    else if (filename.endsWith(".dtd"))
990
    {
991
        contentType="text/plain";
992
    }
993
    else if (filename.endsWith(".xsd"))
994
    {
995
        contentType="text/xml";
996
    }
997
    else if (filename.endsWith("/"))
998
    {
999
        contentType="text/html";
1000
    }
1001
    else
1002
    {
1003
        File f = new File(filename);
1004
        if ( f.isDirectory() )
1005
        {
1006
           contentType="text/html";
1007
        }
1008
        else
1009
        {
1010
           contentType="application/octet-stream";
1011
        }
1012
     }
1013

    
1014
   // Set the mime type
1015
   response.setContentType(contentType);
1016

    
1017
   // Get the content of the file
1018
   FileInputStream fin = null;
1019
   try
1020
   {
1021
      // FileInputStream to metacat
1022
      fin = new FileInputStream(filename);
1023
      // 4K buffer
1024
      byte[] buf = new byte[4 * 1024];
1025
      // Read data from file input stream to byte array
1026
      int b = fin.read(buf);
1027
      // Write to outStream from byte array
1028
      while (b != -1)
1029
      {
1030
        outPut.write(buf, 0, b);
1031
        b = fin.read(buf);
1032
      }
1033
      // close file input stream
1034
      fin.close();
1035

    
1036
   }//try
1037
   catch(Exception e)
1038
   {
1039
      System.out.println("error getting data file from MetacatReplication." +
1040
                         "handlGetDataFileRequest " + e.getMessage());
1041
      e.printStackTrace(System.out);
1042
   }//catch
1043

    
1044
}
1045

    
1046

    
1047
  /**
1048
   * Sends a document to a remote host
1049
   */
1050
  private void handleGetDocumentRequest(PrintWriter out, Hashtable params,
1051
                                        HttpServletResponse response)
1052
  {
1053

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

    
1072
      String docid = ((String[])(params.get("docid")))[0];
1073

    
1074
      DocumentImpl di = new DocumentImpl(docid);
1075
      response.setContentType("text/xml");
1076
      out.print(di.toString(null, null, true));
1077

    
1078
      MetacatReplication.replLog("document " + docid + " sent");
1079

    
1080
    }
1081
    catch(Exception e)
1082
    {
1083
      logMetacat.error("error getting document from MetacatReplication."
1084
                          +"handlGetDocumentRequest " + e.getMessage());
1085
      //e.printStackTrace(System.out);
1086
      response.setContentType("text/xml");
1087
      out.println("<error>"+e.getMessage()+"</error>");
1088
    }
1089

    
1090
  }
1091

    
1092
  /**
1093
   * Sends a list of all of the documents on this sever along with their
1094
   * revision numbers.
1095
   * The format is:
1096
   * <!ELEMENT replication (server, updates)>
1097
   * <!ELEMENT server (#PCDATA)>
1098
   * <!ELEMENT updates ((updatedDocument | deleteDocument | revisionDocument)*)>
1099
   * <!ELEMENT updatedDocument (docid, rev, datafile*)>
1100
   * <!ELEMENT deletedDocument (docid, rev)>
1101
   * <!ELEMENT revisionDocument (docid, rev, datafile*)>
1102
   * <!ELEMENT docid (#PCDATA)>
1103
   * <!ELEMENT rev (#PCDATA)>
1104
   * <!ELEMENT datafile (#PCDATA)>
1105
   * note that the rev in deletedDocument is always empty.  I just left
1106
   * it in there to make the parser implementation easier.
1107
   */
1108
  private void handleUpdateRequest(PrintWriter out, Hashtable params,
1109
                                    HttpServletResponse response)
1110
  {
1111
    // Checked out DBConnection
1112
    DBConnection dbConn = null;
1113
    // DBConenction serial number when checked it out
1114
    int serialNumber = -1;
1115
    PreparedStatement pstmt = null;
1116
    // Server list to store server info of xml_replication table
1117
    ReplicationServerList serverList = null;
1118

    
1119
    try
1120
    {
1121
      // Check out a DBConnection from pool
1122
      dbConn=DBConnectionPool.
1123
                  getDBConnection("MetacatReplication.handleUpdateRequest");
1124
      serialNumber=dbConn.getCheckOutSerialNumber();
1125
      // Create a server list from xml_replication table
1126
      serverList = new ReplicationServerList();
1127

    
1128
      // Get remote server name from param
1129
      String server = ((String[])params.get("server"))[0];
1130
      // If no servr name in param, return a error
1131
      if ( server == null || server.equals(""))
1132
      {
1133
        response.setContentType("text/xml");
1134
        out.println("<error>Request didn't specify server name</error>");
1135
        out.close();
1136
        return;
1137
      }//if
1138

    
1139
      //try to open a https stream to test if the request server's public key
1140
      //in the key store, this is security issue
1141
      URL u = new URL("https://" + server + "?server="
1142
                +util.getLocalReplicationServerName()
1143
                +"&action=test");
1144
      String test = MetacatReplication.getURLContent(u);
1145
      //couldn't pass the test
1146
      if (test.indexOf("successfully")==-1)
1147
      {
1148
        response.setContentType("text/xml");
1149
        out.println("<error>Couldn't pass the trust test</error>");
1150
        out.close();
1151
        return;
1152
      }
1153

    
1154

    
1155
      // Check if local host configure to replicate xml documents to remote
1156
      // server. If not send back a error message
1157
      if (!serverList.getReplicationValue(server))
1158
      {
1159
        response.setContentType("text/xml");
1160
        out.println
1161
        ("<error>Configuration not allow to replicate document to you</error>");
1162
        out.close();
1163
        return;
1164
      }//if
1165

    
1166
      // Store the sql command
1167
      StringBuffer docsql = new StringBuffer();
1168
      StringBuffer revisionSql = new StringBuffer();
1169
      // Stroe the docid list
1170
      StringBuffer doclist = new StringBuffer();
1171
      // Store the deleted docid list
1172
      StringBuffer delsql = new StringBuffer();
1173
      // Store the data set file
1174
      Vector packageFiles = new Vector();
1175

    
1176
      // Append local server's name and replication servlet to doclist
1177
      doclist.append("<?xml version=\"1.0\"?><replication>");
1178
      doclist.append("<server>").append(util.getLocalReplicationServerName());
1179
      //doclist.append(util.getOption("replicationpath"));
1180
      doclist.append("</server><updates>");
1181

    
1182
      // Get correct docid that reside on this server according the requesting
1183
      // server's replicate and data replicate value in xml_replication table
1184
      docsql.append(dbAdapter.getReplicationDocumentListSQL());
1185
      //docsql.append("select docid, rev, doctype from xml_documents where (docid not in (select a.docid from xml_documents a, xml_revisions b where a.docid=b.docid and a.rev<=b.rev)) ");
1186
      revisionSql.append("select docid, rev, doctype from xml_revisions ");
1187
      // If the localhost is not a hub to the remote server, only replicate
1188
      // the docid' which home server is local host (server_location =1)
1189
      if (!serverList.getHubValue(server))
1190
      {
1191
    	String serverLocationDoc = " and a.server_location = 1";
1192
        String serverLocationRev = "where server_location = 1";
1193
        docsql.append(serverLocationDoc);
1194
        revisionSql.append(serverLocationRev);
1195
      }
1196
      logMetacat.info("Doc sql: "+docsql.toString());
1197

    
1198
      // Get any deleted documents
1199
      delsql.append("select distinct docid from ");
1200
      delsql.append("xml_revisions where docid not in (select docid from ");
1201
      delsql.append("xml_documents) ");
1202
      // If the localhost is not a hub to the remote server, only replicate
1203
      // the docid' which home server is local host (server_location =1)
1204
      if (!serverList.getHubValue(server))
1205
      {
1206
        delsql.append("and server_location = 1");
1207
      }
1208
      logMetacat.info("Deleted sql: "+delsql.toString());
1209

    
1210

    
1211

    
1212
      // Get docid list of local host
1213
      pstmt = dbConn.prepareStatement(docsql.toString());
1214
      pstmt.execute();
1215
      ResultSet rs = pstmt.getResultSet();
1216
      boolean tablehasrows = rs.next();
1217
      //If metacat configed to replicate data file
1218
      //if ((util.getOption("replicationsenddata")).equals("on"))
1219
      boolean replicateData = serverList.getDataReplicationValue(server);
1220
      if (replicateData)
1221
      {
1222
        while(tablehasrows)
1223
        {
1224
          String recordDoctype = rs.getString(3);
1225
          Vector packagedoctypes = MetaCatUtil.getOptionList(
1226
                                     MetaCatUtil.getOption("packagedoctype"));
1227
          //if this is a package file, put it at the end
1228
          //because if a package file is read before all of the files it
1229
          //refers to are loaded then there is an error
1230
          if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1231
          {
1232
              //If this is not data file
1233
              if (!recordDoctype.equals("BIN"))
1234
              {
1235
                //for non-data file document
1236
                doclist.append("<updatedDocument>");
1237
                doclist.append("<docid>").append(rs.getString(1));
1238
                doclist.append("</docid><rev>").append(rs.getInt(2));
1239
                doclist.append("</rev>");
1240
                doclist.append("</updatedDocument>");
1241
              }//if
1242
              else
1243
              {
1244
                //for data file document, in datafile attributes
1245
                //we put "datafile" value there
1246
                doclist.append("<updatedDocument>");
1247
                doclist.append("<docid>").append(rs.getString(1));
1248
                doclist.append("</docid><rev>").append(rs.getInt(2));
1249
                doclist.append("</rev>");
1250
                doclist.append("<datafile>");
1251
                doclist.append(MetaCatUtil.getOption("datafileflag"));
1252
                doclist.append("</datafile>");
1253
                doclist.append("</updatedDocument>");
1254
              }//else
1255
          }//if packagedoctpes
1256
          else
1257
          { //the package files are saved to be put into the xml later.
1258
              Vector v = new Vector();
1259
              v.add(new String(rs.getString(1)));
1260
              v.add(new Integer(rs.getInt(2)));
1261
              packageFiles.add(new Vector(v));
1262
          }//esle
1263
          tablehasrows = rs.next();
1264
        }//while
1265
      }//if
1266
      else //metacat was configured not to send data file
1267
      {
1268
        while(tablehasrows)
1269
        {
1270
          String recordDoctype = rs.getString(3);
1271
          if(!recordDoctype.equals("BIN"))
1272
          { //don't replicate data files
1273
            Vector packagedoctypes = MetaCatUtil.getOptionList(
1274
                                     MetaCatUtil.getOption("packagedoctype"));
1275
            if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1276
            {   //if this is a package file, put it at the end
1277
              //because if a package file is read before all of the files it
1278
              //refers to are loaded then there is an error
1279
              doclist.append("<updatedDocument>");
1280
              doclist.append("<docid>").append(rs.getString(1));
1281
              doclist.append("</docid><rev>").append(rs.getInt(2));
1282
              doclist.append("</rev>");
1283
              doclist.append("</updatedDocument>");
1284
            }
1285
            else
1286
            { //the package files are saved to be put into the xml later.
1287
              Vector v = new Vector();
1288
              v.add(new String(rs.getString(1)));
1289
              v.add(new Integer(rs.getInt(2)));
1290
              packageFiles.add(new Vector(v));
1291
            }
1292
         }//if
1293
         tablehasrows = rs.next();
1294
        }//while
1295
      }//else
1296

    
1297
      pstmt = dbConn.prepareStatement(delsql.toString());
1298
      //usage count should increas 1
1299
      dbConn.increaseUsageCount(1);
1300

    
1301
      pstmt.execute();
1302
      rs = pstmt.getResultSet();
1303
      tablehasrows = rs.next();
1304
      while(tablehasrows)
1305
      { //handle the deleted documents
1306
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1307
        doclist.append("</docid><rev></rev></deletedDocument>");
1308
        //note that rev is always empty for deleted docs
1309
        tablehasrows = rs.next();
1310
      }
1311

    
1312
      //now we can put the package files into the xml results
1313
      for(int i=0; i<packageFiles.size(); i++)
1314
      {
1315
        Vector v = (Vector)packageFiles.elementAt(i);
1316
        doclist.append("<updatedDocument>");
1317
        doclist.append("<docid>").append((String)v.elementAt(0));
1318
        doclist.append("</docid><rev>");
1319
        doclist.append(((Integer)v.elementAt(1)).intValue());
1320
        doclist.append("</rev>");
1321
        doclist.append("</updatedDocument>");
1322
      }
1323
      // add revision doc list  
1324
      doclist.append(prepareRevisionDoc(dbConn,revisionSql.toString(),replicateData));
1325
        
1326
      doclist.append("</updates></replication>");
1327
      logMetacat.info("doclist: " + doclist.toString());
1328
      pstmt.close();
1329
      //conn.close();
1330
      response.setContentType("text/xml");
1331
      out.println(doclist.toString());
1332

    
1333
    }
1334
    catch(Exception e)
1335
    {
1336
      logMetacat.error("error in MetacatReplication." +
1337
                         "handleupdaterequest: " + e.getMessage());
1338
      //e.printStackTrace(System.out);
1339
      response.setContentType("text/xml");
1340
      out.println("<error>"+e.getMessage()+"</error>");
1341
    }
1342
    finally
1343
    {
1344
      try
1345
      {
1346
        pstmt.close();
1347
      }//try
1348
      catch (SQLException ee)
1349
      {
1350
        logMetacat.error("Error in MetacatReplication." +
1351
                "handleUpdaterequest to close pstmt: "+ee.getMessage());
1352
      }//catch
1353
      finally
1354
      {
1355
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1356
      }//finally
1357
    }//finally
1358

    
1359
  }//handlUpdateRequest
1360
  
1361
  /*
1362
   * This method will get the xml string for document in xml_revision
1363
   * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1364
   */
1365
  private String prepareRevisionDoc(DBConnection dbConn, String revSql, 
1366
                            boolean replicateData) throws Exception
1367
  {
1368
      logMetacat.warn("The revision document sql is "+ revSql);
1369
      StringBuffer revDocList = new StringBuffer();
1370
      PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1371
      //usage count should increas 1
1372
      dbConn.increaseUsageCount(1);
1373

    
1374
      pstmt.execute();
1375
      ResultSet rs = pstmt.getResultSet();
1376
      boolean tablehasrows = rs.next();
1377
      while(tablehasrows)
1378
      {
1379
        String recordDoctype = rs.getString(3);
1380
        
1381
        //If this is data file and it isn't configured to replicate data
1382
        if (recordDoctype.equals("BIN") && !replicateData)
1383
        {  
1384
            // do nothing
1385
            continue;
1386
        }
1387
        else
1388
        {  
1389
            
1390
            revDocList.append("<revisionDocument>");
1391
            revDocList.append("<docid>").append(rs.getString(1));
1392
            revDocList.append("</docid><rev>").append(rs.getInt(2));
1393
            revDocList.append("</rev>");
1394
            // data file
1395
            if (recordDoctype.equals("BIN"))
1396
            {
1397
                revDocList.append("<datafile>");
1398
                revDocList.append(MetaCatUtil.getOption("datafileflag"));
1399
                revDocList.append("</datafile>");
1400
            }
1401
            revDocList.append("</revisionDocument>");
1402
        
1403
         }//else
1404
         tablehasrows = rs.next();
1405
      }
1406
      //System.out.println("The revision list is"+ revDocList.toString());
1407
      return revDocList.toString();
1408
  }
1409

    
1410
  /**
1411
   * Returns the xml_catalog table encoded in xml
1412
   */
1413
  public static String getCatalogXML()
1414
  {
1415
    return handleGetCatalogRequest(null, null, null, false);
1416
  }
1417

    
1418
  /**
1419
   * Sends the contents of the xml_catalog table encoded in xml
1420
   * The xml format is:
1421
   * <!ELEMENT xml_catalog (row*)>
1422
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1423
   *                system_id)>
1424
   * All of the sub elements of row are #PCDATA
1425

    
1426
   * If printFlag == false then do not print to out.
1427
   */
1428
  private static String handleGetCatalogRequest(PrintWriter out,
1429
                                                Hashtable params,
1430
                                                HttpServletResponse response,
1431
                                                boolean printFlag)
1432
  {
1433
    DBConnection dbConn = null;
1434
    int serialNumber = -1;
1435
    PreparedStatement pstmt = null;
1436
    try
1437
    {
1438
      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1439
                                                "handleGetCatalogRequest");*/
1440
      dbConn=DBConnectionPool.
1441
                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
1442
      serialNumber=dbConn.getCheckOutSerialNumber();
1443
      pstmt = dbConn.prepareStatement("select entry_type, " +
1444
                              "source_doctype, target_doctype, public_id, " +
1445
                              "system_id from xml_catalog");
1446
      pstmt.execute();
1447
      ResultSet rs = pstmt.getResultSet();
1448
      boolean tablehasrows = rs.next();
1449
      StringBuffer sb = new StringBuffer();
1450
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1451
      while(tablehasrows)
1452
      {
1453
        sb.append("<row><entry_type>").append(rs.getString(1));
1454
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1455
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1456
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1457
        sb.append("</public_id><system_id>").append(rs.getString(5));
1458
        sb.append("</system_id></row>");
1459

    
1460
        tablehasrows = rs.next();
1461
      }
1462
      sb.append("</xml_catalog>");
1463
      //conn.close();
1464
      if(printFlag)
1465
      {
1466
        response.setContentType("text/xml");
1467
        out.println(sb.toString());
1468
      }
1469
      pstmt.close();
1470
      return sb.toString();
1471
    }
1472
    catch(Exception e)
1473
    {
1474

    
1475
      logMetacat.error("error in MetacatReplication.handleGetCatalogRequest:"+
1476
                          e.getMessage());
1477
      e.printStackTrace(System.out);
1478
      if(printFlag)
1479
      {
1480
        out.println("<error>"+e.getMessage()+"</error>");
1481
      }
1482
    }
1483
    finally
1484
    {
1485
      try
1486
      {
1487
        pstmt.close();
1488
      }//try
1489
      catch (SQLException ee)
1490
      {
1491
        logMetacat.error("Error in MetacatReplication.handleGetCatalogRequest: "
1492
           +ee.getMessage());
1493
      }//catch
1494
      finally
1495
      {
1496
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1497
      }//finally
1498
    }//finally
1499

    
1500
    return null;
1501
  }
1502

    
1503
  /**
1504
   * Sends the current system date to the remote server.  Using this action
1505
   * for replication gets rid of any problems with syncronizing clocks
1506
   * because a time specific to a document is always kept on its home server.
1507
   */
1508
  private void handleGetTimeRequest(PrintWriter out, Hashtable params,
1509
                                    HttpServletResponse response)
1510
  {
1511
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
1512
    java.util.Date localtime = new java.util.Date();
1513
    String dateString = formatter.format(localtime);
1514
    response.setContentType("text/xml");
1515

    
1516
    out.println("<timestamp>" + dateString + "</timestamp>");
1517
  }
1518

    
1519
  /**
1520
   * this method handles the timeout for a file lock.  when a lock is
1521
   * granted it is granted for 30 seconds.  When this thread runs out
1522
   * it deletes the docid from the queue, thus eliminating the lock.
1523
   */
1524
  public void run()
1525
  {
1526
    try
1527
    {
1528
      logMetacat.info("thread started for docid: " +
1529
                               (String)fileLocks.elementAt(0));
1530

    
1531
      Thread.sleep(30000); //the lock will expire in 30 seconds
1532
      logMetacat.info("thread for docid: " +
1533
                             (String)fileLocks.elementAt(fileLocks.size() - 1) +
1534
                              " exiting.");
1535

    
1536
      fileLocks.remove(fileLocks.size() - 1);
1537
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1538
      //in the vector, the first one inserted will be removed.
1539
    }
1540
    catch(Exception e)
1541
    {
1542
      logMetacat.error("error in file lock thread from " +
1543
                                "MetacatReplication.run: " + e.getMessage());
1544
    }
1545
  }
1546

    
1547
  /**
1548
   * Returns the name of a server given a serverCode
1549
   * @param serverCode the serverid of the server
1550
   * @return the servername or null if the specified serverCode does not
1551
   *         exist.
1552
   */
1553
  public static String getServerNameForServerCode(int serverCode)
1554
  {
1555
    //System.out.println("serverid: " + serverCode);
1556
    DBConnection dbConn = null;
1557
    int serialNumber = -1;
1558
    PreparedStatement pstmt = null;
1559
    try
1560
    {
1561
      dbConn=DBConnectionPool.
1562
                  getDBConnection("MetacatReplication.getServer");
1563
      serialNumber=dbConn.getCheckOutSerialNumber();
1564
      String sql = new String("select server from " +
1565
                              "xml_replication where serverid = " +
1566
                              serverCode);
1567
      pstmt = dbConn.prepareStatement(sql);
1568
      //System.out.println("getserver sql: " + sql);
1569
      pstmt.execute();
1570
      ResultSet rs = pstmt.getResultSet();
1571
      boolean tablehasrows = rs.next();
1572
      if(tablehasrows)
1573
      {
1574
        //System.out.println("server: " + rs.getString(1));
1575
        return rs.getString(1);
1576
      }
1577

    
1578
      //conn.close();
1579
    }
1580
    catch(Exception e)
1581
    {
1582
      System.out.println("Error in MetacatReplication.getServer: " +
1583
                          e.getMessage());
1584
    }
1585
    finally
1586
    {
1587
      try
1588
      {
1589
        pstmt.close();
1590
      }//try
1591
      catch (SQLException ee)
1592
      {
1593
        logMetacat.error("Error in MetacactReplication.getserver: "+
1594
                                    ee.getMessage());
1595
      }//catch
1596
      finally
1597
      {
1598
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1599
      }//fianlly
1600
    }//finally
1601

    
1602

    
1603

    
1604
    return null;
1605
      //return null if the server does not exist
1606
  }
1607

    
1608
  /**
1609
   * Returns a server code given a server name
1610
   * @param server the name of the server
1611
   * @return integer > 0 representing the code of the server, 0 if the server
1612
   *  does not exist.
1613
   */
1614
  public static int getServerCodeForServerName(String server) throws Exception
1615
  {
1616
    DBConnection dbConn = null;
1617
    int serialNumber = -1;
1618
    PreparedStatement pstmt = null;
1619
    int serverCode = 0;
1620

    
1621
    try {
1622

    
1623
      //conn = util.openDBConnection();
1624
      dbConn=DBConnectionPool.
1625
                  getDBConnection("MetacatReplication.getServerCode");
1626
      serialNumber=dbConn.getCheckOutSerialNumber();
1627
      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
1628
                                    "WHERE server LIKE '" + server + "'");
1629
      pstmt.execute();
1630
      ResultSet rs = pstmt.getResultSet();
1631
      boolean tablehasrows = rs.next();
1632
      if ( tablehasrows ) {
1633
        serverCode = rs.getInt(1);
1634
        pstmt.close();
1635
        //conn.close();
1636
        return serverCode;
1637
      }
1638

    
1639
    } catch(Exception e) {
1640
      throw e;
1641

    
1642
    } finally {
1643
      try
1644
      {
1645
        pstmt.close();
1646
        //conn.close();
1647
       }//try
1648
       catch(Exception ee)
1649
       {
1650
         logMetacat.error("Error in MetacatReplicatio.getServerCode: "
1651
                                  +ee.getMessage());
1652

    
1653
       }//catch
1654
       finally
1655
       {
1656
         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1657
       }//finally
1658
    }//finally
1659

    
1660
    return serverCode;
1661
  }
1662

    
1663
  /**
1664
   * Method to get a host server information for given docid
1665
   * @param conn a connection to the database
1666
   */
1667
  public static Hashtable getHomeServerInfoForDocId(String docId)
1668
  {
1669
    Hashtable sl = new Hashtable();
1670
    DBConnection dbConn = null;
1671
    int serialNumber = -1;
1672
    //MetaCatUtil ut=new MetaCatUtil();
1673
    docId=MetaCatUtil.getDocIdFromString(docId);
1674
    PreparedStatement pstmt=null;
1675
    int serverLocation;
1676
    try
1677
    {
1678
      //get conection
1679
      dbConn=DBConnectionPool.
1680
                  getDBConnection("ReplicationHandler.getHomeServer");
1681
      serialNumber=dbConn.getCheckOutSerialNumber();
1682
      //get a server location from xml_document table
1683
      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
1684
                                            +"where docid = ?");
1685
      pstmt.setString(1, docId);
1686
      pstmt.execute();
1687
      ResultSet serverName = pstmt.getResultSet();
1688
      //get a server location
1689
      if(serverName.next())
1690
      {
1691
        serverLocation=serverName.getInt(1);
1692
        pstmt.close();
1693
      }
1694
      else
1695
      {
1696
        pstmt.close();
1697
        //ut.returnConnection(conn);
1698
        return null;
1699
      }
1700
      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
1701
                        "from xml_replication where serverid = ?");
1702
      //increase usage count
1703
      dbConn.increaseUsageCount(1);
1704
      pstmt.setInt(1, serverLocation);
1705
      pstmt.execute();
1706
      ResultSet rs = pstmt.getResultSet();
1707
      boolean tableHasRows = rs.next();
1708
      if (tableHasRows)
1709
      {
1710

    
1711
          String server = rs.getString(1);
1712
          String last_checked = rs.getString(2);
1713
          if(!server.equals("localhost"))
1714
          {
1715
            sl.put(server, last_checked);
1716
          }
1717

    
1718
      }
1719
      else
1720
      {
1721
        pstmt.close();
1722
        //ut.returnConnection(conn);
1723
        return null;
1724
      }
1725
      pstmt.close();
1726
    }
1727
    catch(Exception e)
1728
    {
1729
      System.out.println("error in replicationHandler.getHomeServer(): " +
1730
                         e.getMessage());
1731
    }
1732
    finally
1733
    {
1734
      try
1735
      {
1736
        pstmt.close();
1737
        //ut.returnConnection(conn);
1738
      }
1739
      catch (Exception ee)
1740
      {
1741
        logMetacat.error("Eror irn rplicationHandler.getHomeServer() "+
1742
                          "to close pstmt: "+ee.getMessage());
1743
      }
1744
      finally
1745
      {
1746
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1747
      }
1748

    
1749
    }//finally
1750
    return sl;
1751
  }
1752

    
1753
  /**
1754
   * Returns a home server location  given a accnum
1755
   * @param accNum , given accNum for a document
1756
   *
1757
   */
1758
  public static int getHomeServerCodeForDocId(String accNum) throws Exception
1759
  {
1760
    DBConnection dbConn = null;
1761
    int serialNumber = -1;
1762
    PreparedStatement pstmt = null;
1763
    int serverCode = 1;
1764
    //MetaCatUtil ut = new MetaCatUtil();
1765
    String docId=MetaCatUtil.getDocIdFromString(accNum);
1766

    
1767
    try
1768
    {
1769

    
1770
      // Get DBConnection
1771
      dbConn=DBConnectionPool.
1772
                  getDBConnection("ReplicationHandler.getServerLocation");
1773
      serialNumber=dbConn.getCheckOutSerialNumber();
1774
      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1775
                              + "WHERE docid LIKE '" + docId + "'");
1776
      pstmt.execute();
1777
      ResultSet rs = pstmt.getResultSet();
1778
      boolean tablehasrows = rs.next();
1779
      //If a document is find, return the server location for it
1780
      if ( tablehasrows )
1781
      {
1782
        serverCode = rs.getInt(1);
1783
        pstmt.close();
1784
        //conn.close();
1785
        return serverCode;
1786
      }
1787
      //if couldn't find in xml_documents table, we think server code is 1
1788
      //(this is new document)
1789
      else
1790
      {
1791
        pstmt.close();
1792
        //conn.close();
1793
        return serverCode;
1794
      }
1795

    
1796
    }
1797
    catch(Exception e)
1798
    {
1799

    
1800
      throw e;
1801

    
1802
    }
1803
    finally
1804
    {
1805
      try
1806
      {
1807
        pstmt.close();
1808
        //conn.close();
1809

    
1810
      }
1811
      catch(Exception ee)
1812
      {
1813
        logMetacat.error("Erorr in Replication.getServerLocation "+
1814
                     "to close pstmt"+ee.getMessage());
1815
      }
1816
      finally
1817
      {
1818
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1819
      }//finally
1820
    }//finally
1821
   //return serverCode;
1822
  }
1823

    
1824

    
1825

    
1826
  /**
1827
   * This method returns the content of a url
1828
   * @param u the url to return the content from
1829
   * @return a string representing the content of the url
1830
   * @throws java.io.IOException
1831
   */
1832
  public static String getURLContent(URL u) throws java.io.IOException
1833
  {
1834
    char istreamChar;
1835
    int istreamInt;
1836
    logMetacat.info("Before open the stream"+u.toString());
1837
    InputStream input = u.openStream();
1838
    logMetacat.info("Afetr open the stream"+u.toString());
1839
    InputStreamReader istream = new InputStreamReader(input);
1840
    StringBuffer serverResponse = new StringBuffer();
1841
    while((istreamInt = istream.read()) != -1)
1842
    {
1843
      istreamChar = (char)istreamInt;
1844
      serverResponse.append(istreamChar);
1845
    }
1846
    istream.close();
1847
    input.close();
1848

    
1849
    return serverResponse.toString();
1850
  }
1851

    
1852
  /**
1853
   * Method for writing replication messages to a log file specified in
1854
   * metacat.properties
1855
   */
1856
  public static void replLog(String message)
1857
  {
1858
    try
1859
    {
1860
      FileOutputStream fos = new FileOutputStream(
1861
                                 util.getOption("replicationlog"), true);
1862
      PrintWriter pw = new PrintWriter(fos);
1863
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1864
      java.util.Date localtime = new java.util.Date();
1865
      String dateString = formatter.format(localtime);
1866
      dateString += " :: " + message;
1867
      //time stamp each entry
1868
      pw.println(dateString);
1869
      pw.flush();
1870
    }
1871
    catch(Exception e)
1872
    {
1873
      System.out.println("error writing to replication log from " +
1874
                         "MetacatReplication.replLog: " + e.getMessage());
1875
      //e.printStackTrace(System.out);
1876
    }
1877
  }
1878

    
1879
  /**
1880
   * Method for writing replication messages to a log file specified in
1881
   * metacat.properties
1882
   */
1883
  public static void replErrorLog(String message)
1884
  {
1885
    try
1886
    {
1887
      FileOutputStream fos = new FileOutputStream(
1888
                                 util.getOption("replicationerrorlog"), true);
1889
      PrintWriter pw = new PrintWriter(fos);
1890
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1891
      java.util.Date localtime = new java.util.Date();
1892
      String dateString = formatter.format(localtime);
1893
      dateString += " :: " + message;
1894
      //time stamp each entry
1895
      pw.println(dateString);
1896
      pw.flush();
1897
    }
1898
    catch(Exception e)
1899
    {
1900
      System.out.println("error writing to replication log from " +
1901
                         "MetacatReplication.replLog: " + e.getMessage());
1902
      //e.printStackTrace(System.out);
1903
    }
1904
  }
1905

    
1906
  /**
1907
   * Returns true if the replicate field for server in xml_replication is 1.
1908
   * Returns false otherwise
1909
   */
1910
  public static boolean replToServer(String server)
1911
  {
1912
    DBConnection dbConn = null;
1913
    int serialNumber = -1;
1914
    PreparedStatement pstmt = null;
1915
    try
1916
    {
1917
      dbConn=DBConnectionPool.
1918
                  getDBConnection("MetacatReplication.repltoServer");
1919
      serialNumber=dbConn.getCheckOutSerialNumber();
1920
      pstmt = dbConn.prepareStatement("select replicate from " +
1921
                                    "xml_replication where server like '" +
1922
                                     server + "'");
1923
      pstmt.execute();
1924
      ResultSet rs = pstmt.getResultSet();
1925
      boolean tablehasrows = rs.next();
1926
      if(tablehasrows)
1927
      {
1928
        int i = rs.getInt(1);
1929
        if(i == 1)
1930
        {
1931
          pstmt.close();
1932
          //conn.close();
1933
          return true;
1934
        }
1935
        else
1936
        {
1937
          pstmt.close();
1938
          //conn.close();
1939
          return false;
1940
        }
1941
      }
1942
    }
1943
    catch(Exception e)
1944
    {
1945
      System.out.println("error in MetacatReplication.replToServer: " +
1946
                         e.getMessage());
1947
    }
1948
    finally
1949
    {
1950
      try
1951
      {
1952
        pstmt.close();
1953
        //conn.close();
1954
      }//try
1955
      catch(Exception ee)
1956
      {
1957
        logMetacat.error("Error in MetacatReplication.replToServer: "
1958
                                  +ee.getMessage());
1959
      }//catch
1960
      finally
1961
      {
1962
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1963
      }//finally
1964
    }//finally
1965
    return false;
1966
    //the default if this server does not exist is to not replicate to it.
1967
  }
1968

    
1969

    
1970
}
(46-46/65)