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 154 2000-06-14 04:43:21Z 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.*;    
43
import java.io.File;
44
import java.io.FileInputStream;
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=query -- search text values for document match<br>
53
 * doctype -- document type list returned by the query (publicID)
54
 * qformat=xml -- display resultset from query in XML<br>
55
 * qformat=html -- display resultset from query in HTML<br>
56
 * action=getdocument -- display an XML document in XML or HTML<br>
57
 * docid=34 -- display the document with the document ID number 34<br>
58
 * action=putdocument -- load an XML document into the database store<br>
59
 * doctext -- XML text ofthe document to load into the database<br>
60
 * query -- actual query text (to go with 'action=query')<br>
61
 * action=validate -- vallidate the xml contained in validatetext<br>
62
 * valtext -- XML text to be validated
63
 * action=getdatadoc -- retreive a stored datadocument
64
 * datadoc -- data document name (id)
65
 */
66
public class MetaCatServlet extends HttpServlet {
67

    
68
  private ServletConfig		config = null;
69
  private ServletContext	context = null;
70
  Connection 		conn = null;
71
  DBSimpleQuery		queryobj = null;
72
  DBReader		docreader = null;
73
  DBTransform		dbt = null;
74
  String 	user = null;
75
  String 	password = null;
76
  String 	defaultDB = null;
77
  String 	resultStyleURL = null;
78
  String 	xmlcatalogfile = null;
79
  String    defaultdatapath = null; // path to directory where data files 
80
                                    // that can be downloaded will be stored
81
  String    executescript  = null;  // script to get data file and put it 
82
                                    // in defaultdocpath dir
83
  PropertyResourceBundle options = null;
84

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

    
95
      // Get the configuration file information
96
      options = (PropertyResourceBundle)
97
          PropertyResourceBundle.getBundle("edu.ucsb.nceas.metacat.metacat");
98
      user = (String)options.handleGetObject("user");
99
      password = (String)options.handleGetObject("password");
100
      defaultDB = (String)options.handleGetObject("defaultDB");
101
      resultStyleURL = (String)options.handleGetObject("resultStyleURL");
102
      xmlcatalogfile = (String)options.handleGetObject("xmlcatalogfile");
103
      defaultdatapath = (String)options.handleGetObject("defaultdatapath");
104
      executescript = (String)options.handleGetObject("executescript");
105

    
106
      try {
107
        // Open a connection to the database
108
        conn = MetaCatUtil.openDBConnection(
109
                "oracle.jdbc.driver.OracleDriver",
110
                defaultDB, user, password);
111

    
112
        queryobj = new DBSimpleQuery(conn);
113
        docreader = new DBReader(conn);
114
        dbt = new DBTransform(conn);
115

    
116
      } catch (Exception e) {
117
        System.err.println("Error opening database connection");
118
      }
119
    } catch ( ServletException ex ) {
120
      throw ex;
121
    }
122
  }
123

    
124
  /** Handle "GET" method requests from HTTP clients */
125
  public void doGet (HttpServletRequest request, HttpServletResponse response)
126
    throws ServletException, IOException {
127

    
128
    // Process the data and send back the response
129
    handleGetOrPost(request, response);
130
  }
131

    
132
  /** Handle "POST" method requests from HTTP clients */
133
  public void doPost( HttpServletRequest request, HttpServletResponse response)
134
    throws ServletException, IOException {
135

    
136
    // Process the data and send back the response
137
    handleGetOrPost(request, response);
138
  }
139

    
140
  /**
141
   * Control servlet response depending on the action parameter specified
142
   */
143
  private void handleGetOrPost(HttpServletRequest request, 
144
    HttpServletResponse response) 
145
    throws ServletException, IOException {
146

    
147
    if (conn == null) {
148
      System.err.println("Connection to database lost.  Reopening...");
149
      try {
150
        // Open a connection to the database
151
        conn = MetaCatUtil.openDBConnection(
152
                "oracle.jdbc.driver.OracleDriver",
153
                defaultDB, user, password);
154
  
155
        queryobj = new DBSimpleQuery(conn);
156
        docreader = new DBReader(conn);
157
        dbt = new DBTransform(conn);
158
  
159
      } catch (Exception e) {
160
        System.err.println("Error opening database connection");
161
      }
162
    }
163

    
164
    // Get a handle to the output stream back to the client
165
    PrintWriter out = response.getWriter();
166
    //response.setContentType("text/html");
167
  
168
    String name = null;
169
    String[] value = null;
170
    String[] docid = new String[3];
171
    Hashtable params = new Hashtable();
172
    Enumeration paramlist = request.getParameterNames();
173
    while (paramlist.hasMoreElements()) {
174
      name = (String)paramlist.nextElement();
175
      value = request.getParameterValues(name);
176

    
177
      // Decode the docid and mouse click information
178
      if (name.endsWith(".y")) {
179
        docid[0] = name.substring(0,name.length()-2);
180
        //out.println("docid => " + docid[0]);
181
        params.put("docid", docid);
182
        name = "ypos";
183
      }
184
      if (name.endsWith(".x")) {
185
        name = "xpos";
186
      }
187

    
188
      //out.println(name + " => " + value[0]);
189
      params.put(name,value);
190
    }
191

    
192
    // Determine what type of request the user made
193
    // if the action parameter is set, use it as a default
194
    // but if the ypos param is set, calculate the action needed
195
    String action = ((String[])params.get("action"))[0];
196
    long ypos = 0;
197
    try {
198
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
199
      //out.println("<P>YPOS IS " + ypos);
200
      if (ypos <= 13) {
201
        action = "getdocument";
202
      } else if (ypos > 13 && ypos <= 27) {
203
        action = "validate";
204
      } else if (ypos > 27) {
205
        action = "transform";
206
      } else {
207
        action = "";
208
      }
209
    } catch (Exception npe) {
210
      //out.println("<P>Caught exception looking for Y value.");
211
    }
212

    
213
    if (action.equals("query")) {
214
      handleQueryAction(out, params, response);
215
    } else if (action.equals("getdocument")) {
216
      try {
217
        handleGetDocumentAction(out, params, response);
218
      } catch (ClassNotFoundException e) {
219
        out.println(e.getMessage());
220
      } catch (SQLException se) {
221
        out.println(se.getMessage());
222
      }
223
    } else if (action.equals("putdocument")) {
224
      handlePutDocumentAction(out, params, response);
225
    } else if (action.equals("validate")) {
226
      handleValidateAction(out, params, response);  
227
    } else if (action.equals("getdatadoc")) {
228
      handleGetDataDocumentAction(out, params, response);  
229
    } else {
230
      out.println("Error: action not registered.  Please report this error.");
231
    }
232

    
233
    // Close the stream to the client
234
    out.close();
235
  }
236

    
237
  /** 
238
   * Handle the database query request and return a result set, possibly
239
   * transformed from XML into HTML
240
   */
241
  private void handleQueryAction(PrintWriter out, Hashtable params, 
242
               HttpServletResponse response) {
243
      // Run the query
244
      Hashtable nodelist = null;
245
      String query = ((String[])params.get("query"))[0]; 
246
      String[] doctypeArr = (String[])params.get("doctype");
247
      String doctype = null;
248
      if (doctypeArr != null) {
249
        doctype = ((String[])params.get("doctype"))[0]; 
250
      }
251
      if (queryobj != null) {
252
        if (doctype != null) {
253
          nodelist = queryobj.findDocuments(query,doctype);
254
        } else {
255
          nodelist = queryobj.findDocuments(query);
256
        }
257
      } else {
258
        out.println("Query Object Init failed.");
259
	/*
260
        out.println(user);
261
        out.println(defaultDB);
262
        out.println(xmlcatalogfile);
263
        */
264
        return;
265
      }
266
 
267
      // Create a buffer to hold the xml result
268
      StringBuffer resultset = new StringBuffer();
269
 
270
      // Print the resulting root nodes
271
      Long nodeid;
272
      String document = null;
273
      resultset.append("<?xml version=\"1.0\"?>\n");
274
      //resultset.append("<!DOCTYPE resultset PUBLIC " +
275
      //               "\"-//NCEAS//resultset//EN\" \"resultset.dtd\">\n");
276
      resultset.append("<resultset>\n");
277
      resultset.append("  <query>" + query + "</query>");
278
      Enumeration rootlist = nodelist.keys(); 
279
      while (rootlist.hasMoreElements()) {
280
        nodeid = (Long)rootlist.nextElement();
281
        document = (String)nodelist.get(nodeid);
282
        resultset.append("  <document>" + document + "</document>");
283
      }
284
      resultset.append("</resultset>");
285

    
286
      String qformat = ((String[])params.get("qformat"))[0]; 
287
      if (qformat.equals("xml")) {
288
        // set content type and other response header fields first
289
        response.setContentType("text/xml");
290
        out.println(resultset.toString());
291
      } else if (qformat.equals("html")) {
292
        // set content type and other response header fields first
293
        response.setContentType("text/html");
294
        //out.println("Converting to HTML...");
295
        XMLDocumentFragment htmldoc = null;
296
        try {
297
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
298
          htmldoc = (new XSLProcessor()).processXSL(style, 
299
                     (Reader)(new StringReader(resultset.toString())),null);
300
          htmldoc.print(out);
301
        } catch (Exception e) {
302
          out.println("Error transforming document:\n" + e.getMessage());
303
        }
304
      }
305
  }
306

    
307
  /** 
308
   * Handle the database getdocument request and return a XML document, 
309
   * possibly transformed from XML into HTML
310
   */
311
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
312
               HttpServletResponse response) 
313
               throws ClassNotFoundException, IOException, SQLException {
314
    String docidstr = null;
315
    long docid = 0;
316
    String doc = null;
317
    try {
318
      // Find the document id number
319
      docidstr = ((String[])params.get("docid"))[0]; 
320
      docid = (new Long(docidstr)).longValue();
321

    
322
      // Get the document indicated fromthe db
323
      doc = docreader.readXMLDocument(docid);
324
    } catch (NullPointerException npe) {
325
      response.setContentType("text/html");
326
      out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
327
    }
328

    
329
      // Return the document in XML or HTML format
330
      String qformat = ((String[])params.get("qformat"))[0]; 
331
      if (qformat.equals("xml")) {
332
        // set content type and other response header fields first
333
        response.setContentType("text/xml");
334
        out.println(doc);
335
      } else if (qformat.equals("html")) {
336
        // set content type and other response header fields first
337
        response.setContentType("text/html");
338

    
339
        // Look up the document type
340
        String sourcetype = docreader.getDoctypeInfo(docid).getDoctype();
341

    
342
        // Transform the document to the new doctype
343
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
344
      }
345
  }
346

    
347
  /** 
348
   * Handle the database putdocument request and write an XML document 
349
   * to the database connection
350
   */
351
  private void handlePutDocumentAction(PrintWriter out, Hashtable params, 
352
               HttpServletResponse response) {
353

    
354
      // Get the document indicated
355
      String[] doctext = (String[])params.get("doctext");
356
      StringReader xml = new StringReader(doctext[0]);
357

    
358
      // write the document to the database
359
      try {
360
        DBWriter dbw = new DBWriter(xml, conn);
361
      } catch (SQLException e1) {
362
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
363
      }catch (IOException e2) {
364
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
365
      }catch (ClassNotFoundException e3) {
366
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
367
      }
368

    
369
      // set content type and other response header fields first
370
      response.setContentType("text/xml");
371
  
372
      out.println(doctext[0]);
373
  }
374
  
375
  /** 
376
   * Handle the validtion request and return the results 
377
   * to the requestor
378
   */
379
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
380

    
381
    // Get the document indicated
382
    String valtext = null;
383
    try {
384
      valtext = ((String[])params.get("valtext"))[0];
385
    } catch (Exception nullpe) {
386

    
387
      String docidstr = null;
388
      long docid = 0;
389
      try {
390
        // Find the document id number
391
        docidstr = ((String[])params.get("docid"))[0]; 
392
        docid = (new Long(docidstr)).longValue();
393
  
394
        // Get the document indicated fromthe db
395
        valtext = docreader.readXMLDocument(docid);
396
      } catch (NullPointerException npe) {
397
        response.setContentType("text/html");
398
        out.println("Error getting document ID: " + 
399
                     docidstr +" (" + docid + ")");
400
      }
401
    }
402

    
403
    SAXParser parser = new SAXParser();  // works for both Xerces and Oracle
404
    parser.setValidationMode(true);      // Oracle
405
    try {
406
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
407
      boolean valid = gxv.validateString(valtext);
408

    
409
      // set content type and other response header fields first
410
      response.setContentType("text/html");
411
      out.println("<html>");
412
      out.println("<head><link rel=\"stylesheet\" type=\"text/css\" " +
413
                  "href=\"/xmltodb/rowcol.css\" /></head>");
414
      out.println("<body class=\"emlbody\">");
415
  
416
      if (valid) {
417
        out.println("The input XML is VALID!");
418
      } else {
419
        out.println("The input XML is NOT VALID<br />\n<pre>\n" 
420
                    + gxv.returnErrors() + "\n</pre>\n");
421
        //response.setContentType("text/xml");
422
        //out.println(valtext);
423
      } 
424
      out.println("</body></html>");
425
    } catch (NullPointerException npe2) {
426
      // set content type and other response header fields first
427
      response.setContentType("text/html");
428
      //out.println(valtext); 
429
      out.println("Error validating document."); 
430
    }
431
  }
432

    
433
  /** 
434
   * Look up the document type from the database
435
   *
436
   * @param docid the id of the document to look up
437
   */
438
  private String OldgetDoctype(long docid) {
439
    PreparedStatement pstmt;
440
    String doctype = null;
441
 
442
    try {
443
      pstmt =
444
        conn.prepareStatement("SELECT doctype " + 
445
                                "FROM xml_documents " +
446
                               "WHERE docid = ?");
447
      // Bind the values to the query
448
      pstmt.setLong(1, new Long(docid).longValue());
449

    
450
      pstmt.execute();
451
      try {
452
        ResultSet rs = pstmt.getResultSet();
453
        try {
454
          boolean tableHasRows = rs.next();
455
          if (tableHasRows) {
456
            try {
457
              doctype  = rs.getString(1);
458
            } catch (SQLException e) {
459
              System.out.println("Error with getString: " + e.getMessage());
460
            }
461
          }
462
        } catch (SQLException e) {
463
          System.out.println("Error with next: " + e.getMessage());
464
        }
465
      } catch (SQLException e) {
466
        System.out.println("Error with getrset: " + e.getMessage());
467
      }
468
      pstmt.close();
469
    } catch (SQLException e) {
470
      System.out.println("Error getting id: " + e.getMessage());
471
    }
472

    
473
    return doctype;
474
  }
475
    
476
    
477
  /** 
478
   * Handle the document request and return the results 
479
   * to the requestor
480
   */
481
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
482
      boolean error_flag = false;
483
      String error_message = "";
484
      // Get the document indicated
485
      String[] datadoc = (String[])params.get("datadoc");
486
  //    defaultdatapath = "C:\\Temp\\";    // for testing only!!!
487
   //   executescript = "test.bat";        // for testing only!!!
488
      
489
      // set content type and other response header fields first
490
      response.setContentType("application/octet-stream");
491
   if (defaultdatapath!=null) {
492
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) defaultdatapath=defaultdatapath+System.getProperty("file.separator");
493
      System.out.println("Path= "+defaultdatapath+datadoc[0]);
494
      if (executescript!=null) {
495
        String command = null;
496
        File scriptfile = new File(executescript);
497
        if (scriptfile.exists()) {
498
            command=executescript+" "+datadoc[0]; }  // execute script includes path
499
        else {     // look in defaultdatapath
500
                command = defaultdatapath+executescript+" "+datadoc[0];  // on Win98 one MUST include the .bat extender
501
        }
502
      System.out.println(command);
503
      try {
504
      Process proc = Runtime.getRuntime().exec(command);
505
      proc.waitFor();
506
      }
507
      catch (Exception eee) {
508
        System.out.println("Error running process!");
509
        error_flag = true;
510
        error_message = "Error running process!";}
511
      } // end executescript not null if
512
      File datafile = new File(defaultdatapath+datadoc[0]);
513
      try {
514
      FileInputStream fw = new FileInputStream(datafile);
515
      int x;
516
     while ((x = fw.read())!=-1) {
517
        out.write(x); }
518
      fw.close();
519
      
520
      }
521
      catch (Exception e) {
522
        System.out.println("Error in returning file\n"+e.getMessage());
523
        error_flag=true;
524
        error_message = error_message+"\nError in returning file\n"+e.getMessage();}
525
   } // end defaultdatapath not null if
526
  }
527
    
528
    
529
}
(16-16/20)