Project

General

Profile

1
/**
2
 *  '$RCSfile$'
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, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: berkley $'
10
 *     '$Date: 2000-08-18 15:41:37 -0700 (Fri, 18 Aug 2000) $'
11
 * '$Revision: 384 $'
12
 */
13

    
14
package edu.ucsb.nceas.metacat;
15

    
16
import java.io.PrintWriter;
17
import java.io.IOException;
18
import java.io.Reader;
19
import java.io.StringReader;
20
import java.io.BufferedReader;
21
import java.io.File;
22
import java.io.FileInputStream;
23
import java.util.Enumeration;
24
import java.util.Hashtable;
25
import java.util.ResourceBundle; 
26
import java.util.PropertyResourceBundle;
27
import java.net.URL;
28
import java.net.MalformedURLException;
29
import java.sql.PreparedStatement;
30
import java.sql.ResultSet;
31
import java.sql.Connection;
32
import java.sql.SQLException;
33
import java.lang.reflect.*;
34

    
35
import javax.servlet.ServletConfig;
36
import javax.servlet.ServletContext;
37
import javax.servlet.ServletException;
38
import javax.servlet.ServletInputStream;
39
import javax.servlet.http.HttpServlet;
40
import javax.servlet.http.HttpServletRequest;
41
import javax.servlet.http.HttpServletResponse;
42
import javax.servlet.http.HttpSession;
43
import javax.servlet.http.HttpUtils;
44

    
45
import oracle.xml.parser.v2.XSLStylesheet;
46
import oracle.xml.parser.v2.XSLException;
47
import oracle.xml.parser.v2.XMLDocumentFragment;
48
import oracle.xml.parser.v2.XSLProcessor;
49

    
50
import org.xml.sax.SAXException;
51

    
52
/**
53
 * A metadata catalog server implemented as a Java Servlet
54
 *
55
 * <p>Valid parameters are:<br>
56
 * action=query -- query the values of all elements and attributes
57
 *                     and return a result set of nodes<br>
58
 * action=squery -- structured query (see pathquery.dtd)<br>
59
 * action=insert -- insert an XML document into the database store<br>
60
 * action=update -- update an XML document that is in the database store<br>
61
 * action=delete --  delete an XML document from the database store<br>
62
 * action=validate -- vallidate the xml contained in valtext<br>
63
 * action=getdocument -- display an XML document in XML or HTML<br>
64
 * doctype -- document type list returned by the query (publicID)<br>
65
 * qformat=xml -- display resultset from query in XML<br>
66
 * qformat=html -- display resultset from query in HTML<br>
67
 * docid=34 -- display the document with the document ID number 34<br>
68
 * doctext -- XML text of the document to load into the database<br>
69
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
70
 * valtext -- XML text to be validated<br>
71
 * action=getdatadoc -- retreive a stored datadocument<br>
72
 * action=getdoctypes -- retreive all doctypes (publicID)<br>
73
 * action=getdataguide -- retreive a Data Guide<br>
74
 * datadoc -- data document name (id)<br>
75
 * <p>
76
 * The particular combination of parameters that are valid for each 
77
 * particular action value is quite specific.  This documentation
78
 * will be reorganized to reflect this information.
79
 */
80
public class MetaCatServlet extends HttpServlet {
81

    
82
  private ServletConfig config = null;
83
  private ServletContext context = null;
84
  private Hashtable connectionPool = new Hashtable();
85
  private String resultStyleURL = null;
86
  private String xmlcatalogfile = null;
87
  private String saxparser = null;
88
  private String defaultdatapath = null; 
89
  private String servletpath = null; 
90
  private PropertyResourceBundle options = null;
91
  private MetaCatUtil util = null;
92

    
93
  // path to directory where data files 
94
  // that can be downloaded will be stored
95
  private String htmlpath = null; 
96
  // script to get data file and put it 
97
  // in defaultdocpath dir
98
  private String executescript  = null;  
99

    
100

    
101
  /**
102
   * Initialize the servlet by creating appropriate database connections
103
   */
104
  public void init( ServletConfig config ) throws ServletException {
105
    try {
106
      super.init( config );
107
      this.config = config;
108
      this.context = config.getServletContext(); 
109
      System.out.println("MetaCatServlet Initialize");
110

    
111
      util = new MetaCatUtil();
112

    
113
      // Get the configuration file information
114
      resultStyleURL = util.getOption("resultStyleURL");
115
      xmlcatalogfile = util.getOption("xmlcatalogfile");
116
      saxparser = util.getOption("saxparser");
117
      defaultdatapath = util.getOption("defaultdatapath");
118
      executescript = util.getOption("executescript");
119
      servletpath = util.getOption("servletpath");
120
      htmlpath = util.getOption("htmlpath");
121

    
122
      try {
123
        // Open a pool of db connections
124
        connectionPool = util.getConnectionPool();
125
      } catch (Exception e) {
126
        System.err.println("Error creating pool of database connections");
127
        System.err.println(e.getMessage());
128
      }
129
    } catch ( ServletException ex ) {
130
      throw ex;
131
    }
132
  }
133

    
134
  /**
135
   * Close all db connections from the pool
136
   */
137
  public void destroy() {
138
    
139
    if (util != null) {
140
        util.closeConnections();
141
    }
142
  }
143

    
144
  /** Handle "GET" method requests from HTTP clients */
145
  public void doGet (HttpServletRequest request, HttpServletResponse response)
146
    throws ServletException, IOException {
147

    
148
    // Process the data and send back the response
149
    handleGetOrPost(request, response);
150
  }
151

    
152
  /** Handle "POST" method requests from HTTP clients */
153
  public void doPost( HttpServletRequest request, HttpServletResponse response)
154
    throws ServletException, IOException {
155

    
156
    // Process the data and send back the response
157
    handleGetOrPost(request, response);
158
  }
159

    
160
  /**
161
   * Control servlet response depending on the action parameter specified
162
   */
163
  private void handleGetOrPost(HttpServletRequest request, 
164
    HttpServletResponse response) 
165
    throws ServletException, IOException 
166
 {
167

    
168
    if ( util == null ) {
169
        util = new MetaCatUtil(); 
170
    }
171
    if ( connectionPool == null ) {
172
      try {
173
        // Open a pool of db connections
174
        connectionPool = util.getConnectionPool();
175
      } catch (Exception e) {
176
        System.err.println("Error creating pool of database connections");
177
        System.err.println(e.getMessage());
178
      }
179
    }    
180
    // Get a handle to the output stream back to the client
181
    PrintWriter out = response.getWriter();
182
    //response.setContentType("text/html");
183
  
184
    String name = null;
185
    String[] value = null;
186
    String[] docid = new String[3];
187
    Hashtable params = new Hashtable();
188
    Enumeration paramlist = request.getParameterNames();
189
    while (paramlist.hasMoreElements()) {
190
      name = (String)paramlist.nextElement();
191
      value = request.getParameterValues(name);
192

    
193
      // Decode the docid and mouse click information
194
      if (name.endsWith(".y")) {
195
        docid[0] = name.substring(0,name.length()-2);
196
        //out.println("docid => " + docid[0]);
197
        params.put("docid", docid);
198
        name = "ypos";
199
      }
200
      if (name.endsWith(".x")) {
201
        name = "xpos";
202
      } 
203

    
204
      //out.println(name + " => " + value[0]);
205
      params.put(name,value); 
206
    }  
207
    
208
    //if the user clicked on the input images, decode which image
209
    //was clicked then set the action.
210
    String action = decodeMouseAction(params);
211
    if(action.equals("error"))
212
    {
213
      action = ((String[])params.get("action"))[0];  
214
    }
215
    
216
    // This block handles session management for the servlet
217
    // by looking up the current session information for all actions
218
    // other than "Login" and "Logout"
219
    // handle login action
220
    if (action.equals("Login") || action.equals("Login Client")) {
221
      handleLoginAction(out, params, request, response);
222
    // handle logout action  
223
    } else if (action.equals("Logout") || action.equals("Logout Client")) {
224
      HttpSession sess = request.getSession(false);
225
      if (sess != null) { sess.invalidate();  }    
226
      if (action.equals("Logout Client")) {
227
        out.println("<?xml version=\"1.0\"?>");
228
        out.println("<success>");
229
        out.println("User logout.");
230
        out.println("</success>");
231
        return;
232
      }    
233

    
234
      response.sendRedirect(htmlpath + "/index.html"); 
235

    
236
    // aware of session expiration on every request  
237
    } else {   
238
      HttpSession sess = request.getSession(true);
239
      if (sess.isNew()) { 
240
        // session expired or has not been stored b/w user requests
241
        // redirect to default page for query only access
242

    
243
      //  response.sendRedirect(htmlpath + "/sexpire.html");
244

    
245
      } 
246
    }    
247

    
248
    // Now that we know the session is valid, we can delegate the request
249
    // to a particular action handler
250
    if(action.equals("query"))
251
    {
252
      handleQuery(out, params, response); 
253
    } 
254
    else if(action.equals("squery"))
255
    {
256
      if(params.containsKey("query"))
257
      {
258
        handleSQuery(out, params, response); 
259
        //handleSQuery(((String[])params.get("query"))[0]);
260
      }
261
      else
262
      {
263
        out.println("Illegal action squery without \"query\" parameter");
264
      }
265
    }
266
    else if (action.equals("getdocument")) {
267
      try {
268
        handleGetDocumentAction(out, params, response);
269
      } catch (ClassNotFoundException e) {
270
        out.println(e.getMessage());
271
      } catch (SQLException se) {
272
        out.println(se.getMessage());
273
      }
274
    } else if (action.equals("insert") || action.equals("update")) {
275
      handleInsertOrUpdateAction(out, params, response);
276
    } else if (action.equals("delete")) {
277
      handleDeleteAction(out, params, response);
278
    } else if (action.equals("validate")) {
279
      handleValidateAction(out, params, response);  
280
    } else if (action.equals("getdatadoc")) {
281
      handleGetDataDocumentAction(out, params, response);  
282
    } else if (action.equals("getdoctypes")) {
283
      handleGetDoctypesAction(out, params, response);  
284
    } else if (action.equals("getdataguide")) {
285
      handleGetDataGuideAction(out, params, response);  
286
    } else if (action.equals("Login") || action.equals("Login Client")) {
287
    } else {
288
      out.println("Error: action not registered.  Please report this error.");
289
    }
290

    
291
    // Close the stream to the client
292
    out.close();
293
  }
294
  
295
  /**
296
   * decodes the mouse click information coming from the client.
297
   * This function may be overwritten to provide specific functionality
298
   * for different applications.
299
   * @param params the parameters from the CGI
300
   * @return action the action to be performed or "error" if an error was
301
   * generated
302
   */
303
  protected String decodeMouseAction(Hashtable params)
304
  {
305
    // Determine what type of request the user made
306
    // if the action parameter is set, use it as a default
307
    // but if the ypos param is set, calculate the action needed
308
    String action=null;
309
    long ypos = 0;
310
    try {
311
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
312
      //out.println("<P>YPOS IS " + ypos);
313
      if (ypos <= 13) {
314
        action = "getdocument";
315
      } else if (ypos > 13 && ypos <= 27) {
316
        action = "validate";
317
      } else if (ypos > 27) {
318
        action = "transform";
319
      }
320
      return action;
321
    } catch (Exception npe) {
322
      //
323
      // MBJ -- NOTE that this should be handled more gracefully with
324
      //        the new exception infrastructure -- this "error" return
325
      //        value is inappropriate
326
      //out.println("<P>Caught exception looking for Y value.");
327
      return "error";
328
    }  
329
  }
330

    
331
  /** 
332
   * Handle the Login request. Create a new session object.
333
   * Make a user authentication through SRB RMI Connection.
334
   */
335
  private void handleLoginAction(PrintWriter out, Hashtable params, 
336
               HttpServletRequest request, HttpServletResponse response) {
337

    
338
    MetaCatSession sess = null;
339
    String un = ((String[])params.get("username"))[0];
340
    String pw = ((String[])params.get("password"))[0];
341
    String action = ((String[])params.get("action"))[0];
342
    
343
    try {
344
        sess = new MetaCatSession(request, un, pw);
345
    } catch (Exception e) {
346
      out.println(e.getMessage());
347
    }
348

    
349
    if ( un.equals("anonymous") ) {
350
            try {
351
                if (action.equals("Login Client")) {
352
                    out.println("<?xml version=\"1.0\"?>");
353
                    out.println("<success>");
354
                    out.println("User Authentication successful.");
355
                    out.println("</success>");
356
                    return;
357
                } else {
358
                    response.sendRedirect(
359
                      response.encodeRedirectUrl(htmlpath + "/index.html"));
360
                }    
361
            } catch ( java.io.IOException ioe) {
362
                sess.disconnect();            
363
                out.println("<?xml version=\"1.0\"?>");
364
                out.println("<error>");
365
                out.println("MetaCatServlet.handleLoginAction() - " +
366
                            "Error on redirect of HttpServletResponse: " + 
367
                            ioe.getMessage());
368
                out.println("</error>");
369
                return;
370
            }                
371
    }    
372

    
373
    try { 
374
        if (sess.userAuth(un, pw)) {
375
            try {
376
                if (action.equals("Login Client")) {
377
                    out.println("<?xml version=\"1.0\"?>");
378
                    out.println("<success>");
379
                    out.println("User Authentication successful.");
380
                    out.println("</success>");
381
                } else {
382
                    response.sendRedirect(
383

    
384
                    response.encodeRedirectUrl(htmlpath + "/metacat.html"));
385
                }    
386
            } catch ( java.io.IOException ioe) {
387
                sess.disconnect();            
388
                out.println("<?xml version=\"1.0\"?>");
389
                out.println("<error>");
390
                out.println("MetaCatServlet.handleLoginAction() - " +
391
                            "Error on redirect of HttpServletResponse: " + 
392
                            ioe.getMessage());
393
                out.println("</error>");
394
            }                
395
                
396
        } else {  
397
            sess.disconnect();            
398
            out.println("<?xml version=\"1.0\"?>");
399
            out.println("<error>");
400
            out.println("SRB Connection failed. " +
401
                        "SRB RMI Server is not running now or " +
402
                        "user " + un + 
403
                        " has not been authenticated to use the system.");
404
            out.println("</error>");
405
        }    
406
    } catch ( java.rmi.RemoteException re) {
407
            sess.disconnect();            
408
            out.println("<?xml version=\"1.0\"?>");
409
            out.println("<error>");
410
            out.println("SRB Connection failed. " + re.getMessage());
411
            out.println("</error>"); 
412
    }             
413
  }    
414
  
415
  /**      
416
   * Retreive the squery xml, execute it and display it
417
   *
418
   * @param out the output stream to the client
419
   * @param params the Hashtable of parameters that should be included
420
   * in the squery.
421
   * @param response the response object linked to the client
422
   * @param conn the database connection 
423
   */
424
  protected void handleSQuery(PrintWriter out, Hashtable params, 
425
                              HttpServletResponse response)
426
  { 
427
    String xmlquery = ((String[])params.get("query"))[0];
428
    String qformat = ((String[])params.get("qformat"))[0];
429
    Hashtable doclist = runQuery(xmlquery);
430
    String resultdoc = createResultDocument(doclist, xmlquery);
431

    
432
    //format and transform the results                                        
433
    if(qformat.equals("html")) {
434
      transformResultset(resultdoc, response, out);
435
    } else if(qformat.equals("xml")) {
436
      response.setContentType("text/xml");
437
      out.println(resultdoc);
438
    } else {
439
      out.println("invalid qformat: " + qformat); 
440
    }
441
  }
442
  
443
   /**
444
    * Create the xml query, execute it and display the results.
445
    *
446
    * @param out the output stream to the client
447
    * @param params the Hashtable of parameters that should be included
448
    * in the squery.
449
    * @param response the response object linked to the client
450
    */ 
451
  protected void handleQuery(PrintWriter out, Hashtable params, 
452
                           HttpServletResponse response)
453
  {
454
    //create the query and run it
455
    String xmlquery = DBQuery.createSQuery(params);
456
    Hashtable doclist = runQuery(xmlquery);
457
    String qformat = ((String[])params.get("qformat"))[0]; 
458
    String resultdoc = createResultDocument(doclist, transformQuery(params));
459

    
460
    //format and transform the results                                        
461
    if(qformat.equals("html")) {
462
      transformResultset(resultdoc, response, out);
463
    } else if(qformat.equals("xml")) {
464
      response.setContentType("text/xml");
465
      out.println(resultdoc);
466
    } else {
467
      out.println("invalid qformat: " + qformat); 
468
    }
469
  }
470
  
471
  /**
472
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
473
   * so it can properly be placed in the <query> tag of the resultset.
474
   * This method is overwritable so that other applications can customize
475
   * the structure of what is in the <query> tag.
476
   * 
477
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
478
   */
479
  protected String transformQuery(Hashtable params)
480
  {
481
    //DBQuery.createSQuery is a re-calling of a previously called 
482
    //function but it is necessary
483
    //so that overriding methods have access to the params hashtable
484
    String xmlquery = DBQuery.createSQuery(params);
485
    //the <?xml version="1.0"?> tag is the first 22 characters of the
486
    xmlquery = xmlquery.trim();
487
    int index = xmlquery.indexOf("?>");
488
    return xmlquery.substring(index + 2, xmlquery.length());
489
  }
490
  
491
  /**
492
   * Run the query and return a hashtable of results.
493
   *
494
   * @param xmlquery the query to run
495
   */
496
  private Hashtable runQuery(String xmlquery)
497
  {
498
    Hashtable doclist=null;
499
    Connection conn = null;
500
    try
501
    {
502
        conn = util.getConnection();
503
        DBQuery queryobj = new DBQuery(conn, saxparser);
504
        doclist = queryobj.findDocuments(new StringReader(xmlquery));
505
        util.returnConnection(conn);
506
        return doclist;
507
    } 
508
    catch (Exception e) 
509
    {
510
      if (conn != null) 
511
      {
512
        util.returnConnection(conn); 
513
      }
514
      util.debugMessage("Error in runQuery: " + e.getMessage());
515
      doclist = null;
516
      return doclist;
517
    }    
518
  }
519
  
520
  /**
521
   * Transorms an xml resultset document to html and sends it to the browser
522
   *
523
   * @param resultdoc the string representation of the document that needs
524
   * to be transformed.
525
   * @param response the HttpServletResponse object bound to the client.
526
   * @param out the output stream to the client
527
   */ 
528
  protected void transformResultset(String resultdoc, 
529
                                    HttpServletResponse response,
530
                                    PrintWriter out)
531
  {
532
    Connection conn = null;
533
    try {
534
      conn = util.getConnection();
535
      DBTransform trans = new DBTransform(conn);
536
      response.setContentType("text/html");
537
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
538
                                 "-//W3C//HTML//EN", out);
539
      util.returnConnection(conn); 
540
    }
541
    catch(Exception e)
542
    {
543
      //if (conn != null) 
544
      {
545
        util.returnConnection(conn); 
546
      }
547
    } 
548
  }
549
  
550
  /**
551
   * Transforms a hashtable of documents to an xml or html result.
552
   *
553
   * @param doclist- the hashtable to transform
554
   * @param xmlquery- the query that returned the dolist result
555
   */
556
  protected String createResultDocument(Hashtable doclist, String xmlquery)
557
  {
558
    // Create a buffer to hold the xml result
559
    StringBuffer resultset = new StringBuffer();
560
 
561
    // Print the resulting root nodes 
562
    String docid = null;
563
    String document = null;
564
    resultset.append("<?xml version=\"1.0\"?>\n");
565
    resultset.append("<resultset>\n");
566

    
567
    //the following should work but it doesn't because the parser doesn't 
568
    //like the <?xml?> tag inside the <query> tag.  This is supposed to be
569
    //the way that the query itself is sent back to the client.
570
    
571
    resultset.append("  <query>" + xmlquery + "</query>");   
572
 
573
    Enumeration doclistkeys = doclist.keys(); 
574
    while (doclistkeys.hasMoreElements()) 
575
    {
576
      docid = (String)doclistkeys.nextElement();
577
      document = (String)doclist.get(docid);
578
      resultset.append("  <document>" + document + "</document>");
579
    } 
580
    resultset.append("</resultset>");
581
    return resultset.toString();
582
  }
583

    
584
  /** 
585
   * Handle the database getdocument request and return a XML document, 
586
   * possibly transformed from XML into HTML
587
   */
588
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
589
               HttpServletResponse response) 
590
               throws ClassNotFoundException, IOException, SQLException {
591
    String docidstr = null;
592
    String docid = null;
593
    String doc = null;
594
    Connection conn = null;
595
    
596
    try {
597
      // Find the document id number
598
      docidstr = ((String[])params.get("docid"))[0]; 
599
      //docid = (new Long(docidstr)).longValue();
600
      docid = docidstr;
601

    
602
      conn = util.getConnection();
603
      DBReader docreader = new DBReader(conn);
604
      DBTransform dbt = new DBTransform(conn);
605
      
606
      // Get the document indicated fromthe db
607
      doc = docreader.readXMLDocument(docid);
608

    
609
      // Return the document in XML or HTML format
610
      String qformat = ((String[])params.get("qformat"))[0]; 
611
      if (qformat.equals("xml")) {
612
        // set content type and other response header fields first
613
        response.setContentType("text/xml");
614
        out.println(doc);
615
      } else if (qformat.equals("html")) {
616

    
617
        // Look up the document type
618
        String sourcetype = docreader.getDoctypeInfo(docid).getDoctype();
619

    
620
        // Transform the document to the new doctype
621
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
622
      }
623
    } catch (McdbException e) {
624
      response.setContentType("text/xml");
625
      e.toXml(out);
626
    } catch (Throwable t) {
627
      response.setContentType("text/html");
628
      out.println(t.getMessage());
629
    } finally {
630
      util.returnConnection(conn);
631
    }    
632

    
633
  }
634

    
635
  /** 
636
   * Handle the database putdocument request and write an XML document 
637
   * to the database connection
638
   */
639
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
640
               HttpServletResponse response) {
641

    
642
    Connection conn = null;
643

    
644
    try {
645
      // Get the document indicated
646
      String[] doctext = (String[])params.get("doctext");
647
      StringReader xml = null;
648
      try {
649
        xml = new StringReader(doctext[0]);
650

    
651
        String[] action = (String[])params.get("action");
652
        String[] docid = (String[])params.get("docid");
653
        String newdocid = null;
654

    
655
        String doAction = null;
656
        if (action[0].equals("insert")) {
657
          doAction = "INSERT";
658
        } else if (action[0].equals("update")) {
659
          doAction = "UPDATE";
660
        }
661

    
662
        try {
663
            // get a connection from the pool
664
            conn = util.getConnection();
665
            // write the document to the database
666
            DBWriter dbw = new DBWriter(conn, saxparser);
667

    
668
            try {
669
                String accNumber = docid[0];
670
                if (accNumber.equals("")) {
671
                    accNumber = null;
672
                }
673
                newdocid = dbw.write(xml, doAction, accNumber);  
674
            } catch (NullPointerException npe) {
675
              newdocid = dbw.write(xml, doAction, null);
676
            }
677
        } catch (Exception e) {
678
          response.setContentType("text/html");
679
          out.println(e.getMessage());
680
        } finally {
681
          util.returnConnection(conn);
682
        }    
683

    
684
        // set content type and other response header fields first
685
        response.setContentType("text/xml");
686
        out.println("<?xml version=\"1.0\"?>");
687
        out.println("<success>");
688
        out.println("<docid>" + newdocid + "</docid>"); 
689
        out.println("</success>");
690

    
691
      } catch (NullPointerException npe) {
692
        response.setContentType("text/xml");
693
        out.println("<?xml version=\"1.0\"?>");
694
        out.println("<error>");
695
        out.println(npe.getMessage()); 
696
        out.println("</error>");
697
      }
698
    } catch (Exception e) {
699
      response.setContentType("text/xml");
700
      out.println("<?xml version=\"1.0\"?>");
701
      out.println("<error>");
702
      out.println(e.getMessage()); 
703
      if (e instanceof SAXException) {
704
        Exception e2 = ((SAXException)e).getException();
705
        out.println("<error>");
706
        out.println(e2.getMessage()); 
707
        out.println("</error>");
708
      }
709
      //e.printStackTrace(out);
710
      out.println("</error>");
711
    }
712
  }
713

    
714
  /** 
715
   * Handle the database delete request and delete an XML document 
716
   * from the database connection
717
   */
718
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
719
               HttpServletResponse response) {
720

    
721
    String[] docid = (String[])params.get("docid");
722
    Connection conn = null;
723

    
724
    // delete the document from the database
725
    try {
726
      // get a connection from the pool
727
      conn = util.getConnection();
728
      DBWriter dbw = new DBWriter(conn, saxparser);
729
                                      // NOTE -- NEED TO TEST HERE
730
                                      // FOR EXISTENCE OF PARAM
731
                                      // BEFORE ACCESSING ARRAY
732
      try { 
733
        dbw.delete(docid[0]);
734
        response.setContentType("text/xml");
735
        out.println("<?xml version=\"1.0\"?>");
736
        out.println("<success>");
737
        out.println("Document deleted."); 
738
        out.println("</success>");
739
      } catch (AccessionNumberException ane) {
740
        response.setContentType("text/xml");
741
        out.println("<?xml version=\"1.0\"?>");
742
        out.println("<error>");
743
        out.println("Error deleting document!!!");
744
        out.println(ane.getMessage()); 
745
        out.println("</error>");
746
      }
747
    } catch (Exception e) {
748
      response.setContentType("text/xml");
749
      out.println("<?xml version=\"1.0\"?>");
750
      out.println("<error>");
751
      out.println(e.getMessage()); 
752
      out.println("</error>");
753
    } finally {
754
      util.returnConnection(conn);
755
    }  
756
  }
757
  
758
  /** 
759
   * Handle the validation request and return the results to the requestor
760
   */
761
  private void handleValidateAction(PrintWriter out, Hashtable params, 
762
               HttpServletResponse response) {
763

    
764
    // Get the document indicated
765
    String valtext = null;
766
    
767
    try {
768
      valtext = ((String[])params.get("valtext"))[0];
769
    } catch (Exception nullpe) {
770

    
771
      Connection conn = null;
772
      String docid = null;
773
      try {
774
        // Find the document id number
775
        docid = ((String[])params.get("docid"))[0]; 
776

    
777
        // get a connection from the pool
778
        conn = util.getConnection();
779
        DBReader docreader = new DBReader(conn);
780
        // Get the document indicated from the db
781
        valtext = docreader.readXMLDocument(docid);
782

    
783
      } catch (NullPointerException npe) {
784
        response.setContentType("text/xml");
785
        out.println("<error>Error getting document ID: " + docid + "</error>");
786
        if ( conn != null ) { util.returnConnection(conn); }
787
        return;
788
      } catch (Exception e) {
789
        response.setContentType("text/html");
790
        out.println(e.getMessage()); 
791
      } finally {
792
        util.returnConnection(conn);
793
      }  
794
    }
795

    
796
    Connection conn = null;
797
    try {
798
      // get a connection from the pool
799
      conn = util.getConnection();
800
      DBValidate valobj = new DBValidate(saxparser,conn);
801
      boolean valid = valobj.validateString(valtext);
802

    
803
      // set content type and other response header fields first
804
      response.setContentType("text/xml");
805
      out.println(valobj.returnErrors());
806

    
807
    } catch (NullPointerException npe2) {
808
      // set content type and other response header fields first
809
      response.setContentType("text/xml");
810
      out.println("<error>Error validating document.</error>"); 
811
    } catch (Exception e) {
812
      response.setContentType("text/html");
813
      out.println(e.getMessage()); 
814
    } finally {
815
      util.returnConnection(conn);
816
    }  
817
  }
818

    
819
  /** 
820
   * Handle the document request and return the results to the requestor
821
   */
822
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, 
823
               HttpServletResponse response) {
824
      boolean error_flag = false;
825
      String error_message = "";
826
      // Get the document indicated
827
      String[] datadoc = (String[])params.get("datadoc");
828
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
829
      // executescript = "test.bat";        // for testing only!!!
830
      
831
      // set content type and other response header fields first
832
      response.setContentType("application/octet-stream");
833
      if (defaultdatapath!=null) {
834
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
835
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
836
        }
837
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
838
        if (executescript!=null) {
839
          String command = null;
840
          File scriptfile = new File(executescript);
841
          if (scriptfile.exists()) {
842
            command=executescript+" "+datadoc[0]; // script includes path
843
        } else {     // look in defaultdatapath
844
            // on Win98 one MUST include the .bat extender
845
            command = defaultdatapath+executescript+" "+datadoc[0];  
846
        }
847
      System.out.println(command);
848
      try {
849
      Process proc = Runtime.getRuntime().exec(command);
850
      proc.waitFor();
851
      }
852
      catch (Exception eee) {
853
        System.out.println("Error running process!");
854
        error_flag = true;
855
        error_message = "Error running process!";}
856
      } // end executescript not null if
857
      File datafile = new File(defaultdatapath+datadoc[0]);
858
      try {
859
      FileInputStream fw = new FileInputStream(datafile);
860
      int x;
861
      while ((x = fw.read())!=-1) {
862
        out.write(x); }
863
        fw.close();
864
      } catch (Exception e) {
865
        System.out.println("Error in returning file\n"+e.getMessage());
866
        error_flag=true;
867
        error_message = error_message+"\nError in returning file\n"+
868
                        e.getMessage();
869
      }
870
    } // end defaultdatapath not null if
871
  }
872
  
873
  /** 
874
   * Handle the getdoctypes Action.
875
   * Read all doctypes from db connection in XML format
876
   */
877
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
878
                                       HttpServletResponse response) {
879

    
880
    Connection conn = null;
881
    
882
    try {
883

    
884
        // get connection from the pool
885
        conn = util.getConnection();
886
        DBUtil dbutil = new DBUtil(conn);
887
        String doctypes = dbutil.readDoctypes();
888
        out.println(doctypes);
889

    
890
    } catch (Exception e) {
891
      out.println("<?xml version=\"1.0\"?>");
892
      out.println("<error>");
893
      out.println(e.getMessage());
894
      out.println("</error>");
895
    } finally {
896
      util.returnConnection(conn);
897
    }  
898
    
899
  }
900

    
901
  /** 
902
   * Handle the getdataguide Action.
903
   * Read Data Guide for a given doctype from db connection in XML format
904
   */
905
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
906
                                        HttpServletResponse response) {
907

    
908
    Connection conn = null;
909
    String doctype = null;
910
    String[] doctypeArr = (String[])params.get("doctype");
911

    
912
    // get only the first doctype specified in the list of doctypes
913
    // it could be done for all doctypes in that list
914
    if (doctypeArr != null) {
915
        doctype = ((String[])params.get("doctype"))[0]; 
916
    }
917

    
918
    try {
919

    
920
        // get connection from the pool
921
        conn = util.getConnection();
922
        DBUtil dbutil = new DBUtil(conn);
923
        String dataguide = dbutil.readDataGuide(doctype);
924
        out.println(dataguide);
925

    
926
    } catch (Exception e) {
927
      out.println("<?xml version=\"1.0\"?>");
928
      out.println("<error>");
929
      out.println(e.getMessage());
930
      out.println("</error>");
931
    } finally {
932
      util.returnConnection(conn);
933
    }  
934
    
935
  }
936

    
937
}
(21-21/27)