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 98 2000-05-13 01:29:51Z 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
      }
114
    } catch ( ServletException ex ) {
115
      throw ex;
116
    }
117
  }
118

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

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

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

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

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

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

    
157
    if (action.equals("query")) {
158
      handleQueryAction(out, params, response);
159
    } else if (action.equals("getdocument")) {
160
      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
    } else if (action.equals("putdocument")) {
168
      handlePutDocumentAction(out, params, response);
169
    } else if (action.equals("validate")) {
170
      handleValidateAction(out, params, response);  
171
    } else if (action.equals("getdatadoc")) {
172
      handleGetDataDocumentAction(out, params, response);  
173
    } else {
174
      out.println("Error: action not registered.  Please report this error.");
175
    }
176

    
177
    // Close the stream to the client
178
    out.close();
179
  }
180

    
181
  /** 
182
   * Handle the database query request and return a result set, possibly
183
   * transformed from XML into HTML
184
   */
185
  private void handleQueryAction(PrintWriter out, Hashtable params, 
186
               HttpServletResponse response) {
187
      // Run the query
188
      Hashtable nodelist = null;
189
      String query = ((String[])params.get("query"))[0]; 
190
      if (queryobj != null) {
191
        nodelist = queryobj.findDocuments(query);
192
      } else {
193
        out.println("Query Object Init failed.");
194
	/*
195
        out.println(user);
196
        out.println(defaultDB);
197
        out.println(xmlcatalogfile);
198
        */
199
        return;
200
      }
201
 
202
      // Create a buffer to hold the xml result
203
      StringBuffer resultset = new StringBuffer();
204
 
205
      // Print the resulting root nodes
206
      Long nodeid;
207
      String document = null;
208
      resultset.append("<?xml version=\"1.0\"?>\n");
209
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
210
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
211
      resultset.append("<resultset>\n");
212
      resultset.append("  <query>" + query + "</query>");
213
      Enumeration rootlist = nodelist.keys(); 
214
      while (rootlist.hasMoreElements()) {
215
        nodeid = (Long)rootlist.nextElement();
216
        document = (String)nodelist.get(nodeid);
217
        resultset.append("  <document>" + document + "</document>");
218
      }
219
      resultset.append("</resultset>");
220

    
221
      String qformat = ((String[])params.get("qformat"))[0]; 
222
      if (qformat.equals("xml")) {
223
        // set content type and other response header fields first
224
        response.setContentType("text/xml");
225
        out.println(resultset.toString());
226
      } else if (qformat.equals("html")) {
227
        // set content type and other response header fields first
228
        response.setContentType("text/html");
229
        //out.println("Converting to HTML...");
230
        XMLDocumentFragment htmldoc = null;
231
        try {
232
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
233
          htmldoc = (new XSLProcessor()).processXSL(style, 
234
                     (Reader)(new StringReader(resultset.toString())),null);
235
          htmldoc.print(out);
236
        } catch (Exception e) {
237
          out.println("Error transforming document:\n" + e.getMessage());
238
        }
239
      }
240
  }
241

    
242
  /** 
243
   * Handle the database getdocument request and return a XML document, 
244
   * possibly transformed from XML into HTML
245
   */
246
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
247
               HttpServletResponse response) 
248
               throws ClassNotFoundException, IOException, SQLException {
249
      // Find the document id number
250
      String docidstr = ((String[])params.get("docid"))[0]; 
251
      long docid = (new Long(docidstr)).longValue();
252

    
253
      // Get the document indicated fromthe db
254
      String doc = docreader.readXMLDocument(docid);
255

    
256

    
257
      // Return the document in XML or HTML format
258
      String qformat = ((String[])params.get("qformat"))[0]; 
259
      if (qformat.equals("xml")) {
260
        // set content type and other response header fields first
261
        response.setContentType("text/xml");
262
        out.println(doc);
263
      } else if (qformat.equals("html")) {
264
        // set content type and other response header fields first
265
        response.setContentType("text/html");
266

    
267
        // Look up the document type
268
        String sourcetype = getDoctype(docid);
269

    
270
        // Transform the document to the new doctype
271
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
272
      }
273
  }
274

    
275
  /** 
276
   * Handle the database putdocument request and write an XML document 
277
   * to the database connection
278
   */
279
  private void handlePutDocumentAction(PrintWriter out, Hashtable params, 
280
               HttpServletResponse response) {
281

    
282
      // Get the document indicated
283
      String[] doctext = (String[])params.get("doctext");
284
      StringReader xml = new StringReader(doctext[0]);
285

    
286
      // write the document to the database
287
      try {
288
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
289
      } catch (SQLException e1) {
290
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
291
      }catch (IOException e2) {
292
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
293
      }catch (ClassNotFoundException e3) {
294
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
295
      }
296

    
297
      // set content type and other response header fields first
298
      response.setContentType("text/xml");
299
  
300
      out.println(doctext[0]);
301
  }
302
  
303
  /** 
304
   * Handle the validtion request and return the results 
305
   * to the requestor - DFH
306
   */
307
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
308

    
309
      // Get the document indicated
310
      String[] valtext = (String[])params.get("valtext");
311

    
312

    
313
      SAXParser parser = new SAXParser();           // works for both Xerces and Oracle
314
      parser.setValidationMode(true);               // Oracle
315
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
316
      boolean valid = gxv.validateString(valtext[0]);
317

    
318
      // set content type and other response header fields first
319
      response.setContentType("text/plain");
320
  
321
      if (valid) {
322
        out.println("The input XML is VALID!");
323
      }
324
      else {
325
        out.println("The input XML is NOT VALID\n" + gxv.returnErrors());
326
      } 
327
    }
328

    
329
  /** 
330
   * Look up the document type from the database
331
   *
332
   */
333
  private String getDoctype(long docid) {
334
    // Look up the System ID of the XSL sheet
335
    PreparedStatement pstmt;
336
    String doctype = null;
337
 
338
    try {
339
      pstmt =
340
        conn.prepareStatement("SELECT doctype " + 
341
                                "FROM xml_documents " +
342
                               "WHERE docid = ?");
343
      // Bind the values to the query
344
      pstmt.setLong(1, new Long(docid).longValue());
345

    
346
      pstmt.execute();
347
      try {
348
        ResultSet rs = pstmt.getResultSet();
349
        try {
350
          boolean tableHasRows = rs.next();
351
          if (tableHasRows) {
352
            try {
353
              doctype  = rs.getString(1);
354
            } catch (SQLException e) {
355
              System.out.println("Error with getString: " + e.getMessage());
356
            }
357
          }
358
        } catch (SQLException e) {
359
          System.out.println("Error with next: " + e.getMessage());
360
        }
361
      } catch (SQLException e) {
362
        System.out.println("Error with getrset: " + e.getMessage());
363
      }
364
      pstmt.close();
365
    } catch (SQLException e) {
366
      System.out.println("Error getting id: " + e.getMessage());
367
    }
368

    
369
    return doctype;
370
  }
371
    
372
    
373
  /** 
374
   * Handle the document request and return the results 
375
   * to the requestor - DFH
376
   */
377
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
378
      boolean error_flag = false;
379
      String error_message = "";
380
      // Get the document indicated
381
      String[] datadoc = (String[])params.get("datadoc");
382
  //    defaultdatapath = "C:\\Temp\\";    // for testing only!!!
383
   //   executescript = "test.bat";        // for testing only!!!
384
      
385
      // set content type and other response header fields first
386
      response.setContentType("application/octet-stream");
387
   if (defaultdatapath!=null) {
388
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) defaultdatapath=defaultdatapath+System.getProperty("file.separator");
389
      System.out.println("Path= "+defaultdatapath+datadoc[0]);
390
      if (executescript!=null) {
391
        String command = null;
392
        File scriptfile = new File(executescript);
393
        if (scriptfile.exists()) {
394
            command=executescript+" "+datadoc[0]; }  // execute script includes path
395
        else {     // look in defaultdatapath
396
                command = defaultdatapath+executescript+" "+datadoc[0];  // on Win98 one MUST include the .bat extender
397
        }
398
      System.out.println(command);
399
      try {
400
      Process proc = Runtime.getRuntime().exec(command);
401
      proc.waitFor();
402
      }
403
      catch (Exception eee) {
404
        System.out.println("Error running process!");
405
        error_flag = true;
406
        error_message = "Error running process!";}
407
      } // end executescript not null if
408
      File datafile = new File(defaultdatapath+datadoc[0]);
409
      try {
410
      FileInputStream fw = new FileInputStream(datafile);
411
      int x;
412
     while ((x = fw.read())!=-1) {
413
        out.write(x); }
414
      fw.close();
415
      
416
      }
417
      catch (Exception e) {
418
        System.out.println("Error in returning file\n"+e.getMessage());
419
        error_flag=true;
420
        error_message = error_message+"\nError in returning file\n"+e.getMessage();}
421
   } // end defaultdatapath not null if
422
  }
423
    
424
    
425
}
(16-16/30)