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 103 2000-05-20 00:07:52Z 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
    //response.setContentType("text/html");
163
  
164
    String name = null;
165
    String[] value = null;
166
    String[] docid = new String[3];
167
    Hashtable params = new Hashtable();
168
    Enumeration paramlist = request.getParameterNames();
169
    while (paramlist.hasMoreElements()) {
170
      name = (String)paramlist.nextElement();
171
      value = request.getParameterValues(name);
172

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

    
184
      //out.println(name + " => " + value[0]);
185
      params.put(name,value);
186
    }
187

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

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

    
229
    // Close the stream to the client
230
    out.close();
231
  }
232

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

    
273
      String qformat = ((String[])params.get("qformat"))[0]; 
274
      if (qformat.equals("xml")) {
275
        // set content type and other response header fields first
276
        response.setContentType("text/xml");
277
        out.println(resultset.toString());
278
      } else if (qformat.equals("html")) {
279
        // set content type and other response header fields first
280
        response.setContentType("text/html");
281
        //out.println("Converting to HTML...");
282
        XMLDocumentFragment htmldoc = null;
283
        try {
284
          XSLStylesheet style = new XSLStylesheet(new URL(resultStyleURL), null);
285
          htmldoc = (new XSLProcessor()).processXSL(style, 
286
                     (Reader)(new StringReader(resultset.toString())),null);
287
          htmldoc.print(out);
288
        } catch (Exception e) {
289
          out.println("Error transforming document:\n" + e.getMessage());
290
        }
291
      }
292
  }
293

    
294
  /** 
295
   * Handle the database getdocument request and return a XML document, 
296
   * possibly transformed from XML into HTML
297
   */
298
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
299
               HttpServletResponse response) 
300
               throws ClassNotFoundException, IOException, SQLException {
301
    String docidstr = null;
302
    long docid = 0;
303
    String doc = null;
304
    try {
305
      // Find the document id number
306
      docidstr = ((String[])params.get("docid"))[0]; 
307
      docid = (new Long(docidstr)).longValue();
308

    
309
      // Get the document indicated fromthe db
310
      doc = docreader.readXMLDocument(docid);
311
    } catch (NullPointerException npe) {
312
      response.setContentType("text/html");
313
      out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
314
    }
315

    
316
      // Return the document in XML or HTML format
317
      String qformat = ((String[])params.get("qformat"))[0]; 
318
      if (qformat.equals("xml")) {
319
        // set content type and other response header fields first
320
        response.setContentType("text/xml");
321
        out.println(doc);
322
      } else if (qformat.equals("html")) {
323
        // set content type and other response header fields first
324
        response.setContentType("text/html");
325

    
326
        // Look up the document type
327
        String sourcetype = docreader.getDoctypeInfo(docid).getDoctype();
328

    
329
        // Transform the document to the new doctype
330
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
331
      }
332
  }
333

    
334
  /** 
335
   * Handle the database putdocument request and write an XML document 
336
   * to the database connection
337
   */
338
  private void handlePutDocumentAction(PrintWriter out, Hashtable params, 
339
               HttpServletResponse response) {
340

    
341
      // Get the document indicated
342
      String[] doctext = (String[])params.get("doctext");
343
      StringReader xml = new StringReader(doctext[0]);
344

    
345
      // write the document to the database
346
      try {
347
        DBSAXWriter dbw = new DBSAXWriter(xml, conn);
348
      } catch (SQLException e1) {
349
          out.println("Error 1 loading document:<p>\n" + e1.getMessage());
350
      }catch (IOException e2) {
351
          out.println("Error 2 loading document:<p>\n" + e2.getMessage());
352
      }catch (ClassNotFoundException e3) {
353
          out.println("Error 3 loading document:<p>\n" + e3.getMessage());
354
      }
355

    
356
      // set content type and other response header fields first
357
      response.setContentType("text/xml");
358
  
359
      out.println(doctext[0]);
360
  }
361
  
362
  /** 
363
   * Handle the validtion request and return the results 
364
   * to the requestor - DFH
365
   */
366
  private void handleValidateAction(PrintWriter out, Hashtable params, HttpServletResponse response) {
367

    
368
    // Get the document indicated
369
    String valtext = null;
370
    try {
371
      valtext = ((String[])params.get("valtext"))[0];
372
    } catch (Exception nullpe) {
373

    
374
      String docidstr = null;
375
      long docid = 0;
376
      try {
377
        // Find the document id number
378
        docidstr = ((String[])params.get("docid"))[0]; 
379
        docid = (new Long(docidstr)).longValue();
380
  
381
        // Get the document indicated fromthe db
382
        valtext = docreader.readXMLDocument(docid);
383
      } catch (NullPointerException npe) {
384
        response.setContentType("text/html");
385
        out.println("Error getting document ID: " + 
386
                     docidstr +" (" + docid + ")");
387
      }
388
    }
389

    
390
    SAXParser parser = new SAXParser();  // works for both Xerces and Oracle
391
    parser.setValidationMode(true);      // Oracle
392
    try {
393
      GenericXMLValidate gxv = new GenericXMLValidate(parser, xmlcatalogfile);
394
      boolean valid = gxv.validateString(valtext);
395

    
396
      // set content type and other response header fields first
397
      response.setContentType("text/plain");
398
  
399
      if (valid) {
400
        out.println("The input XML is VALID!");
401
      } else {
402
        out.println("The input XML is NOT VALID\n" + gxv.returnErrors());
403
        //response.setContentType("text/xml");
404
        //out.println(valtext);
405
      } 
406
    } catch (NullPointerException npe2) {
407
      // set content type and other response header fields first
408
      response.setContentType("text/html");
409
      //out.println(valtext); 
410
      out.println("Error validating document."); 
411
    }
412
  }
413

    
414
  /** 
415
   * Look up the document type from the database
416
   *
417
   * @param docid the id of the document to look up
418
   */
419
  private String OldgetDoctype(long docid) {
420
    PreparedStatement pstmt;
421
    String doctype = null;
422
 
423
    try {
424
      pstmt =
425
        conn.prepareStatement("SELECT doctype " + 
426
                                "FROM xml_documents " +
427
                               "WHERE docid = ?");
428
      // Bind the values to the query
429
      pstmt.setLong(1, new Long(docid).longValue());
430

    
431
      pstmt.execute();
432
      try {
433
        ResultSet rs = pstmt.getResultSet();
434
        try {
435
          boolean tableHasRows = rs.next();
436
          if (tableHasRows) {
437
            try {
438
              doctype  = rs.getString(1);
439
            } catch (SQLException e) {
440
              System.out.println("Error with getString: " + e.getMessage());
441
            }
442
          }
443
        } catch (SQLException e) {
444
          System.out.println("Error with next: " + e.getMessage());
445
        }
446
      } catch (SQLException e) {
447
        System.out.println("Error with getrset: " + e.getMessage());
448
      }
449
      pstmt.close();
450
    } catch (SQLException e) {
451
      System.out.println("Error getting id: " + e.getMessage());
452
    }
453

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