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 10:56:32 -0700 (Fri, 18 Aug 2000) $'
11
 * '$Revision: 382 $'
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, xmlquery);
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
   * Run the query and return a hashtable of results.
473
   *
474
   * @param xmlquery the query to run
475
   */
476
  private Hashtable runQuery(String xmlquery)
477
  {
478
    Hashtable doclist=null;
479
    Connection conn = null;
480
    try
481
    {
482
        conn = util.getConnection();
483
        DBQuery queryobj = new DBQuery(conn, saxparser);
484
        doclist = queryobj.findDocuments(new StringReader(xmlquery));
485
        util.returnConnection(conn);
486
        return doclist;
487
    } 
488
    catch (Exception e) 
489
    {
490
      if (conn != null) 
491
      {
492
        util.returnConnection(conn); 
493
      }
494
      util.debugMessage("Error in runQuery: " + e.getMessage());
495
      doclist = null;
496
      return doclist;
497
    }    
498
  }
499
  
500
  /**
501
   * Transorms an xml resultset document to html and sends it to the browser
502
   *
503
   * @param resultdoc the string representation of the document that needs
504
   * to be transformed.
505
   * @param response the HttpServletResponse object bound to the client.
506
   * @param out the output stream to the client
507
   */ 
508
  protected void transformResultset(String resultdoc, 
509
                                    HttpServletResponse response,
510
                                    PrintWriter out)
511
  {
512
    Connection conn = null;
513
    try {
514
      conn = util.getConnection();
515
      DBTransform trans = new DBTransform(conn);
516
      response.setContentType("text/html");
517
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
518
                                 "-//W3C//HTML//EN", out);
519
      util.returnConnection(conn); 
520
    }
521
    catch(Exception e)
522
    {
523
      //if (conn != null) 
524
      {
525
        util.returnConnection(conn); 
526
      }
527
    } 
528
  }
529
  
530
  /**
531
   * Transforms a hashtable of documents to an xml or html result.
532
   *
533
   * @param doclist- the hashtable to transform
534
   * @param xmlquery- the query that returned the dolist result
535
   */
536
  protected String createResultDocument(Hashtable doclist, String xmlquery)
537
  {
538
    // Create a buffer to hold the xml result
539
    StringBuffer resultset = new StringBuffer();
540
 
541
    // Print the resulting root nodes 
542
    String docid = null;
543
    String document = null;
544
    resultset.append("<?xml version=\"1.0\"?>\n");
545
    resultset.append("<resultset>\n");
546

    
547
    //the following should work but it doesn't because the parser doesn't 
548
    //like the <?xml?> tag inside the <query> tag.  This is supposed to be
549
    //the way that the query itself is sent back to the client.
550
    
551
    //resultset.append("  <query>" + xmlquery + "</query>");   
552
 
553
    Enumeration doclistkeys = doclist.keys(); 
554
    while (doclistkeys.hasMoreElements()) 
555
    {
556
      docid = (String)doclistkeys.nextElement();
557
      document = (String)doclist.get(docid);
558
      resultset.append("  <document>" + document + "</document>");
559
    } 
560
    resultset.append("</resultset>");
561
    return resultset.toString();
562
  }
563

    
564
  /** 
565
   * Handle the database getdocument request and return a XML document, 
566
   * possibly transformed from XML into HTML
567
   */
568
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
569
               HttpServletResponse response) 
570
               throws ClassNotFoundException, IOException, SQLException {
571
    String docidstr = null;
572
    String docid = null;
573
    String doc = null;
574
    Connection conn = null;
575
    
576
    try {
577
      // Find the document id number
578
      docidstr = ((String[])params.get("docid"))[0]; 
579
      //docid = (new Long(docidstr)).longValue();
580
      docid = docidstr;
581

    
582
      conn = util.getConnection();
583
      DBReader docreader = new DBReader(conn);
584
      DBTransform dbt = new DBTransform(conn);
585
      
586
      // Get the document indicated fromthe db
587
      doc = docreader.readXMLDocument(docid);
588

    
589
      // Return the document in XML or HTML format
590
      String qformat = ((String[])params.get("qformat"))[0]; 
591
      if (qformat.equals("xml")) {
592
        // set content type and other response header fields first
593
        response.setContentType("text/xml");
594
        out.println(doc);
595
      } else if (qformat.equals("html")) {
596
        // set content type and other response header fields first
597
        response.setContentType("text/html");
598

    
599
        // Look up the document type
600
        String sourcetype = docreader.getDoctypeInfo(docid).getDoctype();
601

    
602
        // Transform the document to the new doctype
603
        dbt.transformXMLDocument(doc, sourcetype, "-//W3C//HTML//EN", out);
604
      }
605
    //} catch (NullPointerException npe) {
606
      //response.setContentType("text/html");
607
      //out.println("Error getting document ID: " + docidstr +" (" + docid + ")");
608
    } catch (McdbException e) {
609
      response.setContentType("text/xml");
610
      e.toXml(out);
611
    } catch (Throwable t) {
612
      response.setContentType("text/html");
613
      out.println(t.getMessage());
614
    } finally {
615
      util.returnConnection(conn);
616
    }    
617

    
618
  }
619

    
620
  /** 
621
   * Handle the database putdocument request and write an XML document 
622
   * to the database connection
623
   */
624
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
625
               HttpServletResponse response) {
626

    
627
    Connection conn = null;
628

    
629
    try {
630
      // Get the document indicated
631
      String[] doctext = (String[])params.get("doctext");
632
      StringReader xml = null;
633
      try {
634
        xml = new StringReader(doctext[0]);
635

    
636
        String[] action = (String[])params.get("action");
637
        String[] docid = (String[])params.get("docid");
638
        String newdocid = null;
639

    
640
        String doAction = null;
641
        if (action[0].equals("insert")) {
642
          doAction = "INSERT";
643
        } else if (action[0].equals("update")) {
644
          doAction = "UPDATE";
645
        }
646

    
647
        try {
648
            // get a connection from the pool
649
            conn = util.getConnection();
650
            // write the document to the database
651
            DBWriter dbw = new DBWriter(conn, saxparser);
652

    
653
            try {
654
                String accNumber = docid[0];
655
                if (accNumber.equals("")) {
656
                    accNumber = null;
657
                }
658
                newdocid = dbw.write(xml, doAction, accNumber);  
659
            } catch (NullPointerException npe) {
660
              newdocid = dbw.write(xml, doAction, null);  
661
            }
662
        } catch (Exception e) {
663
          response.setContentType("text/html");
664
          out.println(e.getMessage());
665
        } finally {
666
          util.returnConnection(conn);
667
        }    
668

    
669
        // set content type and other response header fields first
670
        response.setContentType("text/xml");
671
        out.println("<?xml version=\"1.0\"?>");
672
        out.println("<success>");
673
        out.println("<docid>" + newdocid + "</docid>"); 
674
        out.println("</success>");
675

    
676
      } catch (NullPointerException npe) {
677
        response.setContentType("text/xml");
678
        out.println("<?xml version=\"1.0\"?>");
679
        out.println("<error>");
680
        out.println(npe.getMessage()); 
681
        out.println("</error>");
682
      }
683
    } catch (Exception e) {
684
      response.setContentType("text/xml");
685
      out.println("<?xml version=\"1.0\"?>");
686
      out.println("<error>");
687
      out.println(e.getMessage()); 
688
      if (e instanceof SAXException) {
689
        Exception e2 = ((SAXException)e).getException();
690
        out.println("<error>");
691
        out.println(e2.getMessage()); 
692
        out.println("</error>");
693
      }
694
      //e.printStackTrace(out);
695
      out.println("</error>");
696
    }
697
  }
698

    
699
  /** 
700
   * Handle the database delete request and delete an XML document 
701
   * from the database connection
702
   */
703
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
704
               HttpServletResponse response) {
705

    
706
    String[] docid = (String[])params.get("docid");
707
    Connection conn = null;
708

    
709
    // delete the document from the database
710
    try {
711
      // get a connection from the pool
712
      conn = util.getConnection();
713
      DBWriter dbw = new DBWriter(conn, saxparser);
714
                                      // NOTE -- NEED TO TEST HERE
715
                                      // FOR EXISTENCE OF PARAM
716
                                      // BEFORE ACCESSING ARRAY
717
      try { 
718
        dbw.delete(docid[0]);
719
        response.setContentType("text/xml");
720
        out.println("<?xml version=\"1.0\"?>");
721
        out.println("<success>");
722
        out.println("Document deleted."); 
723
        out.println("</success>");
724
      } catch (AccessionNumberException ane) {
725
        response.setContentType("text/xml");
726
        out.println("<?xml version=\"1.0\"?>");
727
        out.println("<error>");
728
        out.println("Error deleting document!!!");
729
        out.println(ane.getMessage()); 
730
        out.println("</error>");
731
      }
732
    } catch (Exception e) {
733
      response.setContentType("text/xml");
734
      out.println("<?xml version=\"1.0\"?>");
735
      out.println("<error>");
736
      out.println(e.getMessage()); 
737
      out.println("</error>");
738
    } finally {
739
      util.returnConnection(conn);
740
    }  
741
  }
742
  
743
  /** 
744
   * Handle the validation request and return the results to the requestor
745
   */
746
  private void handleValidateAction(PrintWriter out, Hashtable params, 
747
               HttpServletResponse response) {
748

    
749
    // Get the document indicated
750
    String valtext = null;
751
    
752
    try {
753
      valtext = ((String[])params.get("valtext"))[0];
754
    } catch (Exception nullpe) {
755

    
756
      Connection conn = null;
757
      String docid = null;
758
      try {
759
        // Find the document id number
760
        docid = ((String[])params.get("docid"))[0]; 
761

    
762
        // get a connection from the pool
763
        conn = util.getConnection();
764
        DBReader docreader = new DBReader(conn);
765
        // Get the document indicated from the db
766
        valtext = docreader.readXMLDocument(docid);
767

    
768
      } catch (NullPointerException npe) {
769
        response.setContentType("text/xml");
770
        out.println("<error>Error getting document ID: " + docid + "</error>");
771
        if ( conn != null ) { util.returnConnection(conn); }
772
        return;
773
      } catch (Exception e) {
774
        response.setContentType("text/html");
775
        out.println(e.getMessage()); 
776
      } finally {
777
        util.returnConnection(conn);
778
      }  
779
    }
780

    
781
    Connection conn = null;
782
    try {
783
      // get a connection from the pool
784
      conn = util.getConnection();
785
      DBValidate valobj = new DBValidate(saxparser,conn);
786
      boolean valid = valobj.validateString(valtext);
787

    
788
      // set content type and other response header fields first
789
      response.setContentType("text/xml");
790
      out.println(valobj.returnErrors());
791

    
792
    } catch (NullPointerException npe2) {
793
      // set content type and other response header fields first
794
      response.setContentType("text/xml");
795
      out.println("<error>Error validating document.</error>"); 
796
    } catch (Exception e) {
797
      response.setContentType("text/html");
798
      out.println(e.getMessage()); 
799
    } finally {
800
      util.returnConnection(conn);
801
    }  
802
  }
803

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

    
865
    Connection conn = null;
866
    
867
    try {
868

    
869
        // get connection from the pool
870
        conn = util.getConnection();
871
        DBUtil dbutil = new DBUtil(conn);
872
        String doctypes = dbutil.readDoctypes();
873
        out.println(doctypes);
874

    
875
    } catch (Exception e) {
876
      out.println("<?xml version=\"1.0\"?>");
877
      out.println("<error>");
878
      out.println(e.getMessage());
879
      out.println("</error>");
880
    } finally {
881
      util.returnConnection(conn);
882
    }  
883
    
884
  }
885

    
886
  /** 
887
   * Handle the getdataguide Action.
888
   * Read Data Guide for a given doctype from db connection in XML format
889
   */
890
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
891
                                        HttpServletResponse response) {
892

    
893
    Connection conn = null;
894
    String doctype = null;
895
    String[] doctypeArr = (String[])params.get("doctype");
896

    
897
    // get only the first doctype specified in the list of doctypes
898
    // it could be done for all doctypes in that list
899
    if (doctypeArr != null) {
900
        doctype = ((String[])params.get("doctype"))[0]; 
901
    }
902

    
903
    try {
904

    
905
        // get connection from the pool
906
        conn = util.getConnection();
907
        DBUtil dbutil = new DBUtil(conn);
908
        String dataguide = dbutil.readDataGuide(doctype);
909
        out.println(dataguide);
910

    
911
    } catch (Exception e) {
912
      out.println("<?xml version=\"1.0\"?>");
913
      out.println("<error>");
914
      out.println(e.getMessage());
915
      out.println("</error>");
916
    } finally {
917
      util.returnConnection(conn);
918
    }  
919
    
920
  }
921

    
922
}
(21-21/27)