Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements replication for metacat
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: tao $'
10
 *     '$Date: 2005-09-22 17:02:28 -0700 (Thu, 22 Sep 2005) $'
11
 * '$Revision: 2597 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

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

    
41
import org.xml.sax.*;
42

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

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

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

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

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

    
133

    
134

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

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

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

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

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

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

    
236

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

    
292

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
510
  }
511

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
701
  }//catch
702

    
703
}
704

    
705

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

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

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

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

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

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

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

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

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

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

    
775

    
776

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

    
800

    
801

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

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

    
828
    try
829
    {
830

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

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

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

    
886
    try
887
    {
888

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

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

    
914
  }
915

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

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

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

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

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

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

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

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

    
1029
}
1030

    
1031

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

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

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

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

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

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

    
1075
  }
1076

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

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

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

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

    
1139

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

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

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

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

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

    
1193

    
1194

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

    
1280
      pstmt = dbConn.prepareStatement(delsql.toString());
1281
      //usage count should increas 1
1282
      dbConn.increaseUsageCount(1);
1283

    
1284
      pstmt.execute();
1285
      rs = pstmt.getResultSet();
1286
      tablehasrows = rs.next();
1287
      while(tablehasrows)
1288
      { //handle the deleted documents
1289
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1290
        doclist.append("</docid><rev></rev></deletedDocument>");
1291
        //note that rev is always empty for deleted docs
1292
        tablehasrows = rs.next();
1293
      }
1294

    
1295
      //now we can put the package files into the xml results
1296
      for(int i=0; i<packageFiles.size(); i++)
1297
      {
1298
        Vector v = (Vector)packageFiles.elementAt(i);
1299
        doclist.append("<updatedDocument>");
1300
        doclist.append("<docid>").append((String)v.elementAt(0));
1301
        doclist.append("</docid><rev>");
1302
        doclist.append(((Integer)v.elementAt(1)).intValue());
1303
        doclist.append("</rev>");
1304
        doclist.append("</updatedDocument>");
1305
      }
1306
      // add revision doc list  
1307
      doclist.append(prepareRevisionDoc(dbConn,revisionSql.toString(),replicateData));
1308
        
1309
      doclist.append("</updates></replication>");
1310
      MetaCatUtil.debugMessage("doclist: " + doclist.toString(), 40);
1311
      pstmt.close();
1312
      //conn.close();
1313
      response.setContentType("text/xml");
1314
      out.println(doclist.toString());
1315

    
1316
    }
1317
    catch(Exception e)
1318
    {
1319
      MetaCatUtil.debugMessage("error in MetacatReplication." +
1320
                         "handleupdaterequest: " + e.getMessage(), 30);
1321
      //e.printStackTrace(System.out);
1322
      response.setContentType("text/xml");
1323
      out.println("<error>"+e.getMessage()+"</error>");
1324
    }
1325
    finally
1326
    {
1327
      try
1328
      {
1329
        pstmt.close();
1330
      }//try
1331
      catch (SQLException ee)
1332
      {
1333
        MetaCatUtil.debugMessage("Error in MetacatReplication." +
1334
                "handleUpdaterequest to close pstmt: "+ee.getMessage(), 30);
1335
      }//catch
1336
      finally
1337
      {
1338
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1339
      }//finally
1340
    }//finally
1341

    
1342
  }//handlUpdateRequest
1343
  
1344
  /*
1345
   * This method will get the xml string for document in xml_revision
1346
   * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1347
   */
1348
  private String prepareRevisionDoc(DBConnection dbConn, String revSql, 
1349
                            boolean replicateData) throws Exception
1350
  {
1351
      StringBuffer revDocList = new StringBuffer();
1352
      PreparedStatement pstmt = dbConn.prepareStatement(revSql.toString());
1353
      //usage count should increas 1
1354
      dbConn.increaseUsageCount(1);
1355

    
1356
      pstmt.execute();
1357
      ResultSet rs = pstmt.getResultSet();
1358
      boolean tablehasrows = rs.next();
1359
      while(tablehasrows)
1360
      {
1361
        String recordDoctype = rs.getString(3);
1362
        
1363
        //If this is data file and it isn't configured to replicate data
1364
        if (recordDoctype.equals("BIN") && !replicateData)
1365
        {  
1366
            // do nothing
1367
            continue;
1368
        }
1369
        else
1370
        {  
1371
            
1372
            revDocList.append("<revisionDocument>");
1373
            revDocList.append("<docid>").append(rs.getString(1));
1374
            revDocList.append("</docid><rev>").append(rs.getInt(2));
1375
            revDocList.append("</rev>");
1376
            // data file
1377
            if (recordDoctype.equals("BIN"))
1378
            {
1379
                revDocList.append("<datafile>");
1380
                revDocList.append(MetaCatUtil.getOption("datafileflag"));
1381
                revDocList.append("</datafile>");
1382
            }
1383
            revDocList.append("</revsionDocument>");
1384
        
1385
         }//else
1386
      }
1387
      return revDocList.toString();
1388
  }
1389

    
1390
  /**
1391
   * Returns the xml_catalog table encoded in xml
1392
   */
1393
  public static String getCatalogXML()
1394
  {
1395
    return handleGetCatalogRequest(null, null, null, false);
1396
  }
1397

    
1398
  /**
1399
   * Sends the contents of the xml_catalog table encoded in xml
1400
   * The xml format is:
1401
   * <!ELEMENT xml_catalog (row*)>
1402
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1403
   *                system_id)>
1404
   * All of the sub elements of row are #PCDATA
1405

    
1406
   * If printFlag == false then do not print to out.
1407
   */
1408
  private static String handleGetCatalogRequest(PrintWriter out,
1409
                                                Hashtable params,
1410
                                                HttpServletResponse response,
1411
                                                boolean printFlag)
1412
  {
1413
    DBConnection dbConn = null;
1414
    int serialNumber = -1;
1415
    PreparedStatement pstmt = null;
1416
    try
1417
    {
1418
      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1419
                                                "handleGetCatalogRequest");*/
1420
      dbConn=DBConnectionPool.
1421
                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
1422
      serialNumber=dbConn.getCheckOutSerialNumber();
1423
      pstmt = dbConn.prepareStatement("select entry_type, " +
1424
                              "source_doctype, target_doctype, public_id, " +
1425
                              "system_id from xml_catalog");
1426
      pstmt.execute();
1427
      ResultSet rs = pstmt.getResultSet();
1428
      boolean tablehasrows = rs.next();
1429
      StringBuffer sb = new StringBuffer();
1430
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1431
      while(tablehasrows)
1432
      {
1433
        sb.append("<row><entry_type>").append(rs.getString(1));
1434
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1435
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1436
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1437
        sb.append("</public_id><system_id>").append(rs.getString(5));
1438
        sb.append("</system_id></row>");
1439

    
1440
        tablehasrows = rs.next();
1441
      }
1442
      sb.append("</xml_catalog>");
1443
      //conn.close();
1444
      if(printFlag)
1445
      {
1446
        response.setContentType("text/xml");
1447
        out.println(sb.toString());
1448
      }
1449
      pstmt.close();
1450
      return sb.toString();
1451
    }
1452
    catch(Exception e)
1453
    {
1454

    
1455
      System.out.println("error in MetacatReplication.handleGetCatalogRequest:"+
1456
                          e.getMessage());
1457
      e.printStackTrace(System.out);
1458
      if(printFlag)
1459
      {
1460
        out.println("<error>"+e.getMessage()+"</error>");
1461
      }
1462
    }
1463
    finally
1464
    {
1465
      try
1466
      {
1467
        pstmt.close();
1468
      }//try
1469
      catch (SQLException ee)
1470
      {
1471
        MetaCatUtil.
1472
           debugMessage("Error in MetacatReplication.handleGetCatalogRequest: "
1473
           +ee.getMessage(), 30);
1474
      }//catch
1475
      finally
1476
      {
1477
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1478
      }//finally
1479
    }//finally
1480

    
1481
    return null;
1482
  }
1483

    
1484
  /**
1485
   * Sends the current system date to the remote server.  Using this action
1486
   * for replication gets rid of any problems with syncronizing clocks
1487
   * because a time specific to a document is always kept on its home server.
1488
   */
1489
  private void handleGetTimeRequest(PrintWriter out, Hashtable params,
1490
                                    HttpServletResponse response)
1491
  {
1492
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
1493
    java.util.Date localtime = new java.util.Date();
1494
    String dateString = formatter.format(localtime);
1495
    response.setContentType("text/xml");
1496

    
1497
    out.println("<timestamp>" + dateString + "</timestamp>");
1498
  }
1499

    
1500
  /**
1501
   * this method handles the timeout for a file lock.  when a lock is
1502
   * granted it is granted for 30 seconds.  When this thread runs out
1503
   * it deletes the docid from the queue, thus eliminating the lock.
1504
   */
1505
  public void run()
1506
  {
1507
    try
1508
    {
1509
      MetaCatUtil.debugMessage("thread started for docid: " +
1510
                               (String)fileLocks.elementAt(0), 45);
1511

    
1512
      Thread.sleep(30000); //the lock will expire in 30 seconds
1513
      MetaCatUtil.debugMessage("thread for docid: " +
1514
                             (String)fileLocks.elementAt(fileLocks.size() - 1) +
1515
                              " exiting.", 45);
1516

    
1517
      fileLocks.remove(fileLocks.size() - 1);
1518
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1519
      //in the vector, the first one inserted will be removed.
1520
    }
1521
    catch(Exception e)
1522
    {
1523
      MetaCatUtil.debugMessage("error in file lock thread from " +
1524
                                "MetacatReplication.run: " + e.getMessage(), 30);
1525
    }
1526
  }
1527

    
1528
  /**
1529
   * Returns the name of a server given a serverCode
1530
   * @param serverCode the serverid of the server
1531
   * @return the servername or null if the specified serverCode does not
1532
   *         exist.
1533
   */
1534
  public static String getServerNameForServerCode(int serverCode)
1535
  {
1536
    //System.out.println("serverid: " + serverCode);
1537
    DBConnection dbConn = null;
1538
    int serialNumber = -1;
1539
    PreparedStatement pstmt = null;
1540
    try
1541
    {
1542
      dbConn=DBConnectionPool.
1543
                  getDBConnection("MetacatReplication.getServer");
1544
      serialNumber=dbConn.getCheckOutSerialNumber();
1545
      String sql = new String("select server from " +
1546
                              "xml_replication where serverid = " +
1547
                              serverCode);
1548
      pstmt = dbConn.prepareStatement(sql);
1549
      //System.out.println("getserver sql: " + sql);
1550
      pstmt.execute();
1551
      ResultSet rs = pstmt.getResultSet();
1552
      boolean tablehasrows = rs.next();
1553
      if(tablehasrows)
1554
      {
1555
        //System.out.println("server: " + rs.getString(1));
1556
        return rs.getString(1);
1557
      }
1558

    
1559
      //conn.close();
1560
    }
1561
    catch(Exception e)
1562
    {
1563
      System.out.println("Error in MetacatReplication.getServer: " +
1564
                          e.getMessage());
1565
    }
1566
    finally
1567
    {
1568
      try
1569
      {
1570
        pstmt.close();
1571
      }//try
1572
      catch (SQLException ee)
1573
      {
1574
        MetaCatUtil.debugMessage("Error in MetacactReplication.getserver: "+
1575
                                    ee.getMessage(), 30);
1576
      }//catch
1577
      finally
1578
      {
1579
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1580
      }//fianlly
1581
    }//finally
1582

    
1583

    
1584

    
1585
    return null;
1586
      //return null if the server does not exist
1587
  }
1588

    
1589
  /**
1590
   * Returns a server code given a server name
1591
   * @param server the name of the server
1592
   * @return integer > 0 representing the code of the server, 0 if the server
1593
   *  does not exist.
1594
   */
1595
  public static int getServerCodeForServerName(String server) throws Exception
1596
  {
1597
    DBConnection dbConn = null;
1598
    int serialNumber = -1;
1599
    PreparedStatement pstmt = null;
1600
    int serverCode = 0;
1601

    
1602
    try {
1603

    
1604
      //conn = util.openDBConnection();
1605
      dbConn=DBConnectionPool.
1606
                  getDBConnection("MetacatReplication.getServerCode");
1607
      serialNumber=dbConn.getCheckOutSerialNumber();
1608
      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
1609
                                    "WHERE server LIKE '" + server + "'");
1610
      pstmt.execute();
1611
      ResultSet rs = pstmt.getResultSet();
1612
      boolean tablehasrows = rs.next();
1613
      if ( tablehasrows ) {
1614
        serverCode = rs.getInt(1);
1615
        pstmt.close();
1616
        //conn.close();
1617
        return serverCode;
1618
      }
1619

    
1620
    } catch(Exception e) {
1621
      throw e;
1622

    
1623
    } finally {
1624
      try
1625
      {
1626
        pstmt.close();
1627
        //conn.close();
1628
       }//try
1629
       catch(Exception ee)
1630
       {
1631
         MetaCatUtil.debugMessage("Error in MetacatReplicatio.getServerCode: "
1632
                                  +ee.getMessage(), 30);
1633

    
1634
       }//catch
1635
       finally
1636
       {
1637
         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1638
       }//finally
1639
    }//finally
1640

    
1641
    return serverCode;
1642
  }
1643

    
1644
  /**
1645
   * Method to get a host server information for given docid
1646
   * @param conn a connection to the database
1647
   */
1648
  public static Hashtable getHomeServerInfoForDocId(String docId)
1649
  {
1650
    Hashtable sl = new Hashtable();
1651
    DBConnection dbConn = null;
1652
    int serialNumber = -1;
1653
    //MetaCatUtil ut=new MetaCatUtil();
1654
    docId=MetaCatUtil.getDocIdFromString(docId);
1655
    PreparedStatement pstmt=null;
1656
    int serverLocation;
1657
    try
1658
    {
1659
      //get conection
1660
      dbConn=DBConnectionPool.
1661
                  getDBConnection("ReplicationHandler.getHomeServer");
1662
      serialNumber=dbConn.getCheckOutSerialNumber();
1663
      //get a server location from xml_document table
1664
      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
1665
                                            +"where docid = ?");
1666
      pstmt.setString(1, docId);
1667
      pstmt.execute();
1668
      ResultSet serverName = pstmt.getResultSet();
1669
      //get a server location
1670
      if(serverName.next())
1671
      {
1672
        serverLocation=serverName.getInt(1);
1673
        pstmt.close();
1674
      }
1675
      else
1676
      {
1677
        pstmt.close();
1678
        //ut.returnConnection(conn);
1679
        return null;
1680
      }
1681
      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
1682
                        "from xml_replication where serverid = ?");
1683
      //increase usage count
1684
      dbConn.increaseUsageCount(1);
1685
      pstmt.setInt(1, serverLocation);
1686
      pstmt.execute();
1687
      ResultSet rs = pstmt.getResultSet();
1688
      boolean tableHasRows = rs.next();
1689
      if (tableHasRows)
1690
      {
1691

    
1692
          String server = rs.getString(1);
1693
          String last_checked = rs.getString(2);
1694
          if(!server.equals("localhost"))
1695
          {
1696
            sl.put(server, last_checked);
1697
          }
1698

    
1699
      }
1700
      else
1701
      {
1702
        pstmt.close();
1703
        //ut.returnConnection(conn);
1704
        return null;
1705
      }
1706
      pstmt.close();
1707
    }
1708
    catch(Exception e)
1709
    {
1710
      System.out.println("error in replicationHandler.getHomeServer(): " +
1711
                         e.getMessage());
1712
    }
1713
    finally
1714
    {
1715
      try
1716
      {
1717
        pstmt.close();
1718
        //ut.returnConnection(conn);
1719
      }
1720
      catch (Exception ee)
1721
      {
1722
        MetaCatUtil.debugMessage("Eror irn rplicationHandler.getHomeServer() "+
1723
                          "to close pstmt: "+ee.getMessage(), 30);
1724
      }
1725
      finally
1726
      {
1727
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1728
      }
1729

    
1730
    }//finally
1731
    return sl;
1732
  }
1733

    
1734
  /**
1735
   * Returns a home server location  given a accnum
1736
   * @param accNum , given accNum for a document
1737
   *
1738
   */
1739
  public static int getHomeServerCodeForDocId(String accNum) throws Exception
1740
  {
1741
    DBConnection dbConn = null;
1742
    int serialNumber = -1;
1743
    PreparedStatement pstmt = null;
1744
    int serverCode = 1;
1745
    //MetaCatUtil ut = new MetaCatUtil();
1746
    String docId=MetaCatUtil.getDocIdFromString(accNum);
1747

    
1748
    try
1749
    {
1750

    
1751
      // Get DBConnection
1752
      dbConn=DBConnectionPool.
1753
                  getDBConnection("ReplicationHandler.getServerLocation");
1754
      serialNumber=dbConn.getCheckOutSerialNumber();
1755
      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1756
                              + "WHERE docid LIKE '" + docId + "'");
1757
      pstmt.execute();
1758
      ResultSet rs = pstmt.getResultSet();
1759
      boolean tablehasrows = rs.next();
1760
      //If a document is find, return the server location for it
1761
      if ( tablehasrows )
1762
      {
1763
        serverCode = rs.getInt(1);
1764
        pstmt.close();
1765
        //conn.close();
1766
        return serverCode;
1767
      }
1768
      //if couldn't find in xml_documents table, we think server code is 1
1769
      //(this is new document)
1770
      else
1771
      {
1772
        pstmt.close();
1773
        //conn.close();
1774
        return serverCode;
1775
      }
1776

    
1777
    }
1778
    catch(Exception e)
1779
    {
1780

    
1781
      throw e;
1782

    
1783
    }
1784
    finally
1785
    {
1786
      try
1787
      {
1788
        pstmt.close();
1789
        //conn.close();
1790

    
1791
      }
1792
      catch(Exception ee)
1793
      {
1794
        MetaCatUtil.debugMessage("Erorr in Replication.getServerLocation "+
1795
                     "to close pstmt"+ee.getMessage(), 30);
1796
      }
1797
      finally
1798
      {
1799
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1800
      }//finally
1801
    }//finally
1802
   //return serverCode;
1803
  }
1804

    
1805

    
1806

    
1807
  /**
1808
   * This method returns the content of a url
1809
   * @param u the url to return the content from
1810
   * @return a string representing the content of the url
1811
   * @throws java.io.IOException
1812
   */
1813
  public static String getURLContent(URL u) throws java.io.IOException
1814
  {
1815
    char istreamChar;
1816
    int istreamInt;
1817
    MetaCatUtil.debugMessage("Before open the stream"+u.toString(), 50);
1818
    InputStream input = u.openStream();
1819
    MetaCatUtil.debugMessage("Afetr open the stream"+u.toString(), 50);
1820
    InputStreamReader istream = new InputStreamReader(input);
1821
    StringBuffer serverResponse = new StringBuffer();
1822
    while((istreamInt = istream.read()) != -1)
1823
    {
1824
      istreamChar = (char)istreamInt;
1825
      serverResponse.append(istreamChar);
1826
    }
1827
    istream.close();
1828
    input.close();
1829

    
1830
    return serverResponse.toString();
1831
  }
1832

    
1833
  /**
1834
   * Method for writing replication messages to a log file specified in
1835
   * metacat.properties
1836
   */
1837
  public static void replLog(String message)
1838
  {
1839
    try
1840
    {
1841
      FileOutputStream fos = new FileOutputStream(
1842
                                 util.getOption("replicationlog"), true);
1843
      PrintWriter pw = new PrintWriter(fos);
1844
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1845
      java.util.Date localtime = new java.util.Date();
1846
      String dateString = formatter.format(localtime);
1847
      dateString += " :: " + message;
1848
      //time stamp each entry
1849
      pw.println(dateString);
1850
      pw.flush();
1851
    }
1852
    catch(Exception e)
1853
    {
1854
      System.out.println("error writing to replication log from " +
1855
                         "MetacatReplication.replLog: " + e.getMessage());
1856
      //e.printStackTrace(System.out);
1857
    }
1858
  }
1859

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

    
1887
  /**
1888
   * Returns true if the replicate field for server in xml_replication is 1.
1889
   * Returns false otherwise
1890
   */
1891
  public static boolean replToServer(String server)
1892
  {
1893
    DBConnection dbConn = null;
1894
    int serialNumber = -1;
1895
    PreparedStatement pstmt = null;
1896
    try
1897
    {
1898
      dbConn=DBConnectionPool.
1899
                  getDBConnection("MetacatReplication.repltoServer");
1900
      serialNumber=dbConn.getCheckOutSerialNumber();
1901
      pstmt = dbConn.prepareStatement("select replicate from " +
1902
                                    "xml_replication where server like '" +
1903
                                     server + "'");
1904
      pstmt.execute();
1905
      ResultSet rs = pstmt.getResultSet();
1906
      boolean tablehasrows = rs.next();
1907
      if(tablehasrows)
1908
      {
1909
        int i = rs.getInt(1);
1910
        if(i == 1)
1911
        {
1912
          pstmt.close();
1913
          //conn.close();
1914
          return true;
1915
        }
1916
        else
1917
        {
1918
          pstmt.close();
1919
          //conn.close();
1920
          return false;
1921
        }
1922
      }
1923
    }
1924
    catch(Exception e)
1925
    {
1926
      System.out.println("error in MetacatReplication.replToServer: " +
1927
                         e.getMessage());
1928
    }
1929
    finally
1930
    {
1931
      try
1932
      {
1933
        pstmt.close();
1934
        //conn.close();
1935
      }//try
1936
      catch(Exception ee)
1937
      {
1938
        MetaCatUtil.debugMessage("Error in MetacatReplication.replToServer: "
1939
                                  +ee.getMessage(), 30);
1940
      }//catch
1941
      finally
1942
      {
1943
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1944
      }//finally
1945
    }//finally
1946
    return false;
1947
    //the default if this server does not exist is to not replicate to it.
1948
  }
1949

    
1950

    
1951
}
(45-45/64)