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:42:51 -0700 (Tue, 12 Sep 2000) $'
11
 * '$Revision: 444 $'
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
    //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
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
452
   * string as a param instead of a hashtable.
453
   * 
454
   * @param xmlquery a string representing a query.
455
   */
456
  protected String transformQuery(String xmlquery)
457
  {
458
    xmlquery = xmlquery.trim();
459
    int index = xmlquery.indexOf("?>");
460
    return xmlquery.substring(index + 2, xmlquery.length());
461
  }
462
  
463
  /**
464
   * Run the query and return a hashtable of results.
465
   *
466
   * @param xmlquery the query to run
467
   */
468
  private Hashtable runQuery(String xmlquery, String user, String group)
469
  {
470
    Hashtable doclist=null;
471
    Connection conn = null;
472
    try
473
    {
474
      conn = util.getConnection();
475
      DBQuery queryobj = new DBQuery(conn, saxparser);
476
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group);
477
      util.returnConnection(conn);
478
      return doclist;
479
    } 
480
    catch (Exception e) 
481
    {
482
      util.returnConnection(conn); 
483
      util.debugMessage("Error in runQuery: " + e.getMessage());
484
      doclist = null;
485
      return doclist;
486
    }    
487
  }
488
  
489
  /**
490
   * Transorms an xml resultset document to html and sends it to the browser
491
   *
492
   * @param resultdoc the string representation of the document that needs
493
   * to be transformed.
494
   * @param response the HttpServletResponse object bound to the client.
495
   * @param out the output stream to the client
496
   */ 
497
  protected void transformResultset(String resultdoc, 
498
                                    HttpServletResponse response,
499
                                    PrintWriter out)
500
  {
501
    Connection conn = null;
502
    try {
503
      conn = util.getConnection();
504
      DBTransform trans = new DBTransform(conn);
505
      response.setContentType("text/html");
506
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
507
                                 "-//W3C//HTML//EN", out);
508
      util.returnConnection(conn); 
509
    }
510
    catch(Exception e)
511
    {
512
      util.returnConnection(conn); 
513
    } 
514
  }
515
  
516
  /**
517
   * Transforms a hashtable of documents to an xml or html result.
518
   *
519
   * @param doclist- the hashtable to transform
520
   * @param xmlquery- the query that returned the dolist result
521
   */
522
  protected String createResultDocument(Hashtable doclist, String xmlquery)
523
  {
524
    // Create a buffer to hold the xml result
525
    StringBuffer resultset = new StringBuffer();
526
 
527
    // Print the resulting root nodes 
528
    String docid = null;
529
    String document = null;
530
    resultset.append("<?xml version=\"1.0\"?>\n");
531
    resultset.append("<resultset>\n");
532
    
533
    resultset.append("  <query>" + xmlquery + "</query>");   
534
 
535
    Enumeration doclistkeys = doclist.keys(); 
536
    while (doclistkeys.hasMoreElements()) 
537
    {
538
      docid = (String)doclistkeys.nextElement();
539
      document = (String)doclist.get(docid);
540
      resultset.append("  <document>" + document + "</document>");
541
    } 
542
    resultset.append("</resultset>");
543
    //System.out.println(resultset.toString());
544
    return resultset.toString();
545
  }
546
  
547
  /**
548
   * Handle the request to view the abstract of a document.
549
   * The abstractpath CGI parameter gives the xml path to the abstract
550
   * node.  
551
   */
552
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
553
               HttpServletResponse response) throws IOException, SQLException
554
  {
555
    String abstractpath = null;
556
    String docid = null;
557
    Connection conn = null;
558
    response.setContentType("text/html");
559
    try
560
    {
561
      docid = ((String[])params.get("docid"))[0];
562
      if(params.containsKey("abstractpath"))
563
      {
564
        //the CGI parameter abstractpath holds the path to the abstract
565
        //that should be displayed.
566
        abstractpath = ((String[])params.get("abstractpath"))[0];
567
      }
568
      else
569
      {
570
        out.println("error: no abstractpath parameter"); 
571
      }
572
      conn = util.getConnection();
573
    
574
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
575
    
576
      out.println("<html><head><title>Abstract</title></head>");
577
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
578
      for(int i=0; i<abstracts.length; i++)
579
      {
580
        out.println("<p>" + (String)abstracts[i] + "</p>");
581
      }
582
      out.println("</body></html>");
583
    }
584
    catch (IOException ioe)
585
    {
586
       util.debugMessage("error in handlegetabstract: " + ioe.getMessage());
587
    }
588
    catch(SQLException sqle)
589
    {
590
      util.debugMessage("error in handlegetabstract: " + sqle.getMessage()); 
591
    }
592
    catch(Exception e)
593
    {
594
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
595
    }
596
    
597
    util.returnConnection(conn);
598
  }
599

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

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

    
655
  }
656

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

    
664
    Connection conn = null;
665

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
902
    Connection conn = null;
903
    
904
    try {
905

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

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

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

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

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

    
940
    try {
941

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

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

    
959
}
(19-19/27)