Project

General

Profile

1
/**
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, Dan Higgins
7
 * 
8
 *     Version: '$Id: MetaCatServlet.java 100 2000-05-15 05:44:43Z jones $'
9
 */
10

    
11
package edu.ucsb.nceas.metacat;
12

    
13
import java.io.PrintWriter;
14
import java.io.IOException;
15
import java.io.Reader;
16
import java.io.StringReader;
17
import java.io.BufferedReader;
18
import java.util.Enumeration;
19
import java.util.Hashtable;
20
import java.util.ResourceBundle;
21
import java.util.PropertyResourceBundle;
22
import java.net.URL;
23
import java.net.MalformedURLException;
24
import java.sql.PreparedStatement;
25
import java.sql.ResultSet;
26
import java.sql.Connection;
27
import java.sql.SQLException;
28

    
29
import javax.servlet.ServletConfig;
30
import javax.servlet.ServletContext;
31
import javax.servlet.ServletException;
32
import javax.servlet.ServletInputStream;
33
import javax.servlet.http.HttpServlet;
34
import javax.servlet.http.HttpServletRequest;
35
import javax.servlet.http.HttpServletResponse;
36
import javax.servlet.http.HttpUtils;
37

    
38
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
import oracle.xml.parser.v2.*;    //Oracle parser - DFH
43
import java.io.File;  //DFH
44
import java.io.FileInputStream; //DFH
45

    
46
/**
47
 * A metadata catalog server implemented as a Java Servlet
48
   *
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
   * action=putdocument -- load an XML document into the database store<br>
58
   * doctext -- XML text ofthe document to load into the database<br>
59
   * 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
   * action=getdatadoc -- retreive a stored datadocument  //DFH
63
   * datadoc -- data document name (id)                   //DFH
64
 */
65
public class MetaCatServlet extends HttpServlet {
66

    
67
  private ServletConfig		config = null;
68
  private ServletContext	context = null;
69
  Connection 		conn = null;
70
  DBSimpleQuery		queryobj = null;
71
  DBReader		docreader = null;
72
  DBTransform		dbt = null;
73
  String 	user = null;
74
  String 	password = null;
75
  String 	defaultDB = null;
76
  String 	resultStyleURL = null;
77
  String 	xmlcatalogfile = null;
78
  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
  PropertyResourceBundle options = null;
81

    
82
  /**
83
   * Initialize the servlet by creating appropriate database connections
84
   */
85
  public void init( ServletConfig config ) throws ServletException {
86
    try {
87
      super.init( config );
88
      this.config = config;
89
      this.context = config.getServletContext();
90
      System.out.println("Servlet Initialize");
91

    
92
      // Get the configuration file information
93
      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
      xmlcatalogfile = (String)options.handleGetObject("xmlcatalogfile");
99
      defaultdatapath = (String)options.handleGetObject("defaultdatapath");
100
      executescript = (String)options.handleGetObject("executescript");
101

    
102
      try {
103
        // Open a connection to the database
104
        conn = MetaCatUtil.openDBConnection(
105
                "oracle.jdbc.driver.OracleDriver",
106
                defaultDB, user, password);
107

    
108
        queryobj = new DBSimpleQuery(conn);
109
        docreader = new DBReader(conn);
110
        dbt = new DBTransform(conn);
111

    
112
      } catch (Exception e) {
113
        System.err.println("Error opening database connection");
114
      }
115
    } catch ( ServletException ex ) {
116
      throw ex;
117
    }
118
  }
119

    
120
  /** Handle "GET" method requests from HTTP clients */
121
  public void doGet (HttpServletRequest request, HttpServletResponse response)
122
    throws ServletException, IOException {
123

    
124
    // Process the data and send back the response
125
    handleGetOrPost(request, response);
126
  }
127

    
128
  /** Handle "POST" method requests from HTTP clients */
129
  public void doPost( HttpServletRequest request, HttpServletResponse response)
130
    throws ServletException, IOException {
131

    
132
    // Process the data and send back the response
133
    handleGetOrPost(request, response);
134
  }
135

    
136
  /**
137
   * Control servlet response depending on the action parameter specified
138
   */
139
  private void handleGetOrPost(HttpServletRequest request, 
140
    HttpServletResponse response) 
141
    throws ServletException, IOException {
142

    
143
    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
    // Get a handle to the output stream back to the client
161
    PrintWriter out = response.getWriter();
162
  
163
    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
    String action = ((String[])params.get("action"))[0];
174

    
175
    if (action.equals("query")) {
176
      handleQueryAction(out, params, response);
177
    } else if (action.equals("getdocument")) {
178
      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
    } else if (action.equals("putdocument")) {
186
      handlePutDocumentAction(out, params, response);
187
    } else if (action.equals("validate")) {
188
      handleValidateAction(out, params, response);  
189
    } else if (action.equals("getdatadoc")) {
190
      handleGetDataDocumentAction(out, params, response);  
191
    } else {
192
      out.println("Error: action not registered.  Please report this error.");
193
    }
194

    
195
    // Close the stream to the client
196
    out.close();
197
  }
198

    
199
  /** 
200
   * Handle the database query request and return a result set, possibly
201
   * transformed from XML into HTML
202
   */
203
  private void handleQueryAction(PrintWriter out, Hashtable params, 
204
               HttpServletResponse response) {
205
      // Run the query
206
      Hashtable nodelist = null;
207
      String query = ((String[])params.get("query"))[0]; 
208
      if (queryobj != null) {
209
        nodelist = queryobj.findDocuments(query);
210
      } else {
211
        out.println("Query Object Init failed.");
212
	/*
213
        out.println(user);
214
        out.println(defaultDB);
215
        out.println(xmlcatalogfile);
216
        */
217
        return;
218
      }
219
 
220
      // Create a buffer to hold the xml result
221
      StringBuffer resultset = new StringBuffer();
222
 
223
      // Print the resulting root nodes
224
      Long nodeid;
225
      String document = null;
226
      resultset.append("<?xml version=\"1.0\"?>\n");
227
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
228
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
229
      resultset.append("<resultset>\n");
230
      resultset.append("  <query>" + query + "</query>");
231
      Enumeration rootlist = nodelist.keys(); 
232
      while (rootlist.hasMoreElements()) {
233
        nodeid = (Long)rootlist.nextElement();
234
        document = (String)nodelist.get(nodeid);
235
        resultset.append("  <document>" + document + "</document>");
236
      }
237
      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
  }
259

    
260
  /** 
261
   * Handle the database getdocument request and return a XML document, 
262
   * possibly transformed from XML into HTML
263
   */
264
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
265
               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

    
271
      // Get the document indicated fromthe db
272
      String doc = docreader.readXMLDocument(docid);
273

    
274

    
275
      // Return the document in XML or HTML format
276
      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
        // Look up the document type
286
        String sourcetype = getDoctype(docid);
287

    
288
        // Transform the document to the new doctype
289
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
290
      }
291
  }
292

    
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

    
300
      // Get the document indicated
301
      String[] doctext = (String[])params.get("doctext");
302
      StringReader xml = new StringReader(doctext[0]);
303

    
304
      // write the document to the database
305
      try {
306
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
307
      } catch (SQLException e1) {
308
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
309
      }catch (IOException e2) {
310
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
311
      }catch (ClassNotFoundException e3) {
312
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
313
      }
314

    
315
      // set content type and other response header fields first
316
      response.setContentType("text/xml");
317
  
318
      out.println(doctext[0]);
319
  }
320
  
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
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
334
      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

    
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
    
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
}
(16-16/30)