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 91 higgins
 *     Authors: Matt Jones, Dan Higgins
7 51 jones
 *
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 91 higgins
import java.io.File;  //DFH
44
import java.io.FileInputStream; //DFH
45 50 jones
46 46 jones
/**
47
 * A metadata catalog server implemented as a Java Servlet
48 50 jones
   *
49
   * <p>Valid parameters are:<br>
50
   * action=query -- query the values of all elements and attributes
51
   *                     and return a result set of nodes<br>
52
   * action=getdocument -- display an XML document in XML or HTML<br>
53
   * qformat=xml -- display resultset from query in XML<br>
54
   * qformat=html -- display resultset from query in HTML<br>
55
   * action=getdocument -- display an XML document in XML or HTML<br>
56
   * docid=34 -- display the document with the document ID number 34<br>
57 60 jones
   * action=putdocument -- load an XML document into the database store<br>
58
   * doctext -- XML text ofthe document to load into the database<br>
59 68 higgins
   * query -- actual query text (to go with 'action=query')<br>
60
   * action=validate -- vallidate the xml contained in validatetext<br>
61
   * valtext -- XML text to be validated
62 91 higgins
   * action=getdatadoc -- retreive a stored datadocument  //DFH
63
   * datadoc -- data document name (id)                   //DFH
64 46 jones
 */
65
public class MetaCatServlet extends HttpServlet {
66
67
  private ServletConfig		config = null;
68
  private ServletContext	context = null;
69 55 jones
  Connection 		conn = null;
70 46 jones
  DBSimpleQuery		queryobj = null;
71 49 jones
  DBReader		docreader = null;
72 87 jones
  DBTransform		dbt = null;
73 82 jones
  String 	user = null;
74
  String 	password = null;
75
  String 	defaultDB = null;
76
  String 	resultStyleURL = null;
77 83 jones
  String 	xmlcatalogfile = null;
78 91 higgins
  String    defaultdatapath = null;  // path to directory where data files that can be downloaded will be stored
79
  String    executescript  = null;  // script to get data file and put it in defaultdocpath dir
80 82 jones
  PropertyResourceBundle options = null;
81 46 jones
82 50 jones
  /**
83
   * Initialize the servlet by creating appropriate database connections
84
   */
85 46 jones
  public void init( ServletConfig config ) throws ServletException {
86
    try {
87
      super.init( config );
88
      this.config = config;
89
      this.context = config.getServletContext();
90 82 jones
      System.out.println("Servlet Initialize");
91
92 83 jones
      // Get the configuration file information
93 82 jones
      options = (PropertyResourceBundle)PropertyResourceBundle.getBundle("edu.ucsb.nceas.metacat.metacat");
94
      user = (String)options.handleGetObject("user");
95
      password = (String)options.handleGetObject("password");
96
      defaultDB = (String)options.handleGetObject("defaultDB");
97
      resultStyleURL = (String)options.handleGetObject("resultStyleURL");
98 83 jones
      xmlcatalogfile = (String)options.handleGetObject("xmlcatalogfile");
99 91 higgins
      defaultdatapath = (String)options.handleGetObject("defaultdatapath");
100
      executescript = (String)options.handleGetObject("executescript");
101 82 jones
102 46 jones
      try {
103 50 jones
        // Open a connection to the database
104 55 jones
        conn = MetaCatUtil.openDBConnection(
105 50 jones
                "oracle.jdbc.driver.OracleDriver",
106
                defaultDB, user, password);
107
108 55 jones
        queryobj = new DBSimpleQuery(conn);
109
        docreader = new DBReader(conn);
110 87 jones
        dbt = new DBTransform(conn);
111 68 higgins
112 46 jones
      } catch (Exception e) {
113 100 jones
        System.err.println("Error opening database connection");
114 46 jones
      }
115
    } catch ( ServletException ex ) {
116
      throw ex;
117
    }
118
  }
119
120 50 jones
  /** Handle "GET" method requests from HTTP clients */
121 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
122
    throws ServletException, IOException {
123
124 48 jones
    // Process the data and send back the response
125 59 jones
    handleGetOrPost(request, response);
126 48 jones
  }
127
128 50 jones
  /** Handle "POST" method requests from HTTP clients */
129 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
130
    throws ServletException, IOException {
131
132
    // Process the data and send back the response
133 59 jones
    handleGetOrPost(request, response);
134 48 jones
  }
135
136 49 jones
  /**
137 50 jones
   * Control servlet response depending on the action parameter specified
138 49 jones
   */
139 59 jones
  private void handleGetOrPost(HttpServletRequest request,
140
    HttpServletResponse response)
141 48 jones
    throws ServletException, IOException {
142
143 100 jones
    if (conn == null) {
144
      System.err.println("Connection to database lost.  Reopening...");
145
      try {
146
        // Open a connection to the database
147
        conn = MetaCatUtil.openDBConnection(
148
                "oracle.jdbc.driver.OracleDriver",
149
                defaultDB, user, password);
150
151
        queryobj = new DBSimpleQuery(conn);
152
        docreader = new DBReader(conn);
153
        dbt = new DBTransform(conn);
154
155
      } catch (Exception e) {
156
        System.err.println("Error opening database connection");
157
      }
158
    }
159
160 49 jones
    // Get a handle to the output stream back to the client
161 48 jones
    PrintWriter out = response.getWriter();
162 49 jones
163 59 jones
    String name = null;
164
    String[] value = null;
165
    Hashtable params = new Hashtable();
166
    Enumeration paramlist = request.getParameterNames();
167
    while (paramlist.hasMoreElements()) {
168
      name = (String)paramlist.nextElement();
169
      value = request.getParameterValues(name);
170
      params.put(name,value);
171
    }
172
173 49 jones
    String action = ((String[])params.get("action"))[0];
174 46 jones
175 49 jones
    if (action.equals("query")) {
176
      handleQueryAction(out, params, response);
177
    } else if (action.equals("getdocument")) {
178 87 jones
      try {
179
        handleGetDocumentAction(out, params, response);
180
      } catch (ClassNotFoundException e) {
181
        System.out.println(e.getMessage());
182
      } catch (SQLException se) {
183
        System.out.println(se.getMessage());
184
      }
185 55 jones
    } else if (action.equals("putdocument")) {
186
      handlePutDocumentAction(out, params, response);
187 68 higgins
    } else if (action.equals("validate")) {
188
      handleValidateAction(out, params, response);
189 91 higgins
    } else if (action.equals("getdatadoc")) {
190
      handleGetDataDocumentAction(out, params, response);
191 50 jones
    } else {
192
      out.println("Error: action not registered.  Please report this error.");
193 46 jones
    }
194
195 49 jones
    // Close the stream to the client
196 46 jones
    out.close();
197
  }
198 49 jones
199 50 jones
  /**
200
   * Handle the database query request and return a result set, possibly
201
   * transformed from XML into HTML
202
   */
203 49 jones
  private void handleQueryAction(PrintWriter out, Hashtable params,
204
               HttpServletResponse response) {
205
      // Run the query
206 82 jones
      Hashtable nodelist = null;
207 49 jones
      String query = ((String[])params.get("query"))[0];
208 82 jones
      if (queryobj != null) {
209 86 jones
        nodelist = queryobj.findDocuments(query);
210 82 jones
      } else {
211
        out.println("Query Object Init failed.");
212 83 jones
	/*
213 82 jones
        out.println(user);
214
        out.println(defaultDB);
215 83 jones
        out.println(xmlcatalogfile);
216
        */
217
        return;
218 82 jones
      }
219 50 jones
220
      // Create a buffer to hold the xml result
221
      StringBuffer resultset = new StringBuffer();
222
223 49 jones
      // Print the resulting root nodes
224 98 jones
      Long nodeid;
225
      String document = null;
226 50 jones
      resultset.append("<?xml version=\"1.0\"?>\n");
227 87 jones
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
228
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
229 50 jones
      resultset.append("<resultset>\n");
230
      resultset.append("  <query>" + query + "</query>");
231 49 jones
      Enumeration rootlist = nodelist.keys();
232
      while (rootlist.hasMoreElements()) {
233 98 jones
        nodeid = (Long)rootlist.nextElement();
234
        document = (String)nodelist.get(nodeid);
235
        resultset.append("  <document>" + document + "</document>");
236 49 jones
      }
237 50 jones
      resultset.append("</resultset>");
238
239
      String qformat = ((String[])params.get("qformat"))[0];
240
      if (qformat.equals("xml")) {
241
        // set content type and other response header fields first
242
        response.setContentType("text/xml");
243
        out.println(resultset.toString());
244
      } else if (qformat.equals("html")) {
245
        // set content type and other response header fields first
246
        response.setContentType("text/html");
247
        //out.println("Converting to HTML...");
248
        XMLDocumentFragment htmldoc = null;
249
        try {
250
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
251
          htmldoc = (new XSLProcessor()).processXSL(style,
252
                     (Reader)(new StringReader(resultset.toString())),null);
253
          htmldoc.print(out);
254
        } catch (Exception e) {
255
          out.println("Error transforming document:\n" + e.getMessage());
256
        }
257
      }
258 49 jones
  }
259
260 50 jones
  /**
261
   * Handle the database getdocument request and return a XML document,
262
   * possibly transformed from XML into HTML
263
   */
264 49 jones
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
265 87 jones
               HttpServletResponse response)
266
               throws ClassNotFoundException, IOException, SQLException {
267
      // Find the document id number
268
      String docidstr = ((String[])params.get("docid"))[0];
269
      long docid = (new Long(docidstr)).longValue();
270 49 jones
271 87 jones
      // Get the document indicated fromthe db
272
      String doc = docreader.readXMLDocument(docid);
273 85 jones
274 87 jones
275
      // Return the document in XML or HTML format
276 85 jones
      String qformat = ((String[])params.get("qformat"))[0];
277
      if (qformat.equals("xml")) {
278
        // set content type and other response header fields first
279
        response.setContentType("text/xml");
280
        out.println(doc);
281
      } else if (qformat.equals("html")) {
282
        // set content type and other response header fields first
283
        response.setContentType("text/html");
284
285 87 jones
        // Look up the document type
286
        String sourcetype = getDoctype(docid);
287 86 jones
288 87 jones
        // Transform the document to the new doctype
289
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
290 85 jones
      }
291 49 jones
  }
292 55 jones
293
  /**
294
   * Handle the database putdocument request and write an XML document
295
   * to the database connection
296
   */
297
  private void handlePutDocumentAction(PrintWriter out, Hashtable params,
298
               HttpServletResponse response) {
299 59 jones
300 55 jones
      // Get the document indicated
301 59 jones
      String[] doctext = (String[])params.get("doctext");
302
      StringReader xml = new StringReader(doctext[0]);
303
304
      // write the document to the database
305 55 jones
      try {
306 59 jones
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
307 55 jones
      } catch (SQLException e1) {
308 59 jones
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
309 55 jones
      }catch (IOException e2) {
310 59 jones
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
311 55 jones
      }catch (ClassNotFoundException e3) {
312 59 jones
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
313 55 jones
      }
314
315
      // set content type and other response header fields first
316 59 jones
      response.setContentType("text/xml");
317 55 jones
318 59 jones
      out.println(doctext[0]);
319 55 jones
  }
320 68 higgins
321
  /**
322
   * Handle the validtion request and return the results
323
   * to the requestor - DFH
324
   */
325
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
326
327
      // Get the document indicated
328
      String[] valtext = (String[])params.get("valtext");
329
330
331
      SAXParser parser = new SAXParser();           // works for both Xerces and Oracle
332
      parser.setValidationMode(true);               // Oracle
333 83 jones
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
334 68 higgins
      boolean valid = gxv.validateString(valtext[0]);
335
336
      // set content type and other response header fields first
337
      response.setContentType("text/plain");
338
339
      if (valid) {
340
        out.println("The input XML is VALID!");
341
      }
342
      else {
343
        out.println("The input XML is NOT VALID\n" + gxv.returnErrors());
344
      }
345
    }
346 87 jones
347
  /**
348
   * Look up the document type from the database
349
   *
350
   */
351
  private String getDoctype(long docid) {
352
    // Look up the System ID of the XSL sheet
353
    PreparedStatement pstmt;
354
    String doctype = null;
355
356
    try {
357
      pstmt =
358
        conn.prepareStatement("SELECT doctype " +
359
                                "FROM xml_documents " +
360
                               "WHERE docid = ?");
361
      // Bind the values to the query
362
      pstmt.setLong(1, new Long(docid).longValue());
363
364
      pstmt.execute();
365
      try {
366
        ResultSet rs = pstmt.getResultSet();
367
        try {
368
          boolean tableHasRows = rs.next();
369
          if (tableHasRows) {
370
            try {
371
              doctype  = rs.getString(1);
372
            } catch (SQLException e) {
373
              System.out.println("Error with getString: " + e.getMessage());
374
            }
375
          }
376
        } catch (SQLException e) {
377
          System.out.println("Error with next: " + e.getMessage());
378
        }
379
      } catch (SQLException e) {
380
        System.out.println("Error with getrset: " + e.getMessage());
381
      }
382
      pstmt.close();
383
    } catch (SQLException e) {
384
      System.out.println("Error getting id: " + e.getMessage());
385
    }
386
387
    return doctype;
388
  }
389 91 higgins
390
391
  /**
392
   * Handle the document request and return the results
393
   * to the requestor - DFH
394
   */
395
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
396
      boolean error_flag = false;
397
      String error_message = "";
398
      // Get the document indicated
399
      String[] datadoc = (String[])params.get("datadoc");
400
  //    defaultdatapath = "C:\\Temp\\";    // for testing only!!!
401
   //   executescript = "test.bat";        // for testing only!!!
402
403
      // set content type and other response header fields first
404
      response.setContentType("application/octet-stream");
405
   if (defaultdatapath!=null) {
406
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) defaultdatapath=defaultdatapath+System.getProperty("file.separator");
407
      System.out.println("Path= "+defaultdatapath+datadoc[0]);
408
      if (executescript!=null) {
409
        String command = null;
410
        File scriptfile = new File(executescript);
411
        if (scriptfile.exists()) {
412
            command=executescript+" "+datadoc[0]; }  // execute script includes path
413
        else {     // look in defaultdatapath
414
                command = defaultdatapath+executescript+" "+datadoc[0];  // on Win98 one MUST include the .bat extender
415
        }
416
      System.out.println(command);
417
      try {
418
      Process proc = Runtime.getRuntime().exec(command);
419
      proc.waitFor();
420
      }
421
      catch (Exception eee) {
422
        System.out.println("Error running process!");
423
        error_flag = true;
424
        error_message = "Error running process!";}
425
      } // end executescript not null if
426
      File datafile = new File(defaultdatapath+datadoc[0]);
427
      try {
428
      FileInputStream fw = new FileInputStream(datafile);
429
      int x;
430
     while ((x = fw.read())!=-1) {
431
        out.write(x); }
432
      fw.close();
433
434
      }
435
      catch (Exception e) {
436
        System.out.println("Error in returning file\n"+e.getMessage());
437
        error_flag=true;
438
        error_message = error_message+"\nError in returning file\n"+e.getMessage();}
439
   } // end defaultdatapath not null if
440
  }
441
442
443 46 jones
}