Project

General

Profile

1 51 jones
/**
2
 *        Name: MetaCatServlet.java
3
 *     Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *   Copyright: 2000 Regents of the University of California and the
5
 *              National Center for Ecological Analysis and Synthesis
6
 *     Authors: Matt Jones
7
 *
8
 *     Version: '$Id$'
9
 */
10
11
package edu.ucsb.nceas.metacat;
12
13 46 jones
import java.io.PrintWriter;
14
import java.io.IOException;
15 50 jones
import java.io.Reader;
16
import java.io.StringReader;
17 59 jones
import java.io.BufferedReader;
18 46 jones
import java.util.Enumeration;
19
import java.util.Hashtable;
20 82 jones
import java.util.ResourceBundle;
21
import java.util.PropertyResourceBundle;
22 50 jones
import java.net.URL;
23
import java.net.MalformedURLException;
24 85 jones
import java.sql.PreparedStatement;
25
import java.sql.ResultSet;
26 50 jones
import java.sql.Connection;
27 55 jones
import java.sql.SQLException;
28 46 jones
29
import javax.servlet.ServletConfig;
30
import javax.servlet.ServletContext;
31
import javax.servlet.ServletException;
32 48 jones
import javax.servlet.ServletInputStream;
33 46 jones
import javax.servlet.http.HttpServlet;
34
import javax.servlet.http.HttpServletRequest;
35
import javax.servlet.http.HttpServletResponse;
36 47 jones
import javax.servlet.http.HttpUtils;
37 46 jones
38 50 jones
import oracle.xml.parser.v2.XSLStylesheet;
39
import oracle.xml.parser.v2.XSLException;
40
import oracle.xml.parser.v2.XMLDocumentFragment;
41
import oracle.xml.parser.v2.XSLProcessor;
42 68 higgins
import oracle.xml.parser.v2.*;    //Oracle parser - DFH
43 50 jones
44 46 jones
/**
45
 * A metadata catalog server implemented as a Java Servlet
46 50 jones
   *
47
   * <p>Valid parameters are:<br>
48
   * action=query -- query the values of all elements and attributes
49
   *                     and return a result set of nodes<br>
50
   * action=getdocument -- display an XML document in XML or HTML<br>
51
   * qformat=xml -- display resultset from query in XML<br>
52
   * qformat=html -- display resultset from query in HTML<br>
53
   * action=getdocument -- display an XML document in XML or HTML<br>
54
   * docid=34 -- display the document with the document ID number 34<br>
55 60 jones
   * action=putdocument -- load an XML document into the database store<br>
56
   * doctext -- XML text ofthe document to load into the database<br>
57 68 higgins
   * query -- actual query text (to go with 'action=query')<br>
58
   * action=validate -- vallidate the xml contained in validatetext<br>
59
   * valtext -- XML text to be validated
60 46 jones
 */
61
public class MetaCatServlet extends HttpServlet {
62
63
  private ServletConfig		config = null;
64
  private ServletContext	context = null;
65 55 jones
  Connection 		conn = null;
66 46 jones
  DBSimpleQuery		queryobj = null;
67 49 jones
  DBReader		docreader = null;
68 87 jones
  DBTransform		dbt = null;
69 82 jones
  String 	user = null;
70
  String 	password = null;
71
  String 	defaultDB = null;
72
  String 	resultStyleURL = null;
73 83 jones
  String 	xmlcatalogfile = null;
74 82 jones
  PropertyResourceBundle options = null;
75 46 jones
76 50 jones
  /**
77
   * Initialize the servlet by creating appropriate database connections
78
   */
79 46 jones
  public void init( ServletConfig config ) throws ServletException {
80
    try {
81
      super.init( config );
82
      this.config = config;
83
      this.context = config.getServletContext();
84 82 jones
      System.out.println("Servlet Initialize");
85
86 83 jones
      // Get the configuration file information
87 82 jones
      options = (PropertyResourceBundle)PropertyResourceBundle.getBundle("edu.ucsb.nceas.metacat.metacat");
88
      user = (String)options.handleGetObject("user");
89
      password = (String)options.handleGetObject("password");
90
      defaultDB = (String)options.handleGetObject("defaultDB");
91
      resultStyleURL = (String)options.handleGetObject("resultStyleURL");
92 83 jones
      xmlcatalogfile = (String)options.handleGetObject("xmlcatalogfile");
93 82 jones
94 46 jones
      try {
95 50 jones
        // Open a connection to the database
96 55 jones
        conn = MetaCatUtil.openDBConnection(
97 50 jones
                "oracle.jdbc.driver.OracleDriver",
98
                defaultDB, user, password);
99
100 55 jones
        queryobj = new DBSimpleQuery(conn);
101
        docreader = new DBReader(conn);
102 87 jones
        dbt = new DBTransform(conn);
103 68 higgins
104 46 jones
      } catch (Exception e) {
105
      }
106
    } catch ( ServletException ex ) {
107
      throw ex;
108
    }
109
  }
110
111 50 jones
  /** Handle "GET" method requests from HTTP clients */
112 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
113
    throws ServletException, IOException {
114
115 48 jones
    // Process the data and send back the response
116 59 jones
    handleGetOrPost(request, response);
117 48 jones
  }
118
119 50 jones
  /** Handle "POST" method requests from HTTP clients */
120 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
121
    throws ServletException, IOException {
122
123
    // Process the data and send back the response
124 59 jones
    handleGetOrPost(request, response);
125 48 jones
  }
126
127 49 jones
  /**
128 50 jones
   * Control servlet response depending on the action parameter specified
129 49 jones
   */
130 59 jones
  private void handleGetOrPost(HttpServletRequest request,
131
    HttpServletResponse response)
132 48 jones
    throws ServletException, IOException {
133
134 49 jones
    // Get a handle to the output stream back to the client
135 48 jones
    PrintWriter out = response.getWriter();
136 49 jones
137 59 jones
    String name = null;
138
    String[] value = null;
139
    Hashtable params = new Hashtable();
140
    Enumeration paramlist = request.getParameterNames();
141
    while (paramlist.hasMoreElements()) {
142
      name = (String)paramlist.nextElement();
143
      value = request.getParameterValues(name);
144
      params.put(name,value);
145
    }
146
147 49 jones
    String action = ((String[])params.get("action"))[0];
148 46 jones
149 49 jones
    if (action.equals("query")) {
150
      handleQueryAction(out, params, response);
151
    } else if (action.equals("getdocument")) {
152 87 jones
      try {
153
        handleGetDocumentAction(out, params, response);
154
      } catch (ClassNotFoundException e) {
155
        System.out.println(e.getMessage());
156
      } catch (SQLException se) {
157
        System.out.println(se.getMessage());
158
      }
159 55 jones
    } else if (action.equals("putdocument")) {
160
      handlePutDocumentAction(out, params, response);
161 68 higgins
    } else if (action.equals("validate")) {
162
      handleValidateAction(out, params, response);
163 50 jones
    } else {
164
      out.println("Error: action not registered.  Please report this error.");
165 46 jones
    }
166
167 49 jones
    // Close the stream to the client
168 46 jones
    out.close();
169
  }
170 49 jones
171 50 jones
  /**
172
   * Handle the database query request and return a result set, possibly
173
   * transformed from XML into HTML
174
   */
175 49 jones
  private void handleQueryAction(PrintWriter out, Hashtable params,
176
               HttpServletResponse response) {
177
      // Run the query
178 82 jones
      Hashtable nodelist = null;
179 49 jones
      String query = ((String[])params.get("query"))[0];
180 82 jones
      if (queryobj != null) {
181 86 jones
        nodelist = queryobj.findDocuments(query);
182 82 jones
      } else {
183
        out.println("Query Object Init failed.");
184 83 jones
	/*
185 82 jones
        out.println(user);
186
        out.println(defaultDB);
187 83 jones
        out.println(xmlcatalogfile);
188
        */
189
        return;
190 82 jones
      }
191 50 jones
192
      // Create a buffer to hold the xml result
193
      StringBuffer resultset = new StringBuffer();
194
195 49 jones
      // Print the resulting root nodes
196
      long nodeid;
197 50 jones
      resultset.append("<?xml version=\"1.0\"?>\n");
198 87 jones
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
199
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
200 50 jones
      resultset.append("<resultset>\n");
201
      resultset.append("  <query>" + query + "</query>");
202 49 jones
      Enumeration rootlist = nodelist.keys();
203
      while (rootlist.hasMoreElements()) {
204
        nodeid = ((Long)rootlist.nextElement()).longValue();
205 88 jones
        resultset.append("  <docid>" + nodeid + "</docid>");
206 49 jones
      }
207 50 jones
      resultset.append("</resultset>");
208
209
      String qformat = ((String[])params.get("qformat"))[0];
210
      if (qformat.equals("xml")) {
211
        // set content type and other response header fields first
212
        response.setContentType("text/xml");
213
        out.println(resultset.toString());
214
      } else if (qformat.equals("html")) {
215
        // set content type and other response header fields first
216
        response.setContentType("text/html");
217
        //out.println("Converting to HTML...");
218
        XMLDocumentFragment htmldoc = null;
219
        try {
220
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
221
          htmldoc = (new XSLProcessor()).processXSL(style,
222
                     (Reader)(new StringReader(resultset.toString())),null);
223
          htmldoc.print(out);
224
        } catch (Exception e) {
225
          out.println("Error transforming document:\n" + e.getMessage());
226
        }
227
      }
228 49 jones
  }
229
230 50 jones
  /**
231
   * Handle the database getdocument request and return a XML document,
232
   * possibly transformed from XML into HTML
233
   */
234 49 jones
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
235 87 jones
               HttpServletResponse response)
236
               throws ClassNotFoundException, IOException, SQLException {
237
      // Find the document id number
238
      String docidstr = ((String[])params.get("docid"))[0];
239
      long docid = (new Long(docidstr)).longValue();
240 49 jones
241 87 jones
      // Get the document indicated fromthe db
242
      String doc = docreader.readXMLDocument(docid);
243 85 jones
244 87 jones
245
      // Return the document in XML or HTML format
246 85 jones
      String qformat = ((String[])params.get("qformat"))[0];
247
      if (qformat.equals("xml")) {
248
        // set content type and other response header fields first
249
        response.setContentType("text/xml");
250
        out.println(doc);
251
      } else if (qformat.equals("html")) {
252
        // set content type and other response header fields first
253
        response.setContentType("text/html");
254
255 87 jones
        // Look up the document type
256
        String sourcetype = getDoctype(docid);
257 86 jones
258 87 jones
        // Transform the document to the new doctype
259
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
260 85 jones
      }
261 49 jones
  }
262 55 jones
263
  /**
264
   * Handle the database putdocument request and write an XML document
265
   * to the database connection
266
   */
267
  private void handlePutDocumentAction(PrintWriter out, Hashtable params,
268
               HttpServletResponse response) {
269 59 jones
270 55 jones
      // Get the document indicated
271 59 jones
      String[] doctext = (String[])params.get("doctext");
272
      StringReader xml = new StringReader(doctext[0]);
273
274
      // write the document to the database
275 55 jones
      try {
276 59 jones
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
277 55 jones
      } catch (SQLException e1) {
278 59 jones
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
279 55 jones
      }catch (IOException e2) {
280 59 jones
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
281 55 jones
      }catch (ClassNotFoundException e3) {
282 59 jones
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
283 55 jones
      }
284
285
      // set content type and other response header fields first
286 59 jones
      response.setContentType("text/xml");
287 55 jones
288 59 jones
      out.println(doctext[0]);
289 55 jones
  }
290 68 higgins
291
  /**
292
   * Handle the validtion request and return the results
293
   * to the requestor - DFH
294
   */
295
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
296
297
      // Get the document indicated
298
      String[] valtext = (String[])params.get("valtext");
299
300
301
      SAXParser parser = new SAXParser();           // works for both Xerces and Oracle
302
      parser.setValidationMode(true);               // Oracle
303 83 jones
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
304 68 higgins
      boolean valid = gxv.validateString(valtext[0]);
305
306
      // set content type and other response header fields first
307
      response.setContentType("text/plain");
308
309
      if (valid) {
310
        out.println("The input XML is VALID!");
311
      }
312
      else {
313
        out.println("The input XML is NOT VALID\n" + gxv.returnErrors());
314
      }
315
    }
316 87 jones
317
  /**
318
   * Look up the document type from the database
319
   *
320
   */
321
  private String getDoctype(long docid) {
322
    // Look up the System ID of the XSL sheet
323
    PreparedStatement pstmt;
324
    String doctype = null;
325
326
    try {
327
      pstmt =
328
        conn.prepareStatement("SELECT doctype " +
329
                                "FROM xml_documents " +
330
                               "WHERE docid = ?");
331
      // Bind the values to the query
332
      pstmt.setLong(1, new Long(docid).longValue());
333
334
      pstmt.execute();
335
      try {
336
        ResultSet rs = pstmt.getResultSet();
337
        try {
338
          boolean tableHasRows = rs.next();
339
          if (tableHasRows) {
340
            try {
341
              doctype  = rs.getString(1);
342
            } catch (SQLException e) {
343
              System.out.println("Error with getString: " + e.getMessage());
344
            }
345
          }
346
        } catch (SQLException e) {
347
          System.out.println("Error with next: " + e.getMessage());
348
        }
349
      } catch (SQLException e) {
350
        System.out.println("Error with getrset: " + e.getMessage());
351
      }
352
      pstmt.close();
353
    } catch (SQLException e) {
354
      System.out.println("Error getting id: " + e.getMessage());
355
    }
356
357
    return doctype;
358
  }
359 46 jones
}