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-08-31 17:01:30 -0700 (Thu, 31 Aug 2000) $'
11
 * '$Revision: 425 $'
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

    
245
      //  response.sendRedirect(htmlpath + "/sexpire.html");
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); 
257
    } 
258
    else if(action.equals("squery"))
259
    {
260
      if(params.containsKey("query"))
261
      {
262
        handleSQuery(out, params, response); 
263
        //handleSQuery(((String[])params.get("query"))[0]);
264
      }
265
      else
266
      {
267
        out.println("Illegal action squery without \"query\" parameter");
268
      }
269
    }
270
    else if (action.equals("getdocument")) {
271
      try {
272
        handleGetDocumentAction(out, params, response);
273
      } catch (ClassNotFoundException e) {
274
        out.println(e.getMessage());
275
      } catch (SQLException se) {
276
        out.println(se.getMessage());
277
      }
278
    } else if (action.equals("insert") || action.equals("update")) {
279
      if ( !username.equals("public") && (username != null) ) {
280
        handleInsertOrUpdateAction(out, params, response, username, groupname);
281
      } else {  
282
        out.println("Permission denied for " + action);
283
      }  
284
    } else if (action.equals("delete")) {
285
      if ( !username.equals("public") && (username != null) ) {
286
        handleDeleteAction(out, params, response, username, groupname);
287
      } else {  
288
        out.println("Permission denied for " + action);
289
      }  
290
    } else if (action.equals("validate")) {
291
      handleValidateAction(out, params, response);  
292
    } else if (action.equals("getdatadoc")) {
293
      handleGetDataDocumentAction(out, params, response);  
294
    } else if (action.equals("getdoctypes")) {
295
      handleGetDoctypesAction(out, params, response);  
296
    } else if (action.equals("getdataguide")) {
297
      handleGetDataGuideAction(out, params, response);  
298
    } else if (action.equals("Login") || action.equals("Login Client")) {
299
    } else {
300
      out.println("Error: action not registered.  Please report this error.");
301
    }
302

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

    
343
  /** 
344
   * Handle the Login request. Create a new session object.
345
   * Make a user authentication through SRB RMI Connection.
346
   */
347
  private void handleLoginAction(PrintWriter out, Hashtable params, 
348
               HttpServletRequest request, HttpServletResponse response) {
349

    
350
    MetaCatSession sess = null;
351
    String un = ((String[])params.get("username"))[0];
352
    String pw = ((String[])params.get("password"))[0];
353
    String action = ((String[])params.get("action"))[0];
354
    
355
    try {
356
        sess = new MetaCatSession(request, un, pw);
357
    } catch (Exception e) {
358
      out.println(e.getMessage());
359
    }
360
    
361
    String output = null;
362
    output = sess.userLogin(response, un, pw, action, htmlpath);
363
    out.println(output);
364

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

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

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

    
519
    //the following should work but it doesn't because the parser doesn't 
520
    //like the <?xml?> tag inside the <query> tag.  This is supposed to be
521
    //the way that the query itself is sent back to the client.
522
    
523
    resultset.append("  <query>" + xmlquery + "</query>");   
524
 
525
    Enumeration doclistkeys = doclist.keys(); 
526
    while (doclistkeys.hasMoreElements()) 
527
    {
528
      docid = (String)doclistkeys.nextElement();
529
      document = (String)doclist.get(docid);
530
      resultset.append("  <document>" + document + "</document>");
531
    } 
532
    resultset.append("</resultset>");
533
    return resultset.toString();
534
  }
535

    
536
  /** 
537
   * Handle the database getdocument request and return a XML document, 
538
   * possibly transformed from XML into HTML
539
   */
540
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
541
               HttpServletResponse response) 
542
               throws ClassNotFoundException, IOException, SQLException {
543
    String docidstr = null;
544
    String docid = null;
545
    String doc = null;
546
    Connection conn = null;
547
    
548
    try {
549
      // Find the document id number
550
      docidstr = ((String[])params.get("docid"))[0]; 
551
      docid = docidstr;
552

    
553
      conn = util.getConnection();
554
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
555
      // Get the document indicated from the db
556
      //doc = docreader.readXMLDocument(docid);
557

    
558
      // Return the document in XML or HTML format
559
      String qformat = ((String[])params.get("qformat"))[0]; 
560
      if (qformat.equals("xml")) {
561
        // set content type and other response header fields first
562
        response.setContentType("text/xml");
563
        out.println(xmldoc);
564
      } else if (qformat.equals("html")) {
565

    
566
        // Look up the document type
567
        String sourcetype = xmldoc.getDoctype();
568

    
569
        // Transform the document to the new doctype
570
        DBTransform dbt = new DBTransform(conn);
571
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
572
                                 "-//W3C//HTML//EN", out);
573
      }
574
    } catch (McdbException e) {
575
      response.setContentType("text/xml");
576
      e.toXml(out);
577
    } catch (Throwable t) {
578
      response.setContentType("text/html");
579
      out.println(t.getMessage());
580
    } finally {
581
      util.returnConnection(conn);
582
    }    
583

    
584
  }
585

    
586
  /** 
587
   * Handle the database putdocument request and write an XML document 
588
   * to the database connection
589
   */
590
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
591
               HttpServletResponse response, String user, String group) {
592

    
593
    Connection conn = null;
594

    
595
    try {
596
      // Get the document indicated
597
      String[] doctext = (String[])params.get("doctext");
598
      StringReader xml = null;
599
      try {
600
        xml = new StringReader(doctext[0]);
601

    
602
        String[] action = (String[])params.get("action");
603
        String[] docid = (String[])params.get("docid");
604
        String newdocid = null;
605

    
606
        String doAction = null;
607
        if (action[0].equals("insert")) {
608
          doAction = "INSERT";
609
        } else if (action[0].equals("update")) {
610
          doAction = "UPDATE";
611
        }
612

    
613
        try {
614
            // get a connection from the pool
615
            conn = util.getConnection();
616

    
617
            // write the document to the database
618
            try {
619
                String accNumber = docid[0];
620
                if (accNumber.equals("")) {
621
                    accNumber = null;
622
                }
623
                newdocid = DocumentImpl.write(conn, xml, doAction, accNumber, 
624
                                                                  user, group);
625
            } catch (NullPointerException npe) {
626
              newdocid = DocumentImpl.write(conn,xml,doAction,null,user,group);
627
            }
628
        } catch (Exception e) {
629
          response.setContentType("text/html");
630
          out.println(e.getMessage());
631
        } finally {
632
          util.returnConnection(conn);
633
        }    
634

    
635
        // set content type and other response header fields first
636
        response.setContentType("text/xml");
637
        out.println("<?xml version=\"1.0\"?>");
638
        out.println("<success>");
639
        out.println("<docid>" + newdocid + "</docid>"); 
640
        out.println("</success>");
641

    
642
      } catch (NullPointerException npe) {
643
        response.setContentType("text/xml");
644
        out.println("<?xml version=\"1.0\"?>");
645
        out.println("<error>");
646
        out.println(npe.getMessage()); 
647
        out.println("</error>");
648
      }
649
    } catch (Exception e) {
650
      response.setContentType("text/xml");
651
      out.println("<?xml version=\"1.0\"?>");
652
      out.println("<error>");
653
      out.println(e.getMessage()); 
654
      if (e instanceof SAXException) {
655
        Exception e2 = ((SAXException)e).getException();
656
        out.println("<error>");
657
        out.println(e2.getMessage()); 
658
        out.println("</error>");
659
      }
660
      //e.printStackTrace(out);
661
      out.println("</error>");
662
    }
663
  }
664

    
665
  /** 
666
   * Handle the database delete request and delete an XML document 
667
   * from the database connection
668
   */
669
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
670
               HttpServletResponse response, String user, String group) {
671

    
672
    String[] docid = (String[])params.get("docid");
673
    Connection conn = null;
674

    
675
    // delete the document from the database
676
    try {
677
      // get a connection from the pool
678
      conn = util.getConnection();
679
                                      // NOTE -- NEED TO TEST HERE
680
                                      // FOR EXISTENCE OF DOCID PARAM
681
                                      // BEFORE ACCESSING ARRAY
682
      try { 
683
        DocumentImpl.delete(conn, docid[0], user, group);
684
        response.setContentType("text/xml");
685
        out.println("<?xml version=\"1.0\"?>");
686
        out.println("<success>");
687
        out.println("Document deleted."); 
688
        out.println("</success>");
689
      } catch (AccessionNumberException ane) {
690
        response.setContentType("text/xml");
691
        out.println("<?xml version=\"1.0\"?>");
692
        out.println("<error>");
693
        out.println("Error deleting document!!!");
694
        out.println(ane.getMessage()); 
695
        out.println("</error>");
696
      }
697
    } catch (Exception e) {
698
      response.setContentType("text/xml");
699
      out.println("<?xml version=\"1.0\"?>");
700
      out.println("<error>");
701
      out.println(e.getMessage()); 
702
      out.println("</error>");
703
    } finally {
704
      util.returnConnection(conn);
705
    }  
706
  }
707
  
708
  /** 
709
   * Handle the validation request and return the results to the requestor
710
   */
711
  private void handleValidateAction(PrintWriter out, Hashtable params, 
712
               HttpServletResponse response) {
713

    
714
    // Get the document indicated
715
    String valtext = null;
716
    
717
    try {
718
      valtext = ((String[])params.get("valtext"))[0];
719
    } catch (Exception nullpe) {
720

    
721
      Connection conn = null;
722
      String docid = null;
723
      try {
724
        // Find the document id number
725
        docid = ((String[])params.get("docid"))[0]; 
726

    
727
        // get a connection from the pool
728
        conn = util.getConnection();
729

    
730
        // Get the document indicated from the db
731
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
732
        valtext = xmldoc.toString();
733

    
734
      } catch (NullPointerException npe) {
735
        response.setContentType("text/xml");
736
        out.println("<error>Error getting document ID: " + docid + "</error>");
737
        if ( conn != null ) { util.returnConnection(conn); }
738
        return;
739
      } catch (Exception e) {
740
        response.setContentType("text/html");
741
        out.println(e.getMessage()); 
742
      } finally {
743
        util.returnConnection(conn);
744
      }  
745
    }
746

    
747
    Connection conn = null;
748
    try {
749
      // get a connection from the pool
750
      conn = util.getConnection();
751
      DBValidate valobj = new DBValidate(saxparser,conn);
752
      boolean valid = valobj.validateString(valtext);
753

    
754
      // set content type and other response header fields first
755
      response.setContentType("text/xml");
756
      out.println(valobj.returnErrors());
757

    
758
    } catch (NullPointerException npe2) {
759
      // set content type and other response header fields first
760
      response.setContentType("text/xml");
761
      out.println("<error>Error validating document.</error>"); 
762
    } catch (Exception e) {
763
      response.setContentType("text/html");
764
      out.println(e.getMessage()); 
765
    } finally {
766
      util.returnConnection(conn);
767
    }  
768
  }
769

    
770
  /** 
771
   * Handle the document request and return the results to the requestor
772
   */
773
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, 
774
               HttpServletResponse response) {
775
      boolean error_flag = false;
776
      String error_message = "";
777
      // Get the document indicated
778
      String[] datadoc = (String[])params.get("datadoc");
779
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
780
      // executescript = "test.bat";        // for testing only!!!
781
      
782
      // set content type and other response header fields first
783
      response.setContentType("application/octet-stream");
784
      if (defaultdatapath!=null) {
785
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
786
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
787
        }
788
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
789
        if (executescript!=null) {
790
          String command = null;
791
          File scriptfile = new File(executescript);
792
          if (scriptfile.exists()) {
793
            command=executescript+" "+datadoc[0]; // script includes path
794
        } else {     // look in defaultdatapath
795
            // on Win98 one MUST include the .bat extender
796
            command = defaultdatapath+executescript+" "+datadoc[0];  
797
        }
798
      System.out.println(command);
799
      try {
800
      Process proc = Runtime.getRuntime().exec(command);
801
      proc.waitFor();
802
      }
803
      catch (Exception eee) {
804
        System.out.println("Error running process!");
805
        error_flag = true;
806
        error_message = "Error running process!";}
807
      } // end executescript not null if
808
      File datafile = new File(defaultdatapath+datadoc[0]);
809
      try {
810
      FileInputStream fw = new FileInputStream(datafile);
811
      int x;
812
      while ((x = fw.read())!=-1) {
813
        out.write(x); }
814
        fw.close();
815
      } catch (Exception e) {
816
        System.out.println("Error in returning file\n"+e.getMessage());
817
        error_flag=true;
818
        error_message = error_message+"\nError in returning file\n"+
819
                        e.getMessage();
820
      }
821
    } // end defaultdatapath not null if
822
  }
823
  
824
  /** 
825
   * Handle the getdoctypes Action.
826
   * Read all doctypes from db connection in XML format
827
   */
828
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
829
                                       HttpServletResponse response) {
830

    
831
    Connection conn = null;
832
    
833
    try {
834

    
835
        // get connection from the pool
836
        conn = util.getConnection();
837
        DBUtil dbutil = new DBUtil(conn);
838
        String doctypes = dbutil.readDoctypes();
839
        out.println(doctypes);
840

    
841
    } catch (Exception e) {
842
      out.println("<?xml version=\"1.0\"?>");
843
      out.println("<error>");
844
      out.println(e.getMessage());
845
      out.println("</error>");
846
    } finally {
847
      util.returnConnection(conn);
848
    }  
849
    
850
  }
851

    
852
  /** 
853
   * Handle the getdataguide Action.
854
   * Read Data Guide for a given doctype from db connection in XML format
855
   */
856
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
857
                                        HttpServletResponse response) {
858

    
859
    Connection conn = null;
860
    String doctype = null;
861
    String[] doctypeArr = (String[])params.get("doctype");
862

    
863
    // get only the first doctype specified in the list of doctypes
864
    // it could be done for all doctypes in that list
865
    if (doctypeArr != null) {
866
        doctype = ((String[])params.get("doctype"))[0]; 
867
    }
868

    
869
    try {
870

    
871
        // get connection from the pool
872
        conn = util.getConnection();
873
        DBUtil dbutil = new DBUtil(conn);
874
        String dataguide = dbutil.readDataGuide(doctype);
875
        out.println(dataguide);
876

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

    
888
}
(19-19/27)