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: bojilova $'
10
 *     '$Date: 2000-09-12 10:37:07 -0700 (Tue, 12 Sep 2000) $'
11
 * '$Revision: 441 $'
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
    String username = null;
221
    String groupname = null;
222
    if (action.equals("Login") || action.equals("Login Client")) {
223
      handleLoginAction(out, params, request, response);
224
    // handle logout action  
225
    } else if (action.equals("Logout") || action.equals("Logout Client")) {
226
      HttpSession sess = request.getSession(false);
227
      if (sess != null) { sess.invalidate();  }    
228
      if (action.equals("Logout Client")) {
229
        out.println("<?xml version=\"1.0\"?>");
230
        out.println("<success>");
231
        out.println("User logout.");
232
        out.println("</success>");
233
        return;
234
      }    
235

    
236
      response.sendRedirect(htmlpath + "/index.html"); 
237

    
238
    // aware of session expiration on every request  
239
    } else {   
240
      HttpSession sess = request.getSession(true);
241
      if (sess.isNew()) { 
242
        // session expired or has not been stored b/w user requests
243
        // redirect to default page for query only access
244
        //  response.sendRedirect(htmlpath + "/sexpire.html");
245
        username = "public";
246
      } else {
247
        username = (String)sess.getAttribute("username");
248
        groupname = (String)sess.getAttribute("groupname");
249
      }  
250
    }    
251

    
252
    // Now that we know the session is valid, we can delegate the request
253
    // to a particular action handler
254
    if(action.equals("query"))
255
    {
256
      handleQuery(out, params, response, username, groupname); 
257
    } 
258
    else if(action.equals("squery"))
259
    {
260
      if(params.containsKey("query"))
261
      {
262
        handleSQuery(out, params, response, username, groupname); 
263
      }
264
      else
265
      {
266
        out.println("Illegal action squery without \"query\" parameter");
267
      }
268
    }
269
    else if (action.equals("getdocument")) {
270
      try {
271
        handleGetDocumentAction(out, params, response);
272
      } catch (ClassNotFoundException e) {
273
        out.println(e.getMessage());
274
      } catch (SQLException se) {
275
        out.println(se.getMessage());
276
      }
277
    } else if (action.equals("insert") || action.equals("update")) {
278
      if ( !username.equals("public") && (username != null) ) {
279
        handleInsertOrUpdateAction(out, params, response, username, groupname);
280
      } else {  
281
        out.println("Permission denied for " + action);
282
      }  
283
    } else if (action.equals("delete")) {
284
      if ( !username.equals("public") && (username != null) ) {
285
        handleDeleteAction(out, params, response, username, groupname);
286
      } else {  
287
        out.println("Permission denied for " + action);
288
      }  
289
    } else if (action.equals("validate")) {
290
      handleValidateAction(out, params, response); 
291
    } else if (action.equals("getabstract")) {
292
      try{
293
        handleViewAbstractAction(out, params, response);
294
      }
295
      catch(Exception e)
296
      {
297
        out.println("error viewing abstract: " + e.getMessage());
298
      }
299
    } else if (action.equals("getdatadoc")) {
300
      handleGetDataDocumentAction(out, params, response);  
301
    } else if (action.equals("getdoctypes")) {
302
      handleGetDoctypesAction(out, params, response);  
303
    } else if (action.equals("getdataguide")) {
304
      handleGetDataGuideAction(out, params, response);  
305
    } else if (action.equals("Login") || action.equals("Login Client")) {
306
    } else {
307
      out.println("Error: action not registered.  Please report this error.");
308
    }
309

    
310
    // Close the stream to the client
311
    out.close();
312
  }
313
  
314
  /**
315
   * decodes the mouse click information coming from the client.
316
   * This function may be overwritten to provide specific functionality
317
   * for different applications.
318
   * @param params the parameters from the CGI
319
   * @return action the action to be performed or "error" if an error was
320
   * generated
321
   */
322
  protected String decodeMouseAction(Hashtable params)
323
  {
324
    // Determine what type of request the user made
325
    // if the action parameter is set, use it as a default
326
    // but if the ypos param is set, calculate the action needed
327
    String action=null;
328
    long ypos = 0;
329
    try {
330
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
331
      //out.println("<P>YPOS IS " + ypos);
332
      if (ypos <= 13) {
333
        action = "getdocument";
334
      } else if (ypos > 13 && ypos <= 27) {
335
        action = "validate";
336
      } else if (ypos > 27) {
337
        action = "transform";
338
      }
339
      return action;
340
    } catch (Exception npe) {
341
      //
342
      // MBJ -- NOTE that this should be handled more gracefully with
343
      //        the new exception infrastructure -- this "error" return
344
      //        value is inappropriate
345
      //out.println("<P>Caught exception looking for Y value.");
346
      return "error";
347
    }  
348
  }
349

    
350
  /** 
351
   * Handle the Login request. Create a new session object.
352
   * Make a user authentication through SRB RMI Connection.
353
   */
354
  private void handleLoginAction(PrintWriter out, Hashtable params, 
355
               HttpServletRequest request, HttpServletResponse response) {
356

    
357
    MetaCatSession sess = null;
358
    String un = ((String[])params.get("username"))[0];
359
    String pw = ((String[])params.get("password"))[0];
360
    String action = ((String[])params.get("action"))[0];
361
    
362
    try {
363
        sess = new MetaCatSession(request, un, pw);
364
    } catch (Exception e) {
365
      out.println(e.getMessage());
366
    }
367
    
368
    String output = null;
369
    output = sess.userLogin(response, un, pw, action, htmlpath);
370
    out.println(output);
371

    
372
  }    
373
  
374
  /**      
375
   * Retreive the squery xml, execute it and display it
376
   *
377
   * @param out the output stream to the client
378
   * @param params the Hashtable of parameters that should be included
379
   * in the squery.
380
   * @param response the response object linked to the client
381
   * @param conn the database connection 
382
   */
383
  protected void handleSQuery(PrintWriter out, Hashtable params, 
384
                 HttpServletResponse response, String user, String group)
385
  { 
386
    String xmlquery = ((String[])params.get("query"))[0];
387
    String qformat = ((String[])params.get("qformat"))[0];
388
    Hashtable doclist = runQuery(xmlquery, user, group);
389
    String resultdoc = createResultDocument(doclist, xmlquery);
390

    
391
    //format and transform the results                                        
392
    if(qformat.equals("html")) {
393
      transformResultset(resultdoc, response, out);
394
    } else if(qformat.equals("xml")) {
395
      response.setContentType("text/xml");
396
      out.println(resultdoc);
397
    } else {
398
      out.println("invalid qformat: " + qformat); 
399
    }
400
  }
401
  
402
   /**
403
    * Create the xml query, execute it and display the results.
404
    *
405
    * @param out the output stream to the client
406
    * @param params the Hashtable of parameters that should be included
407
    * in the squery.
408
    * @param response the response object linked to the client
409
    */ 
410
  protected void handleQuery(PrintWriter out, Hashtable params, 
411
                 HttpServletResponse response, String user, String group)
412
  {
413
    //create the query and run it
414
    String xmlquery = DBQuery.createSQuery(params);
415
    Hashtable doclist = runQuery(xmlquery, user, group);
416
    String qformat = ((String[])params.get("qformat"))[0]; 
417
    String resultdoc = createResultDocument(doclist, transformQuery(params));
418

    
419
    //format and transform the results                                        
420
    if(qformat.equals("html")) {
421
      transformResultset(resultdoc, response, out);
422
    } else if(qformat.equals("xml")) {
423
      response.setContentType("text/xml");
424
      out.println(resultdoc);
425
    } else {
426
      out.println("invalid qformat: " + qformat); 
427
    }
428
  }
429
  
430
  /**
431
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
432
   * so it can properly be placed in the <query> tag of the resultset.
433
   * This method is overwritable so that other applications can customize
434
   * the structure of what is in the <query> tag.
435
   * 
436
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
437
   */
438
  protected String transformQuery(Hashtable params)
439
  {
440
    //DBQuery.createSQuery is a re-calling of a previously called 
441
    //function but it is necessary
442
    //so that overriding methods have access to the params hashtable
443
    String xmlquery = DBQuery.createSQuery(params);
444
    //the <?xml version="1.0"?> tag is the first 22 characters of the
445
    xmlquery = xmlquery.trim();
446
    int index = xmlquery.indexOf("?>");
447
    return xmlquery.substring(index + 2, xmlquery.length());
448
  }
449
  
450
  /**
451
   * Run the query and return a hashtable of results.
452
   *
453
   * @param xmlquery the query to run
454
   */
455
  private Hashtable runQuery(String xmlquery, String user, String group)
456
  {
457
    Hashtable doclist=null;
458
    Connection conn = null;
459
    try
460
    {
461
      conn = util.getConnection();
462
      DBQuery queryobj = new DBQuery(conn, saxparser);
463
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group);
464
      util.returnConnection(conn);
465
      return doclist;
466
    } 
467
    catch (Exception e) 
468
    {
469
      util.returnConnection(conn); 
470
      util.debugMessage("Error in runQuery: " + e.getMessage());
471
      doclist = null;
472
      return doclist;
473
    }    
474
  }
475
  
476
  /**
477
   * Transorms an xml resultset document to html and sends it to the browser
478
   *
479
   * @param resultdoc the string representation of the document that needs
480
   * to be transformed.
481
   * @param response the HttpServletResponse object bound to the client.
482
   * @param out the output stream to the client
483
   */ 
484
  protected void transformResultset(String resultdoc, 
485
                                    HttpServletResponse response,
486
                                    PrintWriter out)
487
  {
488
    Connection conn = null;
489
    try {
490
      conn = util.getConnection();
491
      DBTransform trans = new DBTransform(conn);
492
      response.setContentType("text/html");
493
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
494
                                 "-//W3C//HTML//EN", out);
495
      util.returnConnection(conn); 
496
    }
497
    catch(Exception e)
498
    {
499
      util.returnConnection(conn); 
500
    } 
501
  }
502
  
503
  /**
504
   * Transforms a hashtable of documents to an xml or html result.
505
   *
506
   * @param doclist- the hashtable to transform
507
   * @param xmlquery- the query that returned the dolist result
508
   */
509
  protected String createResultDocument(Hashtable doclist, String xmlquery)
510
  {
511
    // Create a buffer to hold the xml result
512
    StringBuffer resultset = new StringBuffer();
513
 
514
    // Print the resulting root nodes 
515
    String docid = null;
516
    String document = null;
517
    resultset.append("<?xml version=\"1.0\"?>\n");
518
    resultset.append("<resultset>\n");
519

    
520
    //the following should work but it doesn't because the parser doesn't 
521
    //like the <?xml?> tag inside the <query> tag.  This is supposed to be
522
    //the way that the query itself is sent back to the client.
523
    
524
    resultset.append("  <query>" + xmlquery + "</query>");   
525
 
526
    Enumeration doclistkeys = doclist.keys(); 
527
    while (doclistkeys.hasMoreElements()) 
528
    {
529
      docid = (String)doclistkeys.nextElement();
530
      document = (String)doclist.get(docid);
531
      resultset.append("  <document>" + document + "</document>");
532
    } 
533
    resultset.append("</resultset>");
534
    return resultset.toString();
535
  }
536
  
537
  /**
538
   * Handle the request to view the abstract of a document.
539
   */
540
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
541
               HttpServletResponse response) throws IOException, SQLException
542
  {
543
    String abstractpath = null;
544
    String docid = null;
545
    Connection conn = null;
546
    response.setContentType("text/html");
547
    try
548
    {
549
      docid = ((String[])params.get("docid"))[0];
550
      if(params.containsKey("abstractpath"))
551
      {
552
        abstractpath = ((String[])params.get("abstractpath"))[0];
553
      }
554
      else
555
      {
556
        out.println("error: no abstractpath parameter"); 
557
      }
558
      conn = util.getConnection();
559
    
560
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
561
    
562
      out.println("<html><head><title>Abstract</title></head><body>");
563
      out.println("<h1>Abstract</h1>");
564
      for(int i=0; i<abstracts.length; i++)
565
      {
566
        out.println("<p>" + (String)abstracts[i] + "</p>");
567
      }
568
      out.println("</body></html>");
569
    }
570
    catch (IOException ioe)
571
    {
572
       System.out.println(ioe.getMessage());
573
    }
574
    catch(SQLException sqle)
575
    {
576
      System.out.println(sqle.getMessage()); 
577
    }
578
    catch(Exception e)
579
    {
580
      System.out.println(e.getMessage());
581
    }
582
    
583
    util.returnConnection(conn);
584
  }
585

    
586
  /** 
587
   * Handle the database getdocument request and return a XML document, 
588
   * possibly transformed from XML into HTML
589
   */
590
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
591
               HttpServletResponse response) 
592
               throws ClassNotFoundException, IOException, SQLException {
593
    String docidstr = null;
594
    String docid = null;
595
    String doc = null;
596
    Connection conn = null;
597
    
598
    try {
599
      // Find the document id number
600
      docidstr = ((String[])params.get("docid"))[0]; 
601
      docid = docidstr;
602
      conn = util.getConnection();
603
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
604
      // Get the document indicated from the db
605
      //doc = docreader.readXMLDocument(docid);
606

    
607
      // Return the document in XML or HTML format
608
      String qformat=null;
609
      if(params.containsKey("qformat"))
610
      {
611
        qformat = ((String[])params.get("qformat"))[0];
612
      }
613
      else
614
      {
615
        qformat = "html";        
616
      }
617
      if (qformat.equals("xml")) { 
618
        // set content type and other response header fields first
619
        response.setContentType("text/xml");
620
        xmldoc.toXml(out);
621
        //out.println(xmldoc);
622
      } else if (qformat.equals("html")) {
623
        response.setContentType("text/html");
624
        // Look up the document type
625
        String sourcetype = xmldoc.getDoctype();
626
        // Transform the document to the new doctype
627
        DBTransform dbt = new DBTransform(conn);
628
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
629
                                 "-//W3C//HTML//EN", out);
630
      }
631
    } catch (McdbException e) {
632
      response.setContentType("text/xml");
633
      e.toXml(out);
634
    } catch (Throwable t) {
635
      response.setContentType("text/html");
636
      out.println(t.getMessage());
637
    } finally {
638
      util.returnConnection(conn);
639
    }    
640

    
641
  }
642

    
643
  /** 
644
   * Handle the database putdocument request and write an XML document 
645
   * to the database connection
646
   */
647
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
648
               HttpServletResponse response, String user, String group) {
649

    
650
    Connection conn = null;
651

    
652
    try {
653
      // Get the document indicated
654
      String[] doctext = (String[])params.get("doctext");
655
      StringReader xml = null;
656
      try {
657
        xml = new StringReader(doctext[0]);
658

    
659
        String[] action = (String[])params.get("action");
660
        String[] docid = (String[])params.get("docid");
661
        String newdocid = null;
662

    
663
        String doAction = null;
664
        if (action[0].equals("insert")) {
665
          doAction = "INSERT";
666
        } else if (action[0].equals("update")) {
667
          doAction = "UPDATE";
668
        }
669

    
670
        try {
671
            // get a connection from the pool
672
            conn = util.getConnection();
673

    
674
            // write the document to the database
675
            try {
676
                String accNumber = docid[0];
677
                if (accNumber.equals("")) {
678
                    accNumber = null;
679
                }
680
                newdocid = DocumentImpl.write(conn, xml, doAction, accNumber, 
681
                                                                  user, group);
682
            } catch (NullPointerException npe) {
683
              newdocid = DocumentImpl.write(conn,xml,doAction,null,user,group);
684
            }
685
        } catch (Exception e) {
686
          response.setContentType("text/html");
687
          out.println(e.getMessage());
688
        } finally {
689
          util.returnConnection(conn);
690
        }    
691

    
692
        // set content type and other response header fields first
693
        response.setContentType("text/xml");
694
        out.println("<?xml version=\"1.0\"?>");
695
        out.println("<success>");
696
        out.println("<docid>" + newdocid + "</docid>"); 
697
        out.println("</success>");
698

    
699
      } catch (NullPointerException npe) {
700
        response.setContentType("text/xml");
701
        out.println("<?xml version=\"1.0\"?>");
702
        out.println("<error>");
703
        out.println(npe.getMessage()); 
704
        out.println("</error>");
705
      }
706
    } catch (Exception e) {
707
      response.setContentType("text/xml");
708
      out.println("<?xml version=\"1.0\"?>");
709
      out.println("<error>");
710
      out.println(e.getMessage()); 
711
      if (e instanceof SAXException) {
712
        Exception e2 = ((SAXException)e).getException();
713
        out.println("<error>");
714
        out.println(e2.getMessage()); 
715
        out.println("</error>");
716
      }
717
      //e.printStackTrace(out);
718
      out.println("</error>");
719
    }
720
  }
721

    
722
  /** 
723
   * Handle the database delete request and delete an XML document 
724
   * from the database connection
725
   */
726
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
727
               HttpServletResponse response, String user, String group) {
728

    
729
    String[] docid = (String[])params.get("docid");
730
    Connection conn = null;
731

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

    
771
    // Get the document indicated
772
    String valtext = null;
773
    
774
    try {
775
      valtext = ((String[])params.get("valtext"))[0];
776
    } catch (Exception nullpe) {
777

    
778
      Connection conn = null;
779
      String docid = null;
780
      try {
781
        // Find the document id number
782
        docid = ((String[])params.get("docid"))[0]; 
783

    
784
        // get a connection from the pool
785
        conn = util.getConnection();
786

    
787
        // Get the document indicated from the db
788
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
789
        valtext = xmldoc.toString();
790

    
791
      } catch (NullPointerException npe) {
792
        response.setContentType("text/xml");
793
        out.println("<error>Error getting document ID: " + docid + "</error>");
794
        if ( conn != null ) { util.returnConnection(conn); }
795
        return;
796
      } catch (Exception e) {
797
        response.setContentType("text/html");
798
        out.println(e.getMessage()); 
799
      } finally {
800
        util.returnConnection(conn);
801
      }  
802
    }
803

    
804
    Connection conn = null;
805
    try {
806
      // get a connection from the pool
807
      conn = util.getConnection();
808
      DBValidate valobj = new DBValidate(saxparser,conn);
809
      boolean valid = valobj.validateString(valtext);
810

    
811
      // set content type and other response header fields first
812
      response.setContentType("text/xml");
813
      out.println(valobj.returnErrors());
814

    
815
    } catch (NullPointerException npe2) {
816
      // set content type and other response header fields first
817
      response.setContentType("text/xml");
818
      out.println("<error>Error validating document.</error>"); 
819
    } catch (Exception e) {
820
      response.setContentType("text/html");
821
      out.println(e.getMessage()); 
822
    } finally {
823
      util.returnConnection(conn);
824
    }  
825
  }
826

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

    
888
    Connection conn = null;
889
    
890
    try {
891

    
892
        // get connection from the pool
893
        conn = util.getConnection();
894
        DBUtil dbutil = new DBUtil(conn);
895
        String doctypes = dbutil.readDoctypes();
896
        out.println(doctypes);
897

    
898
    } catch (Exception e) {
899
      out.println("<?xml version=\"1.0\"?>");
900
      out.println("<error>");
901
      out.println(e.getMessage());
902
      out.println("</error>");
903
    } finally {
904
      util.returnConnection(conn);
905
    }  
906
    
907
  }
908

    
909
  /** 
910
   * Handle the getdataguide Action.
911
   * Read Data Guide for a given doctype from db connection in XML format
912
   */
913
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
914
                                        HttpServletResponse response) {
915

    
916
    Connection conn = null;
917
    String doctype = null;
918
    String[] doctypeArr = (String[])params.get("doctype");
919

    
920
    // get only the first doctype specified in the list of doctypes
921
    // it could be done for all doctypes in that list
922
    if (doctypeArr != null) {
923
        doctype = ((String[])params.get("doctype"))[0]; 
924
    }
925

    
926
    try {
927

    
928
        // get connection from the pool
929
        conn = util.getConnection();
930
        DBUtil dbutil = new DBUtil(conn);
931
        String dataguide = dbutil.readDataGuide(doctype);
932
        out.println(dataguide);
933

    
934
    } catch (Exception e) {
935
      out.println("<?xml version=\"1.0\"?>");
936
      out.println("<error>");
937
      out.println(e.getMessage());
938
      out.println("</error>");
939
    } finally {
940
      util.returnConnection(conn);
941
    }  
942
    
943
  }
944

    
945
}
(19-19/27)