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 91 2000-05-11 20:46:53Z higgins $'
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
      resultset.append("<?xml version=\"1.0\"?>\n");
208
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
209
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
210
      resultset.append("<resultset>\n");
211
      resultset.append("  <query>" + query + "</query>");
212
      Enumeration rootlist = nodelist.keys(); 
213
      while (rootlist.hasMoreElements()) {
214
        nodeid = ((Long)rootlist.nextElement()).longValue();
215
        resultset.append("  <docid>" + nodeid + "</docid>");
216
      }
217
      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
  }
239

    
240
  /** 
241
   * Handle the database getdocument request and return a XML document, 
242
   * possibly transformed from XML into HTML
243
   */
244
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
245
               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

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

    
254

    
255
      // Return the document in XML or HTML format
256
      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
        // Look up the document type
266
        String sourcetype = getDoctype(docid);
267

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

    
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

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

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

    
295
      // set content type and other response header fields first
296
      response.setContentType("text/xml");
297
  
298
      out.println(doctext[0]);
299
  }
300
  
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
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
314
      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

    
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
    
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
}
(17-17/20)