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: leinfelder $'
9
 *     '$Date: 2008-10-08 11:28:13 -0700 (Wed, 08 Oct 2008) $'
10
 * '$Revision: 4420 $'
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 java.util.*;
30
import java.util.Date;
31
import java.io.*;
32
import java.sql.*;
33
import java.net.*;
34
import java.text.*;
35

    
36
import javax.servlet.*;
37
import javax.servlet.http.*;
38

    
39
import edu.ucsb.nceas.metacat.service.DatabaseService;
40
import edu.ucsb.nceas.metacat.service.PropertyService;
41
import edu.ucsb.nceas.metacat.service.SessionService;
42
import edu.ucsb.nceas.metacat.util.LDAPUtil;
43
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
44
import edu.ucsb.nceas.metacat.util.SessionData;
45
import edu.ucsb.nceas.metacat.util.SystemUtil;
46
import edu.ucsb.nceas.utilities.GeneralPropertyException;
47
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
48

    
49
import org.apache.log4j.Logger;
50
import org.xml.sax.*;
51

    
52
public class MetacatReplication extends HttpServlet implements Runnable
53
{
54

    
55
  private static final long serialVersionUID = -2898600143193513155L;
56
  private long timeInterval;
57
  private Date firstTime;
58
  private boolean timedReplicationIsOn = false;
59
  Timer replicationDaemon;
60
  private Vector fileLocks = new Vector();
61
  private Thread lockThread = null;
62
  public static final String FORCEREPLICATEDELETE = "forcereplicatedelete";
63
  private static final String TIMEREPLICATION = "replication.timedreplication";
64
  private static final String TIMEREPLICATIONINTERVAl = "replication.timedreplicationinterval";
65
  private static final String FIRSTTIME  = "replication.firsttimedreplication";
66
  private static final int    TIMEINTERVALLIMIT = 7200000;
67
  private static Logger logMetacat = Logger.getLogger(MetacatReplication.class);
68
  public static final String REPLICATIONUSER = "replication";
69

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

    
114
  public void destroy()
115
  {
116
    replicationDaemon.cancel();
117
   
118
  }
119

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

    
127
  public void doPost(HttpServletRequest request, HttpServletResponse response)
128
                     throws ServletException, IOException
129
  {
130
    // Process the data and send back the response
131
    handleGetOrPost(request, response);
132
  }
133

    
134
  private void handleGetOrPost(HttpServletRequest request,
135
                               HttpServletResponse response)
136
                               throws ServletException, IOException
137
  {
138
    //PrintWriter out = response.getWriter();
139
    //ServletOutputStream outPut = response.getOutputStream();
140
    Hashtable params = new Hashtable();
141
    Enumeration paramlist = request.getParameterNames();
142

    
143

    
144

    
145
// NOT NEEDED - doesn't provide enough security because of possible IP spoofing
146
// REPLACED with running replication comminications over HTTPS
147
//    String requestingServerIP = request.getRemoteAddr();
148
//    InetAddress iaddr = InetAddress.getByName(requestingServerIP);
149
//    String requestingServer = iaddr.getHostName();
150

    
151
    while (paramlist.hasMoreElements()) {
152
      String name = (String)paramlist.nextElement();
153
      String[] value = request.getParameterValues(name);
154
      params.put(name, value);
155
    }
156

    
157
    String action = ((String[])params.get("action"))[0];
158
    String server = null;
159

    
160
    try {
161
      // check if the server is included in the list of replicated servers
162
      if ( !action.equals("servercontrol") &&
163
           !action.equals("stop") &&
164
           !action.equals("start") &&
165
           !action.equals("getall") ) {
166

    
167
        server = ((String[])params.get("server"))[0];
168
        if ( getServerCodeForServerName(server) == 0 ) {
169
          System.out.println("Action \"" + action +
170
                             "\" rejected for server: " + server);
171
          return;
172
        } else {
173
          System.out.println("Action \"" + action +
174
                             "\" accepted for server: " + server);
175
        }
176
      }
177
      else
178
      {
179
          // start, stop, getall and servercontrol need to check
180
          // if user is administor
181
          HttpSession sess = request.getSession(true);
182
          SessionData sessionData = null;
183
          String sess_id = "";
184
          String username = "";
185
          String[] groupnames = {""};
186

    
187
          if (params.containsKey("sessionid")) 
188
          {
189
             sess_id = ((String[]) params.get("sessionid"))[0];
190
             logMetacat.info("in has sessionid "+ sess_id);
191
             if (SessionService.isSessionRegistered(sess_id)) 
192
             {
193
                  logMetacat.info("find the id " + sess_id + " in hash table");
194
                  sessionData = SessionService.getRegisteredSession(sess_id);
195
             }
196
           } 
197
          if (sessionData == null) {
198
        	  sessionData = new SessionData(sess.getId(), 
199
					(String) sess.getAttribute("username"), 
200
					(String[]) sess.getAttribute("groups"),
201
					(String) sess.getAttribute("password"));
202
          }
203
          
204
           username = sessionData.getUserName();
205
           logMetacat.warn("The user name from session is: "+ username);
206
           groupnames = sessionData.getGroupNames();
207
           if (!LDAPUtil.isAdministrator(username, groupnames)) 
208
           {
209
               PrintWriter out = response.getWriter();
210
               out.print("<error>");
211
               out.print("The user \"" + username +
212
                       "\" is not authorized for this action.");
213
               out.print("</error>");
214
               out.close();
215
               logMetacat.warn("The user \"" + username +
216
                       "\" is not authorized for this action: " +action);
217
               replErrorLog("The user \"" + username +
218
                       "\" is not authorized for this action: " +action);
219
               return;
220
           }
221
                        
222
      }// this is final else
223
    } catch (Exception e) {
224
      System.out.println("Error in MetacatReplication.handleGetOrPost: " +
225
                         e.getMessage() );
226
      return;
227
    }
228
    
229
    if ( action.equals("readdata") )
230
    {
231
      OutputStream outStream = response.getOutputStream();
232
      //to get the data file.
233
      handleGetDataFileRequest(outStream, params, response);
234
      outStream.close();
235
    }
236
    else if ( action.equals("forcereplicatedatafile") )
237
    {
238
      //read a specific docid from remote host, and store it into local host
239
      handleForceReplicateDataFileRequest(params, request);
240

    
241
    }
242
    else
243
    {
244
    PrintWriter out = response.getWriter();
245
    if ( action.equals("stop") ) {
246
      //stop the replication server
247
      replicationDaemon.cancel();
248
      replicationDaemon = new Timer(true);
249
      timedReplicationIsOn = false;
250
      try {
251
    	  PropertyService.setProperty(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
252
      } catch (GeneralPropertyException gpe) {
253
    	  logMetacat.warn("Could not set " + TIMEREPLICATION + " property: " + gpe.getMessage());
254
      }
255
      out.println("Replication Handler Stopped");
256
      MetacatReplication.replLog("deltaT handler stopped");
257

    
258

    
259
    } else if ( action.equals("start") ) {
260
       String firstTimeStr = "";
261
      //start the replication server
262
       if ( params.containsKey("rate") ) {
263
        timeInterval = new Long(
264
               new String(((String[])params.get("rate"))[0])).longValue();
265
        if(timeInterval < TIMEINTERVALLIMIT) {
266
            out.println("Replication deltaT rate cannot be less than "+
267
                    TIMEINTERVALLIMIT + " millisecs and system automatically setup the rate to "+TIMEINTERVALLIMIT);
268
            //deltaT<30 is a timing mess!
269
            timeInterval = TIMEINTERVALLIMIT;
270
        }
271
      } else {
272
        timeInterval = TIMEINTERVALLIMIT ;
273
      }
274
      logMetacat.info("New rate is: " + timeInterval + " mini seconds.");
275
      if ( params.containsKey("firsttime"))
276
      {
277
         firstTimeStr = ((String[])params.get("firsttime"))[0];
278
         try
279
         {
280
           firstTime = ReplicationHandler.combinateCurrentDateAndGivenTime(firstTimeStr);
281
           logMetacat.info("The first time setting is "+firstTime.toString());
282
         }
283
         catch (Exception e)
284
         {
285
            throw new ServletException(e.getMessage());
286
         }
287
         logMetacat.warn("After combine current time, the real first time is "
288
                                  +firstTime.toString()+" minisec");
289
      }
290
      else
291
      {
292
          MetacatReplication.replErrorLog("You should specify the first time " +
293
                                          "to start a time replication");
294
          logMetacat.warn("You should specify the first time " +
295
                                  "to start a time replication");
296
          return;
297
      }
298
      
299
      timedReplicationIsOn = true;
300
      try {
301
      // save settings to property file
302
      PropertyService.setProperty(TIMEREPLICATION, (new Boolean(timedReplicationIsOn)).toString());
303
      // note we couldn't use firstTime object because it has date info
304
      // we only need time info such as 10:00 PM
305
      PropertyService.setProperty(FIRSTTIME, firstTimeStr);
306
      PropertyService.setProperty(TIMEREPLICATIONINTERVAl, (new Long(timeInterval)).toString());
307
      } catch (GeneralPropertyException gpe) {
308
    	  logMetacat.warn("Could not set property: " + gpe.getMessage());
309
      }
310
      replicationDaemon.cancel();
311
      replicationDaemon = new Timer(true);
312
      replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(), firstTime,
313
                                            timeInterval);
314
      out.println("Replication Handler Started");
315
      MetacatReplication.replLog("deltaT handler started with rate=" +
316
                                    timeInterval + " milliseconds at " +firstTime.toString());
317

    
318

    
319
    } else if ( action.equals("getall") ) {
320
      //updates this server exactly once
321
      replicationDaemon.schedule(new ReplicationHandler(), 0);
322
      response.setContentType("text/html");
323
      out.println("<html><body>\"Get All\" Done</body></html>");
324

    
325
    } else if ( action.equals("forcereplicate") ) {
326
      //read a specific docid from remote host, and store it into local host
327
      handleForceReplicateRequest(out, params, response, request);
328

    
329
    } else if ( action.equals(FORCEREPLICATEDELETE) ) {
330
      //read a specific docid from remote host, and store it into local host
331
      handleForceReplicateDeleteRequest(out, params, response, request);
332

    
333
    } else if ( action.equals("update") ) {
334
      //request an update list from the server
335
      handleUpdateRequest(out, params, response);
336

    
337
    } else if ( action.equals("read") ) {
338
      //request a specific document from the server
339
      //note that this could be replaced by a call to metacatServlet
340
      //handleGetDocumentAction().
341
      handleGetDocumentRequest(out, params, response);
342
    } else if ( action.equals("getlock") ) {
343
      handleGetLockRequest(out, params, response);
344

    
345
    } else if ( action.equals("getdocumentinfo") ) {
346
      handleGetDocumentInfoRequest(out, params, response);
347

    
348
    } else if ( action.equals("gettime") ) {
349
      handleGetTimeRequest(out, params, response);
350

    
351
    } else if ( action.equals("getcatalog") ) {
352
      handleGetCatalogRequest(out, params, response, true);
353

    
354
    } else if ( action.equals("servercontrol") ) {
355
      handleServerControlRequest(out, params, response);
356
    } else if ( action.equals("test") ) {
357
      response.setContentType("text/html");
358
      out.println("<html><body>Test successfully</body></html>");
359
    }
360

    
361
    out.close();
362
    }//else
363
  }
364

    
365
  /**
366
   * This method can add, delete and list the servers currently included in
367
   * xml_replication.
368
   * action           subaction            other needed params
369
   * ---------------------------------------------------------
370
   * servercontrol    add                  server
371
   * servercontrol    delete               server
372
   * servercontrol    list
373
   */
374
  private void handleServerControlRequest(PrintWriter out, Hashtable params,
375
                                          HttpServletResponse response)
376
  {
377
    String subaction = ((String[])params.get("subaction"))[0];
378
    DBConnection dbConn = null;
379
    int serialNumber = -1;
380
    PreparedStatement pstmt = null;
381
    String replicate =null;
382
    String server = null;
383
    String dataReplicate = null;
384
    String hub = null;
385
    try {
386
      //conn = util.openDBConnection();
387
      dbConn=DBConnectionPool.
388
               getDBConnection("MetacatReplication.handleServerControlRequest");
389
      serialNumber=dbConn.getCheckOutSerialNumber();
390

    
391
      // add server to server list
392
      if ( subaction.equals("add") ) {
393
        replicate = ((String[])params.get("replicate"))[0];
394
        server = ((String[])params.get("server"))[0];
395

    
396
        //Get data replication value
397
        dataReplicate = ((String[])params.get("datareplicate"))[0];
398
        //Get hub value
399
        hub = ((String[])params.get("hub"))[0];
400

    
401
        /*pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
402
                  "(server, last_checked, replicate, datareplicate, hub) " +
403
                                      "VALUES ('" + server + "', to_date(" +
404
                                      "'01/01/00', 'MM/DD/YY'), '" +
405
                                      replicate +"', '" +dataReplicate+"', '"
406
                                      + hub +"')");*/
407
        pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
408
                  "(server, last_checked, replicate, datareplicate, hub) " +
409
                                      "VALUES ('" + server + "', "+
410
                                      DatabaseService.getDBAdapter().toDate("01/01/1980", "MM/DD/YYYY")
411
                                      + ", '" +
412
                                      replicate +"', '" +dataReplicate+"', '"
413
                                      + hub +"')");
414

    
415
        pstmt.execute();
416
        pstmt.close();
417
        dbConn.commit();
418
        out.println("Server " + server + " added");
419
        response.setContentType("text/html");
420
        out.println("<html><body><table border=\"1\">");
421
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
422
        out.println("<b>replicate</b></td>");
423
        out.println("<td><b>datareplicate</b></td>");
424
        out.println("<td><b>hub</b></td></tr>");
425
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
426
        //increase dbconnection usage
427
        dbConn.increaseUsageCount(1);
428

    
429
        pstmt.execute();
430
        ResultSet rs = pstmt.getResultSet();
431
        boolean tablehasrows = rs.next();
432
        while(tablehasrows) {
433
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
434
          out.println(rs.getString(3) + "</td><td>");
435
          out.println(rs.getString(4) + "</td><td>");
436
          out.println(rs.getString(5) + "</td><td>");
437
          out.println(rs.getString(6) + "</td></tr>");
438

    
439
          tablehasrows = rs.next();
440
        }
441
        out.println("</table></body></html>");
442

    
443
        // download certificate with the public key on this server
444
        // and import it as a trusted certificate
445
        String certURL = ((String[])params.get("certificate"))[0];
446
        downloadCertificate(certURL);
447

    
448
      // delete server from server list
449
      } else if ( subaction.equals("delete") ) {
450
        server = ((String[])params.get("server"))[0];
451
        pstmt = dbConn.prepareStatement("DELETE FROM xml_replication " +
452
                                      "WHERE server LIKE '" + server + "'");
453
        pstmt.execute();
454
        pstmt.close();
455
        dbConn.commit();
456
        out.println("Server " + server + " deleted");
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

    
464
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
465
        //increase dbconnection usage
466
        dbConn.increaseUsageCount(1);
467
        pstmt.execute();
468
        ResultSet rs = pstmt.getResultSet();
469
        boolean tablehasrows = rs.next();
470
        while(tablehasrows)
471
        {
472
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
473
          out.println(rs.getString(3) + "</td><td>");
474
          out.println(rs.getString(4) + "</td><td>");
475
          out.println(rs.getString(5) + "</td><td>");
476
          out.println(rs.getString(6) + "</td></tr>");
477
          tablehasrows = rs.next();
478
        }
479
        out.println("</table></body></html>");
480

    
481
      // list servers in server list
482
      } else if ( subaction.equals("list") ) {
483
        response.setContentType("text/html");
484
        out.println("<html><body><table border=\"1\">");
485
        out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
486
        out.println("<b>replicate</b></td>");
487
        out.println("<td><b>datareplicate</b></td>");
488
        out.println("<td><b>hub</b></td></tr>");
489
        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
490
        pstmt.execute();
491
        ResultSet rs = pstmt.getResultSet();
492
        boolean tablehasrows = rs.next();
493
        while(tablehasrows) {
494
          out.println("<tr><td>" + rs.getString(2) + "</td><td>");
495
          out.println(rs.getString(3) + "</td><td>");
496
          out.println(rs.getString(4) + "</td><td>");
497
          out.println(rs.getString(5) + "</td><td>");
498
          out.println(rs.getString(6) + "</td></tr>");
499
          tablehasrows = rs.next();
500
        }
501
        out.println("</table></body></html>");
502
      }
503
      else
504
      {
505

    
506
        out.println("<error>Unkonwn subaction</error>");
507

    
508
      }
509
      pstmt.close();
510
      //conn.close();
511

    
512
    } catch(Exception e) {
513
      System.out.println("Error in " +
514
                         "MetacatReplication.handleServerControlRequest " +
515
                         e.getMessage());
516
      e.printStackTrace(System.out);
517
    }
518
    finally
519
    {
520
      try
521
      {
522
        pstmt.close();
523
      }//try
524
      catch (SQLException ee)
525
      {
526
        logMetacat.error("Error in " +
527
                "MetacatReplication.handleServerControlRequest to close pstmt "
528
                 + ee.getMessage());
529
      }//catch
530
      finally
531
      {
532
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
533
      }//finally
534
    }//finally
535

    
536
  }
537

    
538
   	// download certificate with the public key from certURL and
539
	// upload it onto this server; it then must be imported as a
540
	// trusted certificate
541
	private void downloadCertificate(String certURL) throws FileNotFoundException,
542
			IOException, MalformedURLException, PropertyNotFoundException {
543
		
544
		// the path to be uploaded to
545
		String certPath = SystemUtil.getContextDir(); 
546

    
547
		// get filename from the URL of the certificate
548
		String filename = certURL;
549
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
550
		if (slash > -1) {
551
			filename = filename.substring(slash + 1);
552
		}
553

    
554
		// open file output strem to write the input into it
555
		File f = new File(certPath, filename);
556
		synchronized (f) {
557
			try {
558
				if (f.exists()) {
559
					throw new IOException("File already exist: " + f.getCanonicalFile());
560
					// if ( f.exists() && !f.canWrite() ) {
561
					// throw new IOException("Not writable: " +
562
					// f.getCanonicalFile());
563
				}
564
			} catch (SecurityException se) {
565
				// if a security manager exists,
566
				// its checkRead method is called for f.exist()
567
				// or checkWrite method is called for f.canWrite()
568
				throw se;
569
			}
570

    
571
			// create a buffered byte output stream
572
			// that uses a default-sized output buffer
573
			FileOutputStream fos = new FileOutputStream(f);
574
			BufferedOutputStream out = new BufferedOutputStream(fos);
575

    
576
			// this should be http url
577
			URL url = new URL(certURL);
578
			BufferedInputStream bis = null;
579
			try {
580
				bis = new BufferedInputStream(url.openStream());
581
				byte[] buf = new byte[4 * 1024]; // 4K buffer
582
				int b = bis.read(buf);
583
				while (b != -1) {
584
					out.write(buf, 0, b);
585
					b = bis.read(buf);
586
				}
587
			} finally {
588
				if (bis != null)
589
					bis.close();
590
			}
591
			// the input and the output streams must be closed
592
			bis.close();
593
			out.flush();
594
			out.close();
595
			fos.close();
596
		} // end of synchronized(f)
597
	}
598

    
599
  /**
600
	 * when a forcereplication request comes in, local host sends a read request
601
	 * to the requesting server (remote server) for the specified docid. Then
602
	 * store it in local database.
603
	 */
604
  private void handleForceReplicateRequest(PrintWriter out, Hashtable params,
605
                                           HttpServletResponse response, HttpServletRequest request)
606
  {
607
    String server = ((String[])params.get("server"))[0]; // the server that
608
    String docid = ((String[])params.get("docid"))[0]; // sent the document
609
    String dbaction = "UPDATE"; // the default action is UPDATE
610
    boolean override = false;
611
    int serverCode = 1;
612
    DBConnection dbConn = null;
613
    int serialNumber = -1;
614

    
615
    try {
616
      //if the url contains a dbaction then the default action is overridden
617
      if(params.containsKey("dbaction")) {
618
        dbaction = ((String[])params.get("dbaction"))[0];
619
        //serverCode = MetacatReplication.getServerCode(server);
620
        //override = true; //we are now overriding the default action
621
      }
622
      MetacatReplication.replLog("force replication request from " + server);
623
      logMetacat.info("Force replication request from: "+ server);
624
      logMetacat.info("Force replication docid: "+docid);
625
      logMetacat.info("Force replication action: "+dbaction);
626
      // sending back read request to remote server
627
      URL u = new URL("https://" + server + "?server="
628
                +MetaCatUtil.getLocalReplicationServerName()
629
                +"&action=read&docid=" + docid);
630
      String xmldoc = MetacatReplication.getURLContent(u);
631

    
632
      // get the document info from server
633
      URL docinfourl = new URL("https://" + server +
634
                               "?server="+MetaCatUtil.getLocalReplicationServerName()
635
                               +"&action=getdocumentinfo&docid=" + docid);
636

    
637
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
638

    
639
      //dih is the parser for the docinfo xml format
640
      DocInfoHandler dih = new DocInfoHandler();
641
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
642
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
643
      Hashtable docinfoHash = dih.getDocInfo();
644

    
645
      // Get user owner of this docid
646
      String user = (String)docinfoHash.get("user_owner");
647
      // Get home server of this docid
648
      String homeServer=(String)docinfoHash.get("home_server");
649
      String createdDate = (String)docinfoHash.get("date_created");
650
      String updatedDate = (String)docinfoHash.get("date_updated");
651
      logMetacat.info("homeServer: "+homeServer);
652
      // Get Document type
653
      String docType = (String)docinfoHash.get("doctype");
654
      logMetacat.info("docType: "+docType);
655
      String parserBase = null;
656
      // this for eml2 and we need user eml2 parser
657
      if (docType != null &&
658
          (docType.trim()).equals(DocumentImpl.EML2_0_0NAMESPACE))
659
      {
660
         logMetacat.warn("This is an eml200 document!");
661
         parserBase = DocumentImpl.EML200;
662
      }
663
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_0_1NAMESPACE))
664
      {
665
         logMetacat.warn("This is an eml2.0.1 document!");
666
         parserBase = DocumentImpl.EML200;
667
      }
668
      else if (docType != null && (docType.trim()).equals(DocumentImpl.EML2_1_0NAMESPACE))
669
      {
670
         logMetacat.warn("This is an eml2.1.0 document!");
671
         parserBase = DocumentImpl.EML210;
672
      }
673
      logMetacat.warn("The parserBase is: "+parserBase);
674

    
675
      // Get DBConnection from pool
676
      dbConn=DBConnectionPool.
677
              getDBConnection("MetacatReplication.handleForceReplicateRequest");
678
      serialNumber=dbConn.getCheckOutSerialNumber();
679
      // write the document to local database
680
      DocumentImplWrapper wrapper = new DocumentImplWrapper(parserBase, false);
681
      wrapper.writeReplication(dbConn, new StringReader(xmldoc), null, null,
682
                               dbaction, docid, user, null, homeServer, 
683
                               server, createdDate, updatedDate);
684

    
685
      //process extra access rules
686
      Vector accessControlList = (Vector) docinfoHash.get("accessControl");
687
      if (accessControlList != null) {
688
    	  for (int i = 0; i < accessControlList.size(); i++) {
689
        	  AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList.get(i);
690
        	  acfsf.insertPermissions();
691
          }
692
      }
693
      
694
      MetacatReplication.replLog("document " + docid + " added to DB with " +
695
                                 "action " + dbaction);
696
      EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, dbaction);
697
    }//try
698
    catch(Exception e)
699
    {
700
      MetacatReplication.replErrorLog("document " + docid +
701
                                      " failed to added to DB with " +
702
                                      "action " + dbaction + " because "+
703
                                       e.getMessage());
704
      logMetacat.error("ERROR in MetacatReplication.handleForceReplicate" +
705
                         "Request(): " + e.getMessage());
706

    
707
    }//catch
708
    finally
709
    {
710
      // Return the checked out DBConnection
711
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
712
    }//finally
713
  }
714

    
715
/*
716
 * when a forcereplication delete request comes in, local host will delete this
717
 * document
718
 */
719
private void handleForceReplicateDeleteRequest(PrintWriter out, Hashtable params,
720
                                         HttpServletResponse response, HttpServletRequest request)
721
{
722
  String server = ((String[])params.get("server"))[0]; // the server that
723
  String docid = ((String[])params.get("docid"))[0]; // sent the document
724
  try
725
  {
726
    MetacatReplication.replLog("force replication delete request from " + server);
727
    MetacatReplication.replLog("force replication delete docid " + docid);
728
    logMetacat.info("Force replication delete request from: "+ server);
729
    logMetacat.info("Force replication delete docid: "+docid);
730
    DocumentImpl.delete(docid, null, null, server);
731
    MetacatReplication.replLog("document " + docid + " was successfully deleted ");
732
    EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, "delete");
733
    logMetacat.info("document " + docid + " was successfully deleted ");
734
  }
735
  catch(Exception e)
736
  {
737
    MetacatReplication.replErrorLog("document " + docid +
738
                                    " failed to delete because "+
739
                                     e.getMessage());
740
    logMetacat.error("ERROR in MetacatReplication.handleForceDeleteReplicate" +
741
                       "Request(): " + e.getMessage());
742

    
743
  }//catch
744

    
745
}
746

    
747

    
748
  /**
749
   * when a forcereplication data file request comes in, local host sends a
750
   * readdata request to the requesting server (remote server) for the specified
751
   * docid. Then store it in local database and file system
752
   */
753
  private void handleForceReplicateDataFileRequest(Hashtable params, HttpServletRequest request)
754
  {
755

    
756
    //make sure there is some parameters
757
    if(params.isEmpty())
758
    {
759
      return;
760
    }
761
    // Get remote server
762
    String server = ((String[])params.get("server"))[0];
763
    // the docid should include rev number
764
    String docid = ((String[])params.get("docid"))[0];
765
    // Make sure there is a docid and server
766
    if (docid==null || server==null || server.equals(""))
767
    {
768
      logMetacat.error("Didn't specify docid or server for replication");
769
      return;
770
    }
771

    
772
    // Overide or not
773
    boolean override = false;
774
    // dbaction - update or insert
775
    String dbaction=null;
776

    
777
    try
778
    {
779
      //docid was switch to two parts uinque code and rev
780
      //String uniqueCode=MetaCatUtil.getDocIdFromString(docid);
781
      //int rev=MetaCatUtil.getVersionFromString(docid);
782
      if(params.containsKey("dbaction"))
783
      {
784
        dbaction = ((String[])params.get("dbaction"))[0];
785
      }
786
      else//default value is update
787
      {
788
        dbaction = "update";
789
      }
790

    
791
      MetacatReplication.replLog("force replication request from " + server);
792
      logMetacat.info("Force replication request from: "+ server);
793
      logMetacat.info("Force replication docid: "+docid);
794
      logMetacat.info("Force replication action: "+dbaction);
795
      // get the document info from server
796
      URL docinfourl = new URL("https://" + server +
797
                               "?server="+MetaCatUtil.getLocalReplicationServerName()
798
                               +"&action=getdocumentinfo&docid=" + docid);
799

    
800
      String docInfoStr = MetacatReplication.getURLContent(docinfourl);
801

    
802
      //dih is the parser for the docinfo xml format
803
      DocInfoHandler dih = new DocInfoHandler();
804
      XMLReader docinfoParser = ReplicationHandler.initParser(dih);
805
      docinfoParser.parse(new InputSource(new StringReader(docInfoStr)));
806
      Hashtable docinfoHash = dih.getDocInfo();
807
      String user = (String)docinfoHash.get("user_owner");
808

    
809
      String docName = (String)docinfoHash.get("docname");
810

    
811
      String docType = (String)docinfoHash.get("doctype");
812

    
813
      String docHomeServer= (String)docinfoHash.get("home_server");
814
      
815
      String createdDate = (String)docinfoHash.get("date_created");
816
      
817
      String updatedDate = (String)docinfoHash.get("date_updated");
818
      logMetacat.info("docHomeServer of datafile: "+docHomeServer);
819

    
820

    
821

    
822
      //if action is delete, we don't delete the data file. Just archieve
823
      //the xml_documents
824
      /*if (dbaction.equals("delete"))
825
      {
826
        //conn = util.getConnection();
827
        DocumentImpl.delete(docid,user,null);
828
        //util.returnConnection(conn);
829
      }*/
830
      //To data file insert or update is same
831
      if (dbaction.equals("insert")||dbaction.equals("update"))
832
      {
833
        //Get data file and store it into local file system.
834
        // sending back readdata request to server
835
        URL url = new URL("https://" + server + "?server="
836
                +MetaCatUtil.getLocalReplicationServerName()
837
                +"&action=readdata&docid=" + docid);
838
        String datafilePath = PropertyService.getProperty("application.datafilepath");
839
        //register data file into xml_documents table and wite data file
840
        //into file system
841
        DocumentImpl.writeDataFileInReplication(url.openStream(), datafilePath,
842
                            docName, docType, docid, user,docHomeServer,server, 
843
                            DocumentImpl.DOCUMENTTABLE, false, createdDate, updatedDate);
844
        //process extra access rules
845
        Vector accessControlList = (Vector) docinfoHash.get("accessControl");
846
        if (accessControlList != null) {
847
      	  for (int i = 0; i < accessControlList.size(); i++) {
848
          	  AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList.get(i);
849
          	  acfsf.insertPermissions();
850
            }
851
        }
852
        
853
                            //false means non-timed replication
854
        MetacatReplication.replLog("datafile " + docid + " added to DB with " +
855
                "action " + dbaction);
856
        EventLog.getInstance().log(request.getRemoteAddr(), REPLICATIONUSER, docid, dbaction);
857
     }
858

    
859

    
860

    
861
    
862
    }
863
    catch(Exception e)
864
    {
865

    
866
      MetacatReplication.replErrorLog("Datafile " + docid +
867
                                      " failed to added to DB with " +
868
                                      "action " + dbaction + " because "+
869
                                       e.getMessage());
870
      logMetacat.error
871
              ("ERROR in MetacatReplication.handleForceDataFileReplicate" +
872
                         "Request(): " + e.getMessage());
873
    }
874
  }
875
  /**
876
   * Grants or denies a lock to a requesting host.
877
   * The servlet parameters of interrest are:
878
   * docid: the docid of the file the lock is being requested for
879
   * currentdate: the timestamp of the document on the remote server
880
   *
881
   */
882
  private void handleGetLockRequest(PrintWriter out, Hashtable params,
883
                                    HttpServletResponse response)
884
  {
885

    
886
    try
887
    {
888

    
889
      String docid = ((String[])params.get("docid"))[0];
890
      String remoteRev = ((String[])params.get("updaterev"))[0];
891
      DocumentImpl requestDoc = new DocumentImpl(docid);
892
      MetacatReplication.replLog("lock request for " + docid);
893
      int localRevInt = requestDoc.getRev();
894
      int remoteRevInt = Integer.parseInt(remoteRev);
895

    
896
      if(remoteRevInt >= localRevInt)
897
      {
898
        if(!fileLocks.contains(docid))
899
        { //grant the lock if it is not already locked
900
          fileLocks.add(0, docid); //insert at the beginning of the queue Vector
901
          //send a message back to the the remote host authorizing the insert
902
          out.println("<lockgranted><docid>" +docid+ "</docid></lockgranted>");
903
          lockThread = new Thread(this);
904
          lockThread.setPriority(Thread.MIN_PRIORITY);
905
          lockThread.start();
906
          MetacatReplication.replLog("lock granted for " + docid);
907
        }
908
        else
909
        { //deny the lock
910
          out.println("<filelocked><docid>" + docid + "</docid></filelocked>");
911
          MetacatReplication.replLog("lock denied for " + docid +
912
                                     "reason: file already locked");
913
        }
914
      }
915
      else
916
      {//deny the lock.
917
        out.println("<outdatedfile><docid>" + docid + "</docid></filelocked>");
918
        MetacatReplication.replLog("lock denied for " + docid +
919
                                   "reason: client has outdated file");
920
      }
921
      //conn.close();
922
    }
923
    catch(Exception e)
924
    {
925
      System.out.println("error requesting file lock from MetacatReplication." +
926
                         "handleGetLockRequest: " + e.getMessage());
927
      e.printStackTrace(System.out);
928
    }
929
  }
930

    
931
  /**
932
   * Sends all of the xml_documents information encoded in xml to a requestor
933
   * the format is:
934
   * <!ELEMENT documentinfo (docid, docname, doctype, doctitle, user_owner,
935
   *                  user_updated, home_server, public_access, rev)/>
936
   * all of the subelements of document info are #PCDATA
937
   */
938
  private void handleGetDocumentInfoRequest(PrintWriter out, Hashtable params,
939
                                        HttpServletResponse response)
940
  {
941
    String docid = ((String[])(params.get("docid")))[0];
942
    StringBuffer sb = new StringBuffer();
943

    
944
    try
945
    {
946

    
947
      DocumentImpl doc = new DocumentImpl(docid);
948
      sb.append("<documentinfo><docid>").append(docid);
949
      sb.append("</docid><docname>").append(doc.getDocname());
950
      sb.append("</docname><doctype>").append(doc.getDoctype());
951
      sb.append("</doctype>");
952
      sb.append("<user_owner>").append(doc.getUserowner());
953
      sb.append("</user_owner><user_updated>").append(doc.getUserupdated());
954
      sb.append("</user_updated>");
955
      sb.append("<date_created>");
956
      sb.append(doc.getCreateDate());
957
      sb.append("</date_created>");
958
      sb.append("<date_updated>");
959
      sb.append(doc.getUpdateDate());
960
      sb.append("</date_updated>");
961
      sb.append("<home_server>");
962
      sb.append(doc.getDocHomeServer());
963
      sb.append("</home_server>");
964
      sb.append("<public_access>").append(doc.getPublicaccess());
965
      sb.append("</public_access><rev>").append(doc.getRev());
966
      sb.append("</rev>");
967
      
968
      //permissions on the document
969
      PermissionController permController = new PermissionController(docid);
970
      Vector accessControlList = permController.getAccessControl();
971
      sb.append("<accessControl>");
972
      for (int i = 0; i < accessControlList.size(); i++) {
973
    	  AccessControlForSingleFile acfsf = (AccessControlForSingleFile) accessControlList.get(i);
974
    	  sb.append(acfsf.getAccessString());
975
      }
976
      sb.append("</accessControl>");
977
      
978
      sb.append("</documentinfo>");
979
      response.setContentType("text/xml");
980
      out.println(sb.toString());
981

    
982
    }
983
    catch (Exception e)
984
    {
985
      System.out.println("error in " +
986
                         "metacatReplication.handlegetdocumentinforequest: " +
987
                          e.getMessage());
988
    }
989

    
990
  }
991

    
992
  /**
993
   * Sends a datafile to a remote host
994
   */
995
  private void handleGetDataFileRequest(OutputStream outPut,
996
                            Hashtable params, HttpServletResponse response)
997

    
998
  {
999
    // File path for data file
1000
    String filepath;
1001
    // Request docid
1002
    String docId = ((String[])(params.get("docid")))[0];
1003
    //check if the doicd is null
1004
    if (docId==null)
1005
    {
1006
      logMetacat.error("Didn't specify docid for replication");
1007
      return;
1008
    }
1009

    
1010
    //try to open a https stream to test if the request server's public key
1011
    //in the key store, this is security issue
1012
    try
1013
    {
1014
      filepath = PropertyService.getProperty("application.datafilepath");
1015
      String server = ((String[])params.get("server"))[0];
1016
      URL u = new URL("https://" + server + "?server="
1017
                +MetaCatUtil.getLocalReplicationServerName()
1018
                +"&action=test");
1019
      String test = MetacatReplication.getURLContent(u);
1020
      //couldn't pass the test
1021
      if (test.indexOf("successfully")==-1)
1022
      {
1023
        //response.setContentType("text/xml");
1024
        //outPut.println("<error>Couldn't pass the trust test</error>");
1025
        logMetacat.error("Couldn't pass the trust test");
1026
        return;
1027
      }
1028
    }//try
1029
    catch (Exception ee)
1030
    {
1031
      return;
1032
    }//catch
1033

    
1034
    if(!filepath.endsWith("/"))
1035
    {
1036
          filepath += "/";
1037
    }
1038
    // Get file aboslute file name
1039
    String filename = filepath + docId;
1040

    
1041
    //MIME type
1042
    String contentType = null;
1043
    if (filename.endsWith(".xml"))
1044
    {
1045
        contentType="text/xml";
1046
    }
1047
    else if (filename.endsWith(".css"))
1048
    {
1049
        contentType="text/css";
1050
    }
1051
    else if (filename.endsWith(".dtd"))
1052
    {
1053
        contentType="text/plain";
1054
    }
1055
    else if (filename.endsWith(".xsd"))
1056
    {
1057
        contentType="text/xml";
1058
    }
1059
    else if (filename.endsWith("/"))
1060
    {
1061
        contentType="text/html";
1062
    }
1063
    else
1064
    {
1065
        File f = new File(filename);
1066
        if ( f.isDirectory() )
1067
        {
1068
           contentType="text/html";
1069
        }
1070
        else
1071
        {
1072
           contentType="application/octet-stream";
1073
        }
1074
     }
1075

    
1076
   // Set the mime type
1077
   response.setContentType(contentType);
1078

    
1079
   // Get the content of the file
1080
   FileInputStream fin = null;
1081
   try
1082
   {
1083
      // FileInputStream to metacat
1084
      fin = new FileInputStream(filename);
1085
      // 4K buffer
1086
      byte[] buf = new byte[4 * 1024];
1087
      // Read data from file input stream to byte array
1088
      int b = fin.read(buf);
1089
      // Write to outStream from byte array
1090
      while (b != -1)
1091
      {
1092
        outPut.write(buf, 0, b);
1093
        b = fin.read(buf);
1094
      }
1095
      // close file input stream
1096
      fin.close();
1097

    
1098
   }//try
1099
   catch(Exception e)
1100
   {
1101
      System.out.println("error getting data file from MetacatReplication." +
1102
                         "handlGetDataFileRequest " + e.getMessage());
1103
      e.printStackTrace(System.out);
1104
   }//catch
1105

    
1106
}
1107

    
1108

    
1109
  /**
1110
   * Sends a document to a remote host
1111
   */
1112
  private void handleGetDocumentRequest(PrintWriter out, Hashtable params,
1113
                                        HttpServletResponse response)
1114
  {
1115

    
1116
    try
1117
    {
1118
      //try to open a https stream to test if the request server's public key
1119
      //in the key store, this is security issue
1120
      String server = ((String[])params.get("server"))[0];
1121
      URL u = new URL("https://" + server + "?server="
1122
                +MetaCatUtil.getLocalReplicationServerName()
1123
                +"&action=test");
1124
      String test = MetacatReplication.getURLContent(u);
1125
      //couldn't pass the test
1126
      if (test.indexOf("successfully")==-1)
1127
      {
1128
        response.setContentType("text/xml");
1129
        out.println("<error>Couldn't pass the trust test "+test+" </error>");
1130
        out.close();
1131
        return;
1132
      }
1133

    
1134
      String docid = ((String[])(params.get("docid")))[0];
1135

    
1136
      DocumentImpl di = new DocumentImpl(docid);
1137
      response.setContentType("text/xml");
1138
      out.print(di.toString(null, null, true));
1139

    
1140
      MetacatReplication.replLog("document " + docid + " sent");
1141

    
1142
    }
1143
    catch(Exception e)
1144
    {
1145
      logMetacat.error("error getting document from MetacatReplication."
1146
                          +"handlGetDocumentRequest " + e.getMessage());
1147
      //e.printStackTrace(System.out);
1148
      response.setContentType("text/xml");
1149
      out.println("<error>"+e.getMessage()+"</error>");
1150
    }
1151

    
1152
  }
1153

    
1154
  /**
1155
   * Sends a list of all of the documents on this sever along with their
1156
   * revision numbers.
1157
   * The format is:
1158
   * <!ELEMENT replication (server, updates)>
1159
   * <!ELEMENT server (#PCDATA)>
1160
   * <!ELEMENT updates ((updatedDocument | deleteDocument | revisionDocument)*)>
1161
   * <!ELEMENT updatedDocument (docid, rev, datafile*)>
1162
   * <!ELEMENT deletedDocument (docid, rev)>
1163
   * <!ELEMENT revisionDocument (docid, rev, datafile*)>
1164
   * <!ELEMENT docid (#PCDATA)>
1165
   * <!ELEMENT rev (#PCDATA)>
1166
   * <!ELEMENT datafile (#PCDATA)>
1167
   * note that the rev in deletedDocument is always empty.  I just left
1168
   * it in there to make the parser implementation easier.
1169
   */
1170
  private void handleUpdateRequest(PrintWriter out, Hashtable params,
1171
                                    HttpServletResponse response)
1172
  {
1173
    // Checked out DBConnection
1174
    DBConnection dbConn = null;
1175
    // DBConenction serial number when checked it out
1176
    int serialNumber = -1;
1177
    PreparedStatement pstmt = null;
1178
    // Server list to store server info of xml_replication table
1179
    ReplicationServerList serverList = null;
1180

    
1181
    try
1182
    {
1183
      // Check out a DBConnection from pool
1184
      dbConn=DBConnectionPool.
1185
                  getDBConnection("MetacatReplication.handleUpdateRequest");
1186
      serialNumber=dbConn.getCheckOutSerialNumber();
1187
      // Create a server list from xml_replication table
1188
      serverList = new ReplicationServerList();
1189

    
1190
      // Get remote server name from param
1191
      String server = ((String[])params.get("server"))[0];
1192
      // If no servr name in param, return a error
1193
      if ( server == null || server.equals(""))
1194
      {
1195
        response.setContentType("text/xml");
1196
        out.println("<error>Request didn't specify server name</error>");
1197
        out.close();
1198
        return;
1199
      }//if
1200

    
1201
      //try to open a https stream to test if the request server's public key
1202
      //in the key store, this is security issue
1203
      URL u = new URL("https://" + server + "?server="
1204
                +MetaCatUtil.getLocalReplicationServerName()
1205
                +"&action=test");
1206
      String test = MetacatReplication.getURLContent(u);
1207
      //couldn't pass the test
1208
      if (test.indexOf("successfully")==-1)
1209
      {
1210
        response.setContentType("text/xml");
1211
        out.println("<error>Couldn't pass the trust test</error>");
1212
        out.close();
1213
        return;
1214
      }
1215

    
1216

    
1217
      // Check if local host configure to replicate xml documents to remote
1218
      // server. If not send back a error message
1219
      if (!serverList.getReplicationValue(server))
1220
      {
1221
        response.setContentType("text/xml");
1222
        out.println
1223
        ("<error>Configuration not allow to replicate document to you</error>");
1224
        out.close();
1225
        return;
1226
      }//if
1227

    
1228
      // Store the sql command
1229
      StringBuffer docsql = new StringBuffer();
1230
      StringBuffer revisionSql = new StringBuffer();
1231
      // Stroe the docid list
1232
      StringBuffer doclist = new StringBuffer();
1233
      // Store the deleted docid list
1234
      StringBuffer delsql = new StringBuffer();
1235
      // Store the data set file
1236
      Vector packageFiles = new Vector();
1237

    
1238
      // Append local server's name and replication servlet to doclist
1239
      doclist.append("<?xml version=\"1.0\"?><replication>");
1240
      doclist.append("<server>").append(MetaCatUtil.getLocalReplicationServerName());
1241
      //doclist.append(util.getProperty("replicationpath"));
1242
      doclist.append("</server><updates>");
1243

    
1244
      // Get correct docid that reside on this server according the requesting
1245
      // server's replicate and data replicate value in xml_replication table
1246
      docsql.append(DatabaseService.getDBAdapter().getReplicationDocumentListSQL());
1247
      //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)) ");
1248
      revisionSql.append("select docid, rev, doctype from xml_revisions ");
1249
      // If the localhost is not a hub to the remote server, only replicate
1250
      // the docid' which home server is local host (server_location =1)
1251
      if (!serverList.getHubValue(server))
1252
      {
1253
    	String serverLocationDoc = " and a.server_location = 1";
1254
        String serverLocationRev = "where server_location = 1";
1255
        docsql.append(serverLocationDoc);
1256
        revisionSql.append(serverLocationRev);
1257
      }
1258
      logMetacat.info("Doc sql: "+docsql.toString());
1259

    
1260
      // Get any deleted documents
1261
      delsql.append("select distinct docid from ");
1262
      delsql.append("xml_revisions where docid not in (select docid from ");
1263
      delsql.append("xml_documents) ");
1264
      // If the localhost is not a hub to the remote server, only replicate
1265
      // the docid' which home server is local host (server_location =1)
1266
      if (!serverList.getHubValue(server))
1267
      {
1268
        delsql.append("and server_location = 1");
1269
      }
1270
      logMetacat.info("Deleted sql: "+delsql.toString());
1271

    
1272

    
1273

    
1274
      // Get docid list of local host
1275
      pstmt = dbConn.prepareStatement(docsql.toString());
1276
      pstmt.execute();
1277
      ResultSet rs = pstmt.getResultSet();
1278
      boolean tablehasrows = rs.next();
1279
      //If metacat configed to replicate data file
1280
      //if ((util.getProperty("replicationsenddata")).equals("on"))
1281
      boolean replicateData = serverList.getDataReplicationValue(server);
1282
      if (replicateData)
1283
      {
1284
        while(tablehasrows)
1285
        {
1286
          String recordDoctype = rs.getString(3);
1287
          Vector packagedoctypes = MetaCatUtil.getOptionList(
1288
                                     PropertyService.getProperty("xml.packagedoctype"));
1289
          //if this is a package file, put it at the end
1290
          //because if a package file is read before all of the files it
1291
          //refers to are loaded then there is an error
1292
          if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1293
          {
1294
              //If this is not data file
1295
              if (!recordDoctype.equals("BIN"))
1296
              {
1297
                //for non-data file document
1298
                doclist.append("<updatedDocument>");
1299
                doclist.append("<docid>").append(rs.getString(1));
1300
                doclist.append("</docid><rev>").append(rs.getInt(2));
1301
                doclist.append("</rev>");
1302
                doclist.append("</updatedDocument>");
1303
              }//if
1304
              else
1305
              {
1306
                //for data file document, in datafile attributes
1307
                //we put "datafile" value there
1308
                doclist.append("<updatedDocument>");
1309
                doclist.append("<docid>").append(rs.getString(1));
1310
                doclist.append("</docid><rev>").append(rs.getInt(2));
1311
                doclist.append("</rev>");
1312
                doclist.append("<datafile>");
1313
                doclist.append(PropertyService.getProperty("replication.datafileflag"));
1314
                doclist.append("</datafile>");
1315
                doclist.append("</updatedDocument>");
1316
              }//else
1317
          }//if packagedoctpes
1318
          else
1319
          { //the package files are saved to be put into the xml later.
1320
              Vector v = new Vector();
1321
              v.add(new String(rs.getString(1)));
1322
              v.add(new Integer(rs.getInt(2)));
1323
              packageFiles.add(new Vector(v));
1324
          }//esle
1325
          tablehasrows = rs.next();
1326
        }//while
1327
      }//if
1328
      else //metacat was configured not to send data file
1329
      {
1330
        while(tablehasrows)
1331
        {
1332
          String recordDoctype = rs.getString(3);
1333
          if(!recordDoctype.equals("BIN"))
1334
          { //don't replicate data files
1335
            Vector packagedoctypes = MetaCatUtil.getOptionList(
1336
                                     PropertyService.getProperty("xml.packagedoctype"));
1337
            if(recordDoctype != null && !packagedoctypes.contains(recordDoctype))
1338
            {   //if this is a package file, put it at the end
1339
              //because if a package file is read before all of the files it
1340
              //refers to are loaded then there is an error
1341
              doclist.append("<updatedDocument>");
1342
              doclist.append("<docid>").append(rs.getString(1));
1343
              doclist.append("</docid><rev>").append(rs.getInt(2));
1344
              doclist.append("</rev>");
1345
              doclist.append("</updatedDocument>");
1346
            }
1347
            else
1348
            { //the package files are saved to be put into the xml later.
1349
              Vector v = new Vector();
1350
              v.add(new String(rs.getString(1)));
1351
              v.add(new Integer(rs.getInt(2)));
1352
              packageFiles.add(new Vector(v));
1353
            }
1354
         }//if
1355
         tablehasrows = rs.next();
1356
        }//while
1357
      }//else
1358

    
1359
      pstmt = dbConn.prepareStatement(delsql.toString());
1360
      //usage count should increas 1
1361
      dbConn.increaseUsageCount(1);
1362

    
1363
      pstmt.execute();
1364
      rs = pstmt.getResultSet();
1365
      tablehasrows = rs.next();
1366
      while(tablehasrows)
1367
      { //handle the deleted documents
1368
        doclist.append("<deletedDocument><docid>").append(rs.getString(1));
1369
        doclist.append("</docid><rev></rev></deletedDocument>");
1370
        //note that rev is always empty for deleted docs
1371
        tablehasrows = rs.next();
1372
      }
1373

    
1374
      //now we can put the package files into the xml results
1375
      for(int i=0; i<packageFiles.size(); i++)
1376
      {
1377
        Vector v = (Vector)packageFiles.elementAt(i);
1378
        doclist.append("<updatedDocument>");
1379
        doclist.append("<docid>").append((String)v.elementAt(0));
1380
        doclist.append("</docid><rev>");
1381
        doclist.append(((Integer)v.elementAt(1)).intValue());
1382
        doclist.append("</rev>");
1383
        doclist.append("</updatedDocument>");
1384
      }
1385
      // add revision doc list  
1386
      doclist.append(prepareRevisionDoc(dbConn,revisionSql.toString(),replicateData));
1387
        
1388
      doclist.append("</updates></replication>");
1389
      logMetacat.info("doclist: " + doclist.toString());
1390
      pstmt.close();
1391
      //conn.close();
1392
      response.setContentType("text/xml");
1393
      out.println(doclist.toString());
1394

    
1395
    }
1396
    catch(Exception e)
1397
    {
1398
      logMetacat.error("error in MetacatReplication." +
1399
                         "handleupdaterequest: " + e.getMessage());
1400
      //e.printStackTrace(System.out);
1401
      response.setContentType("text/xml");
1402
      out.println("<error>"+e.getMessage()+"</error>");
1403
    }
1404
    finally
1405
    {
1406
      try
1407
      {
1408
        pstmt.close();
1409
      }//try
1410
      catch (SQLException ee)
1411
      {
1412
        logMetacat.error("Error in MetacatReplication." +
1413
                "handleUpdaterequest to close pstmt: "+ee.getMessage());
1414
      }//catch
1415
      finally
1416
      {
1417
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1418
      }//finally
1419
    }//finally
1420

    
1421
  }//handlUpdateRequest
1422
  
1423
  /*
1424
   * This method will get the xml string for document in xml_revision
1425
   * The schema look like <!ELEMENT revisionDocument (docid, rev, datafile*)>
1426
   */
1427
  private String prepareRevisionDoc(DBConnection dbConn, String revSql, 
1428
                            boolean replicateData) throws Exception
1429
  {
1430
      logMetacat.warn("The revision document sql is "+ revSql);
1431
      StringBuffer revDocList = new StringBuffer();
1432
      PreparedStatement pstmt = dbConn.prepareStatement(revSql);
1433
      //usage count should increas 1
1434
      dbConn.increaseUsageCount(1);
1435

    
1436
      pstmt.execute();
1437
      ResultSet rs = pstmt.getResultSet();
1438
      boolean tablehasrows = rs.next();
1439
      while(tablehasrows)
1440
      {
1441
        String recordDoctype = rs.getString(3);
1442
        
1443
        //If this is data file and it isn't configured to replicate data
1444
        if (recordDoctype.equals("BIN") && !replicateData)
1445
        {  
1446
            // do nothing
1447
            continue;
1448
        }
1449
        else
1450
        {  
1451
            
1452
            revDocList.append("<revisionDocument>");
1453
            revDocList.append("<docid>").append(rs.getString(1));
1454
            revDocList.append("</docid><rev>").append(rs.getInt(2));
1455
            revDocList.append("</rev>");
1456
            // data file
1457
            if (recordDoctype.equals("BIN"))
1458
            {
1459
                revDocList.append("<datafile>");
1460
                revDocList.append(PropertyService.getProperty("replication.datafileflag"));
1461
                revDocList.append("</datafile>");
1462
            }
1463
            revDocList.append("</revisionDocument>");
1464
        
1465
         }//else
1466
         tablehasrows = rs.next();
1467
      }
1468
      //System.out.println("The revision list is"+ revDocList.toString());
1469
      return revDocList.toString();
1470
  }
1471

    
1472
  /**
1473
   * Returns the xml_catalog table encoded in xml
1474
   */
1475
  public static String getCatalogXML()
1476
  {
1477
    return handleGetCatalogRequest(null, null, null, false);
1478
  }
1479

    
1480
  /**
1481
   * Sends the contents of the xml_catalog table encoded in xml
1482
   * The xml format is:
1483
   * <!ELEMENT xml_catalog (row*)>
1484
   * <!ELEMENT row (entry_type, source_doctype, target_doctype, public_id,
1485
   *                system_id)>
1486
   * All of the sub elements of row are #PCDATA
1487

    
1488
   * If printFlag == false then do not print to out.
1489
   */
1490
  private static String handleGetCatalogRequest(PrintWriter out,
1491
                                                Hashtable params,
1492
                                                HttpServletResponse response,
1493
                                                boolean printFlag)
1494
  {
1495
    DBConnection dbConn = null;
1496
    int serialNumber = -1;
1497
    PreparedStatement pstmt = null;
1498
    try
1499
    {
1500
      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
1501
                                                "handleGetCatalogRequest");*/
1502
      dbConn=DBConnectionPool.
1503
                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
1504
      serialNumber=dbConn.getCheckOutSerialNumber();
1505
      pstmt = dbConn.prepareStatement("select entry_type, " +
1506
                              "source_doctype, target_doctype, public_id, " +
1507
                              "system_id from xml_catalog");
1508
      pstmt.execute();
1509
      ResultSet rs = pstmt.getResultSet();
1510
      boolean tablehasrows = rs.next();
1511
      StringBuffer sb = new StringBuffer();
1512
      sb.append("<?xml version=\"1.0\"?><xml_catalog>");
1513
      while(tablehasrows)
1514
      {
1515
        sb.append("<row><entry_type>").append(rs.getString(1));
1516
        sb.append("</entry_type><source_doctype>").append(rs.getString(2));
1517
        sb.append("</source_doctype><target_doctype>").append(rs.getString(3));
1518
        sb.append("</target_doctype><public_id>").append(rs.getString(4));
1519
        // system id may not have server url on front.  Add it if not.
1520
        String systemID = rs.getString(5);
1521
        if (!systemID.startsWith("http://")) {
1522
        	systemID = SystemUtil.getContextURL() + systemID;
1523
        }
1524
        sb.append("</public_id><system_id>").append(systemID);
1525
        sb.append("</system_id></row>");
1526

    
1527
        tablehasrows = rs.next();
1528
      }
1529
      sb.append("</xml_catalog>");
1530
      //conn.close();
1531
      if(printFlag)
1532
      {
1533
        response.setContentType("text/xml");
1534
        out.println(sb.toString());
1535
      }
1536
      pstmt.close();
1537
      return sb.toString();
1538
    }
1539
    catch(Exception e)
1540
    {
1541

    
1542
      logMetacat.error("error in MetacatReplication.handleGetCatalogRequest:"+
1543
                          e.getMessage());
1544
      e.printStackTrace(System.out);
1545
      if(printFlag)
1546
      {
1547
        out.println("<error>"+e.getMessage()+"</error>");
1548
      }
1549
    }
1550
    finally
1551
    {
1552
      try
1553
      {
1554
        pstmt.close();
1555
      }//try
1556
      catch (SQLException ee)
1557
      {
1558
        logMetacat.error("Error in MetacatReplication.handleGetCatalogRequest: "
1559
           +ee.getMessage());
1560
      }//catch
1561
      finally
1562
      {
1563
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1564
      }//finally
1565
    }//finally
1566

    
1567
    return null;
1568
  }
1569

    
1570
  /**
1571
   * Sends the current system date to the remote server.  Using this action
1572
   * for replication gets rid of any problems with syncronizing clocks
1573
   * because a time specific to a document is always kept on its home server.
1574
   */
1575
  private void handleGetTimeRequest(PrintWriter out, Hashtable params,
1576
                                    HttpServletResponse response)
1577
  {
1578
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yy HH:mm:ss");
1579
    java.util.Date localtime = new java.util.Date();
1580
    String dateString = formatter.format(localtime);
1581
    response.setContentType("text/xml");
1582

    
1583
    out.println("<timestamp>" + dateString + "</timestamp>");
1584
  }
1585

    
1586
  /**
1587
   * this method handles the timeout for a file lock.  when a lock is
1588
   * granted it is granted for 30 seconds.  When this thread runs out
1589
   * it deletes the docid from the queue, thus eliminating the lock.
1590
   */
1591
  public void run()
1592
  {
1593
    try
1594
    {
1595
      logMetacat.info("thread started for docid: " +
1596
                               (String)fileLocks.elementAt(0));
1597

    
1598
      Thread.sleep(30000); //the lock will expire in 30 seconds
1599
      logMetacat.info("thread for docid: " +
1600
                             (String)fileLocks.elementAt(fileLocks.size() - 1) +
1601
                              " exiting.");
1602

    
1603
      fileLocks.remove(fileLocks.size() - 1);
1604
      //fileLocks is treated as a FIFO queue.  If there are more than one lock
1605
      //in the vector, the first one inserted will be removed.
1606
    }
1607
    catch(Exception e)
1608
    {
1609
      logMetacat.error("error in file lock thread from " +
1610
                                "MetacatReplication.run: " + e.getMessage());
1611
    }
1612
  }
1613

    
1614
  /**
1615
   * Returns the name of a server given a serverCode
1616
   * @param serverCode the serverid of the server
1617
   * @return the servername or null if the specified serverCode does not
1618
   *         exist.
1619
   */
1620
  public static String getServerNameForServerCode(int serverCode)
1621
  {
1622
    //System.out.println("serverid: " + serverCode);
1623
    DBConnection dbConn = null;
1624
    int serialNumber = -1;
1625
    PreparedStatement pstmt = null;
1626
    try
1627
    {
1628
      dbConn=DBConnectionPool.
1629
                  getDBConnection("MetacatReplication.getServer");
1630
      serialNumber=dbConn.getCheckOutSerialNumber();
1631
      String sql = new String("select server from " +
1632
                              "xml_replication where serverid = " +
1633
                              serverCode);
1634
      pstmt = dbConn.prepareStatement(sql);
1635
      //System.out.println("getserver sql: " + sql);
1636
      pstmt.execute();
1637
      ResultSet rs = pstmt.getResultSet();
1638
      boolean tablehasrows = rs.next();
1639
      if(tablehasrows)
1640
      {
1641
        //System.out.println("server: " + rs.getString(1));
1642
        return rs.getString(1);
1643
      }
1644

    
1645
      //conn.close();
1646
    }
1647
    catch(Exception e)
1648
    {
1649
      System.out.println("Error in MetacatReplication.getServer: " +
1650
                          e.getMessage());
1651
    }
1652
    finally
1653
    {
1654
      try
1655
      {
1656
        pstmt.close();
1657
      }//try
1658
      catch (SQLException ee)
1659
      {
1660
        logMetacat.error("Error in MetacactReplication.getserver: "+
1661
                                    ee.getMessage());
1662
      }//catch
1663
      finally
1664
      {
1665
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1666
      }//fianlly
1667
    }//finally
1668

    
1669

    
1670

    
1671
    return null;
1672
      //return null if the server does not exist
1673
  }
1674

    
1675
  /**
1676
   * Returns a server code given a server name
1677
   * @param server the name of the server
1678
   * @return integer > 0 representing the code of the server, 0 if the server
1679
   *  does not exist.
1680
   */
1681
  public static int getServerCodeForServerName(String server) throws Exception
1682
  {
1683
    DBConnection dbConn = null;
1684
    int serialNumber = -1;
1685
    PreparedStatement pstmt = null;
1686
    int serverCode = 0;
1687

    
1688
    try {
1689

    
1690
      //conn = util.openDBConnection();
1691
      dbConn=DBConnectionPool.
1692
                  getDBConnection("MetacatReplication.getServerCode");
1693
      serialNumber=dbConn.getCheckOutSerialNumber();
1694
      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
1695
                                    "WHERE server LIKE '" + server + "'");
1696
      pstmt.execute();
1697
      ResultSet rs = pstmt.getResultSet();
1698
      boolean tablehasrows = rs.next();
1699
      if ( tablehasrows ) {
1700
        serverCode = rs.getInt(1);
1701
        pstmt.close();
1702
        //conn.close();
1703
        return serverCode;
1704
      }
1705

    
1706
    } catch(Exception e) {
1707
      throw e;
1708

    
1709
    } finally {
1710
      try
1711
      {
1712
        pstmt.close();
1713
        //conn.close();
1714
       }//try
1715
       catch(Exception ee)
1716
       {
1717
         logMetacat.error("Error in MetacatReplicatio.getServerCode: "
1718
                                  +ee.getMessage());
1719

    
1720
       }//catch
1721
       finally
1722
       {
1723
         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1724
       }//finally
1725
    }//finally
1726

    
1727
    return serverCode;
1728
  }
1729

    
1730
  /**
1731
   * Method to get a host server information for given docid
1732
   * @param conn a connection to the database
1733
   */
1734
  public static Hashtable getHomeServerInfoForDocId(String docId)
1735
  {
1736
    Hashtable sl = new Hashtable();
1737
    DBConnection dbConn = null;
1738
    int serialNumber = -1;
1739
    docId=MetaCatUtil.getDocIdFromString(docId);
1740
    PreparedStatement pstmt=null;
1741
    int serverLocation;
1742
    try
1743
    {
1744
      //get conection
1745
      dbConn=DBConnectionPool.
1746
                  getDBConnection("ReplicationHandler.getHomeServer");
1747
      serialNumber=dbConn.getCheckOutSerialNumber();
1748
      //get a server location from xml_document table
1749
      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
1750
                                            +"where docid = ?");
1751
      pstmt.setString(1, docId);
1752
      pstmt.execute();
1753
      ResultSet serverName = pstmt.getResultSet();
1754
      //get a server location
1755
      if(serverName.next())
1756
      {
1757
        serverLocation=serverName.getInt(1);
1758
        pstmt.close();
1759
      }
1760
      else
1761
      {
1762
        pstmt.close();
1763
        //ut.returnConnection(conn);
1764
        return null;
1765
      }
1766
      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
1767
                        "from xml_replication where serverid = ?");
1768
      //increase usage count
1769
      dbConn.increaseUsageCount(1);
1770
      pstmt.setInt(1, serverLocation);
1771
      pstmt.execute();
1772
      ResultSet rs = pstmt.getResultSet();
1773
      boolean tableHasRows = rs.next();
1774
      if (tableHasRows)
1775
      {
1776

    
1777
          String server = rs.getString(1);
1778
          String last_checked = rs.getString(2);
1779
          if(!server.equals("localhost"))
1780
          {
1781
            sl.put(server, last_checked);
1782
          }
1783

    
1784
      }
1785
      else
1786
      {
1787
        pstmt.close();
1788
        //ut.returnConnection(conn);
1789
        return null;
1790
      }
1791
      pstmt.close();
1792
    }
1793
    catch(Exception e)
1794
    {
1795
      System.out.println("error in replicationHandler.getHomeServer(): " +
1796
                         e.getMessage());
1797
    }
1798
    finally
1799
    {
1800
      try
1801
      {
1802
        pstmt.close();
1803
        //ut.returnConnection(conn);
1804
      }
1805
      catch (Exception ee)
1806
      {
1807
        logMetacat.error("Eror irn rplicationHandler.getHomeServer() "+
1808
                          "to close pstmt: "+ee.getMessage());
1809
      }
1810
      finally
1811
      {
1812
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1813
      }
1814

    
1815
    }//finally
1816
    return sl;
1817
  }
1818

    
1819
  /**
1820
   * Returns a home server location  given a accnum
1821
   * @param accNum , given accNum for a document
1822
   *
1823
   */
1824
  public static int getHomeServerCodeForDocId(String accNum) throws Exception
1825
  {
1826
    DBConnection dbConn = null;
1827
    int serialNumber = -1;
1828
    PreparedStatement pstmt = null;
1829
    int serverCode = 1;
1830
    String docId=MetaCatUtil.getDocIdFromString(accNum);
1831

    
1832
    try
1833
    {
1834

    
1835
      // Get DBConnection
1836
      dbConn=DBConnectionPool.
1837
                  getDBConnection("ReplicationHandler.getServerLocation");
1838
      serialNumber=dbConn.getCheckOutSerialNumber();
1839
      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents "
1840
                              + "WHERE docid LIKE '" + docId + "'");
1841
      pstmt.execute();
1842
      ResultSet rs = pstmt.getResultSet();
1843
      boolean tablehasrows = rs.next();
1844
      //If a document is find, return the server location for it
1845
      if ( tablehasrows )
1846
      {
1847
        serverCode = rs.getInt(1);
1848
        pstmt.close();
1849
        //conn.close();
1850
        return serverCode;
1851
      }
1852
      //if couldn't find in xml_documents table, we think server code is 1
1853
      //(this is new document)
1854
      else
1855
      {
1856
        pstmt.close();
1857
        //conn.close();
1858
        return serverCode;
1859
      }
1860

    
1861
    }
1862
    catch(Exception e)
1863
    {
1864

    
1865
      throw e;
1866

    
1867
    }
1868
    finally
1869
    {
1870
      try
1871
      {
1872
        pstmt.close();
1873
        //conn.close();
1874

    
1875
      }
1876
      catch(Exception ee)
1877
      {
1878
        logMetacat.error("Erorr in Replication.getServerLocation "+
1879
                     "to close pstmt"+ee.getMessage());
1880
      }
1881
      finally
1882
      {
1883
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1884
      }//finally
1885
    }//finally
1886
   //return serverCode;
1887
  }
1888

    
1889

    
1890

    
1891
  /**
1892
   * This method returns the content of a url
1893
   * @param u the url to return the content from
1894
   * @return a string representing the content of the url
1895
   * @throws java.io.IOException
1896
   */
1897
  public static String getURLContent(URL u) throws java.io.IOException
1898
  {
1899
    char istreamChar;
1900
    int istreamInt;
1901
    logMetacat.info("Before open the stream"+u.toString());
1902
    InputStream input = u.openStream();
1903
    logMetacat.info("Afetr open the stream"+u.toString());
1904
    InputStreamReader istream = new InputStreamReader(input);
1905
    StringBuffer serverResponse = new StringBuffer();
1906
    while((istreamInt = istream.read()) != -1)
1907
    {
1908
      istreamChar = (char)istreamInt;
1909
      serverResponse.append(istreamChar);
1910
    }
1911
    istream.close();
1912
    input.close();
1913

    
1914
    return serverResponse.toString();
1915
  }
1916

    
1917
  /**
1918
	 * Method for writing replication messages to a log file specified in
1919
	 * metacat.properties
1920
	 */
1921
	public static void replLog(String message) {
1922
		try {
1923
			FileOutputStream fos = 
1924
				new FileOutputStream(PropertyService.getProperty("replication.logdir")
1925
					+ "/metacatreplication.log", true);
1926
			PrintWriter pw = new PrintWriter(fos);
1927
			SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
1928
			java.util.Date localtime = new java.util.Date();
1929
			String dateString = formatter.format(localtime);
1930
			dateString += " :: " + message;
1931
			// time stamp each entry
1932
			pw.println(dateString);
1933
			pw.flush();
1934
		} catch (Exception e) {
1935
			System.out.println("error writing to replication log from "
1936
					+ "MetacatReplication.replLog: " + e.getMessage());
1937
			// e.printStackTrace(System.out);
1938
		}
1939
	}
1940

    
1941
  /**
1942
	 * Method for writing replication messages to a log file specified in
1943
	 * metacat.properties
1944
	 */
1945
  public static void replErrorLog(String message)
1946
  {
1947
    try
1948
    {
1949
    	FileOutputStream fos = 
1950
			new FileOutputStream(PropertyService.getProperty("replication.logdir")
1951
				+ "/metacatreplicationerror.log", true);
1952
      PrintWriter pw = new PrintWriter(fos);
1953
      SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
1954
      java.util.Date localtime = new java.util.Date();
1955
      String dateString = formatter.format(localtime);
1956
      dateString += " :: " + message;
1957
      //time stamp each entry
1958
      pw.println(dateString);
1959
      pw.flush();
1960
    }
1961
    catch(Exception e)
1962
    {
1963
      System.out.println("error writing to replication error log from " +
1964
                         "MetacatReplication.replErrorLog: " + e.getMessage());
1965
      //e.printStackTrace(System.out);
1966
    }
1967
  }
1968

    
1969
  /**
1970
   * Returns true if the replicate field for server in xml_replication is 1.
1971
   * Returns false otherwise
1972
   */
1973
  public static boolean replToServer(String server)
1974
  {
1975
    DBConnection dbConn = null;
1976
    int serialNumber = -1;
1977
    PreparedStatement pstmt = null;
1978
    try
1979
    {
1980
      dbConn=DBConnectionPool.
1981
                  getDBConnection("MetacatReplication.repltoServer");
1982
      serialNumber=dbConn.getCheckOutSerialNumber();
1983
      pstmt = dbConn.prepareStatement("select replicate from " +
1984
                                    "xml_replication where server like '" +
1985
                                     server + "'");
1986
      pstmt.execute();
1987
      ResultSet rs = pstmt.getResultSet();
1988
      boolean tablehasrows = rs.next();
1989
      if(tablehasrows)
1990
      {
1991
        int i = rs.getInt(1);
1992
        if(i == 1)
1993
        {
1994
          pstmt.close();
1995
          //conn.close();
1996
          return true;
1997
        }
1998
        else
1999
        {
2000
          pstmt.close();
2001
          //conn.close();
2002
          return false;
2003
        }
2004
      }
2005
    }
2006
    catch(Exception e)
2007
    {
2008
      System.out.println("error in MetacatReplication.replToServer: " +
2009
                         e.getMessage());
2010
    }
2011
    finally
2012
    {
2013
      try
2014
      {
2015
        pstmt.close();
2016
        //conn.close();
2017
      }//try
2018
      catch(Exception ee)
2019
      {
2020
        logMetacat.error("Error in MetacatReplication.replToServer: "
2021
                                  +ee.getMessage());
2022
      }//catch
2023
      finally
2024
      {
2025
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2026
      }//finally
2027
    }//finally
2028
    return false;
2029
    //the default if this server does not exist is to not replicate to it.
2030
  }
2031

    
2032

    
2033
}
(46-46/67)