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: berkley $'
10
 *     '$Date: 2000-11-16 15:26:00 -0800 (Thu, 16 Nov 2000) $'
11
 * '$Revision: 549 $'
12
 */
13

    
14
package edu.ucsb.nceas.metacat;
15

    
16
import java.util.*;
17
import java.io.*;
18
import java.sql.*;
19
import java.net.*;
20
import java.lang.*;
21
import java.text.*;
22
import javax.servlet.*;
23
import javax.servlet.http.*;
24
import oracle.xml.parser.v2.*;
25
import org.xml.sax.*;
26

    
27
public class MetacatReplication extends HttpServlet
28
{  
29
  private String deltaT;
30
  Timer replicationDaemon;
31
  MetaCatUtil util = new MetaCatUtil();
32
  
33
  /**
34
   * Initialize the servlet by creating appropriate database connections
35
   */
36
  public void init(ServletConfig config) throws ServletException 
37
  {
38
    //initialize db connections to handle any update requests
39
    MetaCatUtil util = new MetaCatUtil();
40
    deltaT = util.getOption("deltaT");
41
    //break off a thread to do the delta-T check
42
    replicationDaemon = new Timer(true);
43
    //replicationDaemon.scheduleAtFixedRate(new replicationHandler(), 0, 
44
    //                                      new Integer(deltaT).intValue() * 1000);
45
    //System.out.println("timer scheduled at: " + new Integer(deltaT).intValue() 
46
    //                   + " seconds");
47
    
48
  }
49
  
50
  public void destroy() 
51
  {
52
    replicationDaemon.cancel();
53
    System.out.println("Replication daemon cancelled.");
54
  }
55
  
56
  public void doGet (HttpServletRequest request, HttpServletResponse response)
57
                     throws ServletException, IOException 
58
  {
59
    // Process the data and send back the response
60
    handleGetOrPost(request, response);
61
  }
62

    
63
  public void doPost(HttpServletRequest request, HttpServletResponse response)
64
                     throws ServletException, IOException 
65
  {
66
    // Process the data and send back the response
67
    handleGetOrPost(request, response);
68
  }
69
  
70
  private void handleGetOrPost(HttpServletRequest request, 
71
                               HttpServletResponse response) 
72
                               throws ServletException, IOException 
73
  {
74
    PrintWriter out = response.getWriter();
75
    
76
    Hashtable params = new Hashtable();
77
    Enumeration paramlist = request.getParameterNames();
78
    
79
    while (paramlist.hasMoreElements()) 
80
    {
81
      String name = (String)paramlist.nextElement();
82
      String[] value = request.getParameterValues(name);
83
      params.put(name, value);  
84
    }
85
    
86
    if(params.containsKey("action"))
87
    {
88
      if(((String[])params.get("action"))[0].equals("stop"))
89
      { //stop the replication server
90
        replicationDaemon.cancel();
91
        out.println("Replication Handler Stopped");
92
      }
93
      else if(((String[])params.get("action"))[0].equals("start"))
94
      { //start the replication server
95
        int rate;
96
        if(params.containsKey("rate"))
97
        {
98
          rate = new Integer(
99
                 new String(((String[])params.get("rate"))[0])).intValue();
100
          if(rate < 30)
101
          {
102
            out.println("Replication deltaT rate cannot be less than 30!");
103
            rate = 1000;
104
          }
105
        }
106
        else
107
        {
108
          rate = 1000;
109
        }
110
        
111
        out.println("New rate is: " + rate + " seconds.");
112
        replicationDaemon.cancel();
113
        replicationDaemon = new Timer(true);
114
        replicationDaemon.scheduleAtFixedRate(new ReplicationHandler(out), 0, 
115
                                              rate * 1000);
116
        out.println("Replication Handler Started");
117
      }
118
      else if(((String[])params.get("action"))[0].equals("update"))
119
      { //request an update list from the server
120
        handleUpdateRequest(out, params, response);
121
      }
122
      else if(((String[])params.get("action"))[0].equals("getdocument"))
123
      { //request a specific document from the server
124
        //note that this could be replaced by a call to metacatServlet
125
        //handleGetDocumentAction().
126
        handleGetDocumentRequest(out, params, response);
127
      }
128
    }
129
  }
130
  
131
  private void handleGetDocumentRequest(PrintWriter out, Hashtable params, 
132
                                   HttpServletResponse response)
133
  {
134
    try
135
    {
136
      String docid = ((String[])(params.get("docid")))[0];
137
      System.out.println("incoming get request for document: " +
138
                         docid);
139
      Connection conn = util.openDBConnection();
140
      DocumentImpl di = new DocumentImpl(conn, docid);
141
      response.setContentType("text/xml");
142
      out.print(di.toString());
143
      conn.close();
144
    }
145
    catch(Exception e)
146
    {
147
      System.out.println("error getting document: " + e.getMessage());
148
    }
149
    
150
  }
151
  
152
  private void handleUpdateRequest(PrintWriter out, Hashtable params, 
153
                                   HttpServletResponse response)
154
  {
155
    System.out.println("incoming update request for dt/time " + 
156
                       ((String[])params.get("date"))[0] +
157
                       " from external metacat");
158
    response.setContentType("text/xml");
159
    StringBuffer returnXML = new StringBuffer();
160
    returnXML.append("<?xml version=\"1.0\"?><replication>");
161
    
162
    StringBuffer sql = new StringBuffer();
163
    String updateStr = ((String[])params.get("date"))[0];
164
    updateStr = updateStr.replace('+', ' ');
165
    //pseudo algorithm:
166
    ///////////////////////////////////////////////////////////////////////
167
    //get the date/time from the requestor, query the db for any documents
168
    //that have an update date later than the requested date and send
169
    //those docids back to the requestor.  If there are no newer documents
170
    //then send back a null message.
171
    ///////////////////////////////////////////////////////////////////////
172
    
173
    //Timestamp update = Timestamp.valueOf(updateStr);
174
    SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
175
    java.util.Date update = new java.util.Date();
176
    ParsePosition pos = new ParsePosition(0);
177
    update = formatter.parse(updateStr, pos);
178
    //update = new java.util.Date(update.getTime() - 10000);
179
    String dateString = formatter.format(update);
180
    sql.append("select docid, date_updated, server_location from ");
181
    sql.append("xml_documents where date_updated > ");
182
    sql.append("to_date('").append(dateString).append("','YY-MM-DD HH24:MI:SS')");
183
    //System.out.println("sql: " + sql.toString());
184
    
185
    try
186
    {
187
      Connection conn = util.openDBConnection();
188
      PreparedStatement pstmt = conn.prepareStatement(sql.toString());
189
      pstmt.execute();
190
      ResultSet rs = pstmt.getResultSet();
191
      boolean tablehasrows = rs.next();
192
      
193
      //if a '1' should not represent localhost, add code here to query
194
      //xml_replication for the proper serverid number
195
      
196
      returnXML.append("<server>").append(util.getOption("server"));
197
      returnXML.append(util.getOption("replicationpath"));
198
      returnXML.append("</server><updates>");
199
      while(tablehasrows)
200
      {
201
        String docid = rs.getString(1);
202
        String dateUpdated = rs.getString(2);
203
        int serverCode = rs.getInt(3);
204
        if(serverCode == 1)
205
        { //check that this document is from this server.
206
          //servers only replicate their own documents!
207
          returnXML.append("<updatedDocument><docid>").append(docid);
208
          returnXML.append("</docid><date_updated>").append(dateUpdated);
209
          returnXML.append("</date_updated></updatedDocument>");
210
        }
211
        tablehasrows = rs.next();
212
      }
213
      returnXML.append("</updates></replication>");
214
      conn.close();
215
      //System.out.println(returnXML.toString());
216
      out.print(returnXML.toString());
217
    }
218
    catch(Exception e)
219
    {
220
      System.out.println("Exception in metacatReplication: " + e.getMessage());
221
    }
222
  }
223
}
(25-25/34)