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-09-12 12:28:45 -0700 (Tue, 12 Sep 2000) $'
11
 * '$Revision: 443 $'
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, transformQuery(xmlquery));
390
	
391
    System.out.println("transformed query");
392
    System.out.println(transformQuery(xmlquery));
393
    //format and transform the results                                        
394
    if(qformat.equals("html")) {
395
      transformResultset(resultdoc, response, out);
396
    } else if(qformat.equals("xml")) {
397
      response.setContentType("text/xml");
398
      out.println(resultdoc);
399
    } else {
400
      out.println("invalid qformat: " + qformat); 
401
    }
402
  }
403
  
404
   /**
405
    * Create the xml query, execute it and display the results.
406
    *
407
    * @param out the output stream to the client
408
    * @param params the Hashtable of parameters that should be included
409
    * in the squery.
410
    * @param response the response object linked to the client
411
    */ 
412
  protected void handleQuery(PrintWriter out, Hashtable params, 
413
                 HttpServletResponse response, String user, String group)
414
  {
415
    //create the query and run it
416
    String xmlquery = DBQuery.createSQuery(params);
417
    Hashtable doclist = runQuery(xmlquery, user, group);
418
    String qformat = ((String[])params.get("qformat"))[0]; 
419
    String resultdoc = createResultDocument(doclist, transformQuery(params));
420
    System.out.println(transformQuery(params));
421

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

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

    
602
  /** 
603
   * Handle the database getdocument request and return a XML document, 
604
   * possibly transformed from XML into HTML
605
   */
606
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
607
               HttpServletResponse response) 
608
               throws ClassNotFoundException, IOException, SQLException {
609
    String docidstr = null;
610
    String docid = null;
611
    String doc = null;
612
    Connection conn = null;
613
    
614
    try {
615
      // Find the document id number
616
      docidstr = ((String[])params.get("docid"))[0]; 
617
      docid = docidstr;
618
      conn = util.getConnection();
619
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
620
      // Get the document indicated from the db
621
      //doc = docreader.readXMLDocument(docid);
622

    
623
      // Return the document in XML or HTML format
624
      String qformat=null;
625
      if(params.containsKey("qformat"))
626
      {
627
        qformat = ((String[])params.get("qformat"))[0];
628
      }
629
      else
630
      {
631
        qformat = "html";        
632
      }
633
      if (qformat.equals("xml")) { 
634
        // set content type and other response header fields first
635
        response.setContentType("text/xml");
636
        xmldoc.toXml(out);
637
        //out.println(xmldoc);
638
      } else if (qformat.equals("html")) {
639
        response.setContentType("text/html");
640
        // Look up the document type
641
        String sourcetype = xmldoc.getDoctype();
642
        // Transform the document to the new doctype
643
        DBTransform dbt = new DBTransform(conn);
644
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
645
                                 "-//W3C//HTML//EN", out);
646
      }
647
    } catch (McdbException e) {
648
      response.setContentType("text/xml");
649
      e.toXml(out);
650
    } catch (Throwable t) {
651
      response.setContentType("text/html");
652
      out.println(t.getMessage());
653
    } finally {
654
      util.returnConnection(conn);
655
    }    
656

    
657
  }
658

    
659
  /** 
660
   * Handle the database putdocument request and write an XML document 
661
   * to the database connection
662
   */
663
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
664
               HttpServletResponse response, String user, String group) {
665

    
666
    Connection conn = null;
667

    
668
    try {
669
      // Get the document indicated
670
      String[] doctext = (String[])params.get("doctext");
671
      StringReader xml = null;
672
      try {
673
        xml = new StringReader(doctext[0]);
674

    
675
        String[] action = (String[])params.get("action");
676
        String[] docid = (String[])params.get("docid");
677
        String newdocid = null;
678

    
679
        String doAction = null;
680
        if (action[0].equals("insert")) {
681
          doAction = "INSERT";
682
        } else if (action[0].equals("update")) {
683
          doAction = "UPDATE";
684
        }
685

    
686
        try {
687
            // get a connection from the pool
688
            conn = util.getConnection();
689

    
690
            // write the document to the database
691
            try {
692
                String accNumber = docid[0];
693
                if (accNumber.equals("")) {
694
                    accNumber = null;
695
                }
696
                newdocid = DocumentImpl.write(conn, xml, doAction, accNumber, 
697
                                                                  user, group);
698
            } catch (NullPointerException npe) {
699
              newdocid = DocumentImpl.write(conn,xml,doAction,null,user,group);
700
            }
701
        } catch (Exception e) {
702
          response.setContentType("text/html");
703
          out.println(e.getMessage());
704
        } finally {
705
          util.returnConnection(conn);
706
        }    
707

    
708
        // set content type and other response header fields first
709
        response.setContentType("text/xml");
710
        out.println("<?xml version=\"1.0\"?>");
711
        out.println("<success>");
712
        out.println("<docid>" + newdocid + "</docid>"); 
713
        out.println("</success>");
714

    
715
      } catch (NullPointerException npe) {
716
        response.setContentType("text/xml");
717
        out.println("<?xml version=\"1.0\"?>");
718
        out.println("<error>");
719
        out.println(npe.getMessage()); 
720
        out.println("</error>");
721
      }
722
    } catch (Exception e) {
723
      response.setContentType("text/xml");
724
      out.println("<?xml version=\"1.0\"?>");
725
      out.println("<error>");
726
      out.println(e.getMessage()); 
727
      if (e instanceof SAXException) {
728
        Exception e2 = ((SAXException)e).getException();
729
        out.println("<error>");
730
        out.println(e2.getMessage()); 
731
        out.println("</error>");
732
      }
733
      //e.printStackTrace(out);
734
      out.println("</error>");
735
    }
736
  }
737

    
738
  /** 
739
   * Handle the database delete request and delete an XML document 
740
   * from the database connection
741
   */
742
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
743
               HttpServletResponse response, String user, String group) {
744

    
745
    String[] docid = (String[])params.get("docid");
746
    Connection conn = null;
747

    
748
    // delete the document from the database
749
    try {
750
      // get a connection from the pool
751
      conn = util.getConnection();
752
                                      // NOTE -- NEED TO TEST HERE
753
                                      // FOR EXISTENCE OF DOCID PARAM
754
                                      // BEFORE ACCESSING ARRAY
755
      try { 
756
        DocumentImpl.delete(conn, docid[0], user, group);
757
        response.setContentType("text/xml");
758
        out.println("<?xml version=\"1.0\"?>");
759
        out.println("<success>");
760
        out.println("Document deleted."); 
761
        out.println("</success>");
762
      } catch (AccessionNumberException ane) {
763
        response.setContentType("text/xml");
764
        out.println("<?xml version=\"1.0\"?>");
765
        out.println("<error>");
766
        out.println("Error deleting document!!!");
767
        out.println(ane.getMessage()); 
768
        out.println("</error>");
769
      }
770
    } catch (Exception e) {
771
      response.setContentType("text/xml");
772
      out.println("<?xml version=\"1.0\"?>");
773
      out.println("<error>");
774
      out.println(e.getMessage()); 
775
      out.println("</error>");
776
    } finally {
777
      util.returnConnection(conn);
778
    }  
779
  }
780
  
781
  /** 
782
   * Handle the validation request and return the results to the requestor
783
   */
784
  private void handleValidateAction(PrintWriter out, Hashtable params, 
785
               HttpServletResponse response) {
786

    
787
    // Get the document indicated
788
    String valtext = null;
789
    
790
    try {
791
      valtext = ((String[])params.get("valtext"))[0];
792
    } catch (Exception nullpe) {
793

    
794
      Connection conn = null;
795
      String docid = null;
796
      try {
797
        // Find the document id number
798
        docid = ((String[])params.get("docid"))[0]; 
799

    
800
        // get a connection from the pool
801
        conn = util.getConnection();
802

    
803
        // Get the document indicated from the db
804
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
805
        valtext = xmldoc.toString();
806

    
807
      } catch (NullPointerException npe) {
808
        response.setContentType("text/xml");
809
        out.println("<error>Error getting document ID: " + docid + "</error>");
810
        if ( conn != null ) { util.returnConnection(conn); }
811
        return;
812
      } catch (Exception e) {
813
        response.setContentType("text/html");
814
        out.println(e.getMessage()); 
815
      } finally {
816
        util.returnConnection(conn);
817
      }  
818
    }
819

    
820
    Connection conn = null;
821
    try {
822
      // get a connection from the pool
823
      conn = util.getConnection();
824
      DBValidate valobj = new DBValidate(saxparser,conn);
825
      boolean valid = valobj.validateString(valtext);
826

    
827
      // set content type and other response header fields first
828
      response.setContentType("text/xml");
829
      out.println(valobj.returnErrors());
830

    
831
    } catch (NullPointerException npe2) {
832
      // set content type and other response header fields first
833
      response.setContentType("text/xml");
834
      out.println("<error>Error validating document.</error>"); 
835
    } catch (Exception e) {
836
      response.setContentType("text/html");
837
      out.println(e.getMessage()); 
838
    } finally {
839
      util.returnConnection(conn);
840
    }  
841
  }
842

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

    
904
    Connection conn = null;
905
    
906
    try {
907

    
908
        // get connection from the pool
909
        conn = util.getConnection();
910
        DBUtil dbutil = new DBUtil(conn);
911
        String doctypes = dbutil.readDoctypes();
912
        out.println(doctypes);
913

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

    
925
  /** 
926
   * Handle the getdataguide Action.
927
   * Read Data Guide for a given doctype from db connection in XML format
928
   */
929
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
930
                                        HttpServletResponse response) {
931

    
932
    Connection conn = null;
933
    String doctype = null;
934
    String[] doctypeArr = (String[])params.get("doctype");
935

    
936
    // get only the first doctype specified in the list of doctypes
937
    // it could be done for all doctypes in that list
938
    if (doctypeArr != null) {
939
        doctype = ((String[])params.get("doctype"))[0]; 
940
    }
941

    
942
    try {
943

    
944
        // get connection from the pool
945
        conn = util.getConnection();
946
        DBUtil dbutil = new DBUtil(conn);
947
        String dataguide = dbutil.readDataGuide(doctype);
948
        out.println(dataguide);
949

    
950
    } catch (Exception e) {
951
      out.println("<?xml version=\"1.0\"?>");
952
      out.println("<error>");
953
      out.println(e.getMessage());
954
      out.println("</error>");
955
    } finally {
956
      util.returnConnection(conn);
957
    }  
958
    
959
  }
960

    
961
}
(19-19/27)