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
      }
114
    } catch ( ServletException ex ) {
115
      throw ex;
116
    }
117
  }
118
119 50 jones
  /** Handle "GET" method requests from HTTP clients */
120 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
121
    throws ServletException, IOException {
122
123 48 jones
    // Process the data and send back the response
124 59 jones
    handleGetOrPost(request, response);
125 48 jones
  }
126
127 50 jones
  /** Handle "POST" method requests from HTTP clients */
128 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
129
    throws ServletException, IOException {
130
131
    // Process the data and send back the response
132 59 jones
    handleGetOrPost(request, response);
133 48 jones
  }
134
135 49 jones
  /**
136 50 jones
   * Control servlet response depending on the action parameter specified
137 49 jones
   */
138 59 jones
  private void handleGetOrPost(HttpServletRequest request,
139
    HttpServletResponse response)
140 48 jones
    throws ServletException, IOException {
141
142 49 jones
    // Get a handle to the output stream back to the client
143 48 jones
    PrintWriter out = response.getWriter();
144 49 jones
145 59 jones
    String name = null;
146
    String[] value = null;
147
    Hashtable params = new Hashtable();
148
    Enumeration paramlist = request.getParameterNames();
149
    while (paramlist.hasMoreElements()) {
150
      name = (String)paramlist.nextElement();
151
      value = request.getParameterValues(name);
152
      params.put(name,value);
153
    }
154
155 49 jones
    String action = ((String[])params.get("action"))[0];
156 46 jones
157 49 jones
    if (action.equals("query")) {
158
      handleQueryAction(out, params, response);
159
    } else if (action.equals("getdocument")) {
160 87 jones
      try {
161
        handleGetDocumentAction(out, params, response);
162
      } catch (ClassNotFoundException e) {
163
        System.out.println(e.getMessage());
164
      } catch (SQLException se) {
165
        System.out.println(se.getMessage());
166
      }
167 55 jones
    } else if (action.equals("putdocument")) {
168
      handlePutDocumentAction(out, params, response);
169 68 higgins
    } else if (action.equals("validate")) {
170
      handleValidateAction(out, params, response);
171 91 higgins
    } else if (action.equals("getdatadoc")) {
172
      handleGetDataDocumentAction(out, params, response);
173 50 jones
    } else {
174
      out.println("Error: action not registered.  Please report this error.");
175 46 jones
    }
176
177 49 jones
    // Close the stream to the client
178 46 jones
    out.close();
179
  }
180 49 jones
181 50 jones
  /**
182
   * Handle the database query request and return a result set, possibly
183
   * transformed from XML into HTML
184
   */
185 49 jones
  private void handleQueryAction(PrintWriter out, Hashtable params,
186
               HttpServletResponse response) {
187
      // Run the query
188 82 jones
      Hashtable nodelist = null;
189 49 jones
      String query = ((String[])params.get("query"))[0];
190 82 jones
      if (queryobj != null) {
191 86 jones
        nodelist = queryobj.findDocuments(query);
192 82 jones
      } else {
193
        out.println("Query Object Init failed.");
194 83 jones
	/*
195 82 jones
        out.println(user);
196
        out.println(defaultDB);
197 83 jones
        out.println(xmlcatalogfile);
198
        */
199
        return;
200 82 jones
      }
201 50 jones
202
      // Create a buffer to hold the xml result
203
      StringBuffer resultset = new StringBuffer();
204
205 49 jones
      // Print the resulting root nodes
206
      long nodeid;
207 50 jones
      resultset.append("<?xml version=\"1.0\"?>\n");
208 87 jones
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
209
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
210 50 jones
      resultset.append("<resultset>\n");
211
      resultset.append("  <query>" + query + "</query>");
212 49 jones
      Enumeration rootlist = nodelist.keys();
213
      while (rootlist.hasMoreElements()) {
214
        nodeid = ((Long)rootlist.nextElement()).longValue();
215 88 jones
        resultset.append("  <docid>" + nodeid + "</docid>");
216 49 jones
      }
217 50 jones
      resultset.append("</resultset>");
218
219
      String qformat = ((String[])params.get("qformat"))[0];
220
      if (qformat.equals("xml")) {
221
        // set content type and other response header fields first
222
        response.setContentType("text/xml");
223
        out.println(resultset.toString());
224
      } else if (qformat.equals("html")) {
225
        // set content type and other response header fields first
226
        response.setContentType("text/html");
227
        //out.println("Converting to HTML...");
228
        XMLDocumentFragment htmldoc = null;
229
        try {
230
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
231
          htmldoc = (new XSLProcessor()).processXSL(style,
232
                     (Reader)(new StringReader(resultset.toString())),null);
233
          htmldoc.print(out);
234
        } catch (Exception e) {
235
          out.println("Error transforming document:\n" + e.getMessage());
236
        }
237
      }
238 49 jones
  }
239
240 50 jones
  /**
241
   * Handle the database getdocument request and return a XML document,
242
   * possibly transformed from XML into HTML
243
   */
244 49 jones
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
245 87 jones
               HttpServletResponse response)
246
               throws ClassNotFoundException, IOException, SQLException {
247
      // Find the document id number
248
      String docidstr = ((String[])params.get("docid"))[0];
249
      long docid = (new Long(docidstr)).longValue();
250 49 jones
251 87 jones
      // Get the document indicated fromthe db
252
      String doc = docreader.readXMLDocument(docid);
253 85 jones
254 87 jones
255
      // Return the document in XML or HTML format
256 85 jones
      String qformat = ((String[])params.get("qformat"))[0];
257
      if (qformat.equals("xml")) {
258
        // set content type and other response header fields first
259
        response.setContentType("text/xml");
260
        out.println(doc);
261
      } else if (qformat.equals("html")) {
262
        // set content type and other response header fields first
263
        response.setContentType("text/html");
264
265 87 jones
        // Look up the document type
266
        String sourcetype = getDoctype(docid);
267 86 jones
268 87 jones
        // Transform the document to the new doctype
269
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
270 85 jones
      }
271 49 jones
  }
272 55 jones
273
  /**
274
   * Handle the database putdocument request and write an XML document
275
   * to the database connection
276
   */
277
  private void handlePutDocumentAction(PrintWriter out, Hashtable params,
278
               HttpServletResponse response) {
279 59 jones
280 55 jones
      // Get the document indicated
281 59 jones
      String[] doctext = (String[])params.get("doctext");
282
      StringReader xml = new StringReader(doctext[0]);
283
284
      // write the document to the database
285 55 jones
      try {
286 59 jones
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
287 55 jones
      } catch (SQLException e1) {
288 59 jones
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
289 55 jones
      }catch (IOException e2) {
290 59 jones
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
291 55 jones
      }catch (ClassNotFoundException e3) {
292 59 jones
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
293 55 jones
      }
294
295
      // set content type and other response header fields first
296 59 jones
      response.setContentType("text/xml");
297 55 jones
298 59 jones
      out.println(doctext[0]);
299 55 jones
  }
300 68 higgins
301
  /**
302
   * Handle the validtion request and return the results
303
   * to the requestor - DFH
304
   */
305
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
306
307
      // Get the document indicated
308
      String[] valtext = (String[])params.get("valtext");
309
310
311
      SAXParser parser = new SAXParser();           // works for both Xerces and Oracle
312
      parser.setValidationMode(true);               // Oracle
313 83 jones
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
314 68 higgins
      boolean valid = gxv.validateString(valtext[0]);
315
316
      // set content type and other response header fields first
317
      response.setContentType("text/plain");
318
319
      if (valid) {
320
        out.println("The input XML is VALID!");
321
      }
322
      else {
323
        out.println("The input XML is NOT VALID\n" + gxv.returnErrors());
324
      }
325
    }
326 87 jones
327
  /**
328
   * Look up the document type from the database
329
   *
330
   */
331
  private String getDoctype(long docid) {
332
    // Look up the System ID of the XSL sheet
333
    PreparedStatement pstmt;
334
    String doctype = null;
335
336
    try {
337
      pstmt =
338
        conn.prepareStatement("SELECT doctype " +
339
                                "FROM xml_documents " +
340
                               "WHERE docid = ?");
341
      // Bind the values to the query
342
      pstmt.setLong(1, new Long(docid).longValue());
343
344
      pstmt.execute();
345
      try {
346
        ResultSet rs = pstmt.getResultSet();
347
        try {
348
          boolean tableHasRows = rs.next();
349
          if (tableHasRows) {
350
            try {
351
              doctype  = rs.getString(1);
352
            } catch (SQLException e) {
353
              System.out.println("Error with getString: " + e.getMessage());
354
            }
355
          }
356
        } catch (SQLException e) {
357
          System.out.println("Error with next: " + e.getMessage());
358
        }
359
      } catch (SQLException e) {
360
        System.out.println("Error with getrset: " + e.getMessage());
361
      }
362
      pstmt.close();
363
    } catch (SQLException e) {
364
      System.out.println("Error getting id: " + e.getMessage());
365
    }
366
367
    return doctype;
368
  }
369 91 higgins
370
371
  /**
372
   * Handle the document request and return the results
373
   * to the requestor - DFH
374
   */
375
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
376
      boolean error_flag = false;
377
      String error_message = "";
378
      // Get the document indicated
379
      String[] datadoc = (String[])params.get("datadoc");
380
  //    defaultdatapath = "C:\\Temp\\";    // for testing only!!!
381
   //   executescript = "test.bat";        // for testing only!!!
382
383
      // set content type and other response header fields first
384
      response.setContentType("application/octet-stream");
385
   if (defaultdatapath!=null) {
386
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) defaultdatapath=defaultdatapath+System.getProperty("file.separator");
387
      System.out.println("Path= "+defaultdatapath+datadoc[0]);
388
      if (executescript!=null) {
389
        String command = null;
390
        File scriptfile = new File(executescript);
391
        if (scriptfile.exists()) {
392
            command=executescript+" "+datadoc[0]; }  // execute script includes path
393
        else {     // look in defaultdatapath
394
                command = defaultdatapath+executescript+" "+datadoc[0];  // on Win98 one MUST include the .bat extender
395
        }
396
      System.out.println(command);
397
      try {
398
      Process proc = Runtime.getRuntime().exec(command);
399
      proc.waitFor();
400
      }
401
      catch (Exception eee) {
402
        System.out.println("Error running process!");
403
        error_flag = true;
404
        error_message = "Error running process!";}
405
      } // end executescript not null if
406
      File datafile = new File(defaultdatapath+datadoc[0]);
407
      try {
408
      FileInputStream fw = new FileInputStream(datafile);
409
      int x;
410
     while ((x = fw.read())!=-1) {
411
        out.write(x); }
412
      fw.close();
413
414
      }
415
      catch (Exception e) {
416
        System.out.println("Error in returning file\n"+e.getMessage());
417
        error_flag=true;
418
        error_message = error_message+"\nError in returning file\n"+e.getMessage();}
419
   } // end defaultdatapath not null if
420
  }
421
422
423 46 jones
}