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-15 12:52:12 -0700 (Fri, 15 Sep 2000) $'
11
 * '$Revision: 453 $'
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.io.DataInputStream;
24
import java.util.Enumeration;
25
import java.util.Hashtable;
26
import java.util.ResourceBundle; 
27
import java.util.PropertyResourceBundle;
28
import java.net.URL;
29
import java.net.MalformedURLException;
30
import java.sql.PreparedStatement;
31
import java.sql.ResultSet;
32
import java.sql.Connection;
33
import java.sql.SQLException;
34
import java.lang.reflect.*;
35
import java.net.*;
36

    
37
import javax.servlet.ServletConfig;
38
import javax.servlet.ServletContext;
39
import javax.servlet.ServletException;
40
import javax.servlet.ServletInputStream;
41
import javax.servlet.http.HttpServlet;
42
import javax.servlet.http.HttpServletRequest;
43
import javax.servlet.http.HttpServletResponse;
44
import javax.servlet.http.HttpSession;
45
import javax.servlet.http.HttpUtils;
46

    
47
import oracle.xml.parser.v2.XSLStylesheet;
48
import oracle.xml.parser.v2.XSLException;
49
import oracle.xml.parser.v2.XMLDocumentFragment;
50
import oracle.xml.parser.v2.XSLProcessor;
51

    
52
import org.xml.sax.SAXException;
53

    
54
/**
55
 * A metadata catalog server implemented as a Java Servlet
56
 *
57
 * <p>Valid parameters are:<br>
58
 * action=query -- query the values of all elements and attributes
59
 *                     and return a result set of nodes<br>
60
 * action=squery -- structured query (see pathquery.dtd)<br>
61
 * action=insert -- insert an XML document into the database store<br>
62
 * action=update -- update an XML document that is in the database store<br>
63
 * action=delete --  delete an XML document from the database store<br>
64
 * action=validate -- vallidate the xml contained in valtext<br>
65
 * action=getdocument -- display an XML document in XML or HTML<br>
66
 * doctype -- document type list returned by the query (publicID)<br>
67
 * qformat=xml -- display resultset from query in XML<br>
68
 * qformat=html -- display resultset from query in HTML<br>
69
 * docid=34 -- display the document with the document ID number 34<br>
70
 * doctext -- XML text of the document to load into the database<br>
71
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
72
 * valtext -- XML text to be validated<br>
73
 * action=getdatadoc -- retreive a stored datadocument<br>
74
 * action=getdoctypes -- retreive all doctypes (publicID)<br>
75
 * action=getdataguide -- retreive a Data Guide<br>
76
 * datadoc -- data document name (id)<br>
77
 * <p>
78
 * The particular combination of parameters that are valid for each 
79
 * particular action value is quite specific.  This documentation
80
 * will be reorganized to reflect this information.
81
 */
82
public class MetaCatServlet extends HttpServlet {
83

    
84
  private ServletConfig config = null;
85
  private ServletContext context = null;
86
  private Hashtable connectionPool = new Hashtable();
87
  private String resultStyleURL = null;
88
  private String xmlcatalogfile = null;
89
  private String saxparser = null;
90
  private String defaultdatapath = null; 
91
  private String servletpath = null; 
92
  private PropertyResourceBundle options = null;
93
  private MetaCatUtil util = null;
94

    
95
  // path to directory where data files 
96
  // that can be downloaded will be stored
97
  private String htmlpath = null; 
98
  // script to get data file and put it 
99
  // in defaultdocpath dir
100
  private String executescript  = null;  
101

    
102

    
103
  /**
104
   * Initialize the servlet by creating appropriate database connections
105
   */
106
  public void init( ServletConfig config ) throws ServletException {
107
    try {
108
      super.init( config );
109
      this.config = config;
110
      this.context = config.getServletContext(); 
111
      System.out.println("MetaCatServlet Initialize");
112

    
113
      util = new MetaCatUtil();
114

    
115
      // Get the configuration file information
116
      resultStyleURL = util.getOption("resultStyleURL");
117
      xmlcatalogfile = util.getOption("xmlcatalogfile");
118
      saxparser = util.getOption("saxparser");
119
      defaultdatapath = util.getOption("defaultdatapath");
120
      executescript = util.getOption("executescript");
121
      servletpath = util.getOption("servletpath");
122
      htmlpath = util.getOption("htmlpath");
123

    
124
      try {
125
        // Open a pool of db connections
126
        connectionPool = util.getConnectionPool();
127
      } catch (Exception e) {
128
        System.err.println("Error creating pool of database connections");
129
        System.err.println(e.getMessage());
130
      }
131
    } catch ( ServletException ex ) {
132
      throw ex;
133
    }
134
  }
135

    
136
  /**
137
   * Close all db connections from the pool
138
   */
139
  public void destroy() {
140
    
141
    if (util != null) {
142
        util.closeConnections();
143
    }
144
  }
145

    
146
  /** Handle "GET" method requests from HTTP clients */
147
  public void doGet (HttpServletRequest request, HttpServletResponse response)
148
    throws ServletException, IOException {
149

    
150
    // Process the data and send back the response
151
    handleGetOrPost(request, response);
152
  }
153

    
154
  /** Handle "POST" method requests from HTTP clients */
155
  public void doPost( HttpServletRequest request, HttpServletResponse response)
156
    throws ServletException, IOException {
157

    
158
    // Process the data and send back the response
159
    handleGetOrPost(request, response);
160
  }
161

    
162
  /**
163
   * Control servlet response depending on the action parameter specified
164
   */
165
  private void handleGetOrPost(HttpServletRequest request, 
166
    HttpServletResponse response) 
167
    throws ServletException, IOException 
168
 {
169

    
170
    if ( util == null ) {
171
        util = new MetaCatUtil(); 
172
    }
173
    if ( connectionPool == null ) {
174
      try {
175
        // Open a pool of db connections
176
        connectionPool = util.getConnectionPool();
177
      } catch (Exception e) {
178
        System.err.println("Error creating pool of database connections");
179
        System.err.println(e.getMessage());
180
      }
181
    }    
182
    // Get a handle to the output stream back to the client
183
    PrintWriter out = response.getWriter();
184
    //response.setContentType("text/html");
185
  
186
    String name = null;
187
    String[] value = null;
188
    String[] docid = new String[3];
189
    Hashtable params = new Hashtable();
190
    Enumeration paramlist = request.getParameterNames();
191
    while (paramlist.hasMoreElements()) {
192
      name = (String)paramlist.nextElement();
193
      value = request.getParameterValues(name);
194

    
195
      // Decode the docid and mouse click information
196
      if (name.endsWith(".y")) {
197
        docid[0] = name.substring(0,name.length()-2);
198
        //out.println("docid => " + docid[0]);
199
        params.put("docid", docid);
200
        name = "ypos";
201
      }
202
      if (name.endsWith(".x")) {
203
        name = "xpos";
204
      } 
205

    
206
      //out.println(name + " => " + value[0]);
207
      params.put(name,value); 
208
    }  
209
    
210
    //if the user clicked on the input images, decode which image
211
    //was clicked then set the action.
212
    String action = decodeMouseAction(params);
213
    if(action.equals("error"))
214
    {
215
      action = ((String[])params.get("action"))[0];  
216
    }
217
    
218
    // This block handles session management for the servlet
219
    // by looking up the current session information for all actions
220
    // other than "Login" and "Logout"
221
    // handle login action
222
    String username = null;
223
    String groupname = null;
224
    if (action.equals("Login") || action.equals("Login Client")) {
225
      handleLoginAction(out, params, request, response);
226
    // handle logout action  
227
    } else if (action.equals("Logout") || action.equals("Logout Client")) {
228
      HttpSession sess = request.getSession(false);
229
      if (sess != null) { sess.invalidate();  }    
230
      if (action.equals("Logout Client")) {
231
        out.println("<?xml version=\"1.0\"?>");
232
        out.println("<success>");
233
        out.println("User logout.");
234
        out.println("</success>");
235
        return;
236
      }    
237

    
238
      response.sendRedirect(htmlpath + "/index.html"); 
239

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

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

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

    
362
  /** 
363
   * Handle the Login request. Create a new session object.
364
   * Make a user authentication through SRB RMI Connection.
365
   */
366
  private void handleLoginAction(PrintWriter out, Hashtable params, 
367
               HttpServletRequest request, HttpServletResponse response) {
368

    
369
    MetaCatSession sess = null;
370
    String un = ((String[])params.get("username"))[0];
371
    String pw = ((String[])params.get("password"))[0];
372
    String action = ((String[])params.get("action"))[0];
373
    
374
    try {
375
        sess = new MetaCatSession(request, un, pw);
376
    } catch (Exception e) {
377
      out.println(e.getMessage());
378
    }
379
    
380
    String output = null;
381
    output = sess.userLogin(response, un, pw, action, htmlpath);
382
    out.println(output);
383

    
384
  }    
385
  
386
  /**      
387
   * Retreive the squery xml, execute it and display it
388
   *
389
   * @param out the output stream to the client
390
   * @param params the Hashtable of parameters that should be included
391
   * in the squery.
392
   * @param response the response object linked to the client
393
   * @param conn the database connection 
394
   */
395
  protected void handleSQuery(PrintWriter out, Hashtable params, 
396
                 HttpServletResponse response, String user, String group)
397
  { 
398
    String xmlquery = ((String[])params.get("query"))[0];
399
    String qformat = ((String[])params.get("qformat"))[0];
400
    Hashtable doclist = runQuery(xmlquery, user, group);
401
    String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
402

    
403
    //format and transform the results                                        
404
    if(qformat.equals("html")) {
405
      transformResultset(resultdoc, response, out);
406
    } else if(qformat.equals("xml")) {
407
      response.setContentType("text/xml");
408
      out.println(resultdoc);
409
    } else {
410
      out.println("invalid qformat: " + qformat); 
411
    }
412
  }
413
  
414
   /**
415
    * Create the xml query, execute it and display the results.
416
    *
417
    * @param out the output stream to the client
418
    * @param params the Hashtable of parameters that should be included
419
    * in the squery.
420
    * @param response the response object linked to the client
421
    */ 
422
  protected void handleQuery(PrintWriter out, Hashtable params, 
423
                 HttpServletResponse response, String user, String group)
424
  {
425
    //create the query and run it
426
    String xmlquery = DBQuery.createSQuery(params);
427
    Hashtable doclist = runQuery(xmlquery, user, group);
428
    String qformat = ((String[])params.get("qformat"))[0]; 
429
    String resultdoc = createResultDocument(doclist, transformQuery(params));
430

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

    
612
  /** 
613
   * Handle the database getrelateddocument request and return a XML document, 
614
   * possibly transformed from XML into HTML
615
   */
616
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params, 
617
               HttpServletResponse response) 
618
               throws ClassNotFoundException, IOException, SQLException 
619
  {
620
    String docid = null;
621
    Connection conn = null;
622
      
623
    if(params.containsKey("url"))
624
    {//the identifier for the related document is contained in the URL param
625
      try
626
      {
627
        DocumentImpl xmldoc=null;
628
        metacatURL murl = new metacatURL(((String[])params.get("url"))[0]);
629
        if(murl.getURLType().equals("metacat"))
630
        {//get the document from the database if it is the right type of url
631
          String[] murlParams = murl.getParam(0);
632
          if(murlParams[0].equals("docid"))
633
          {//the docid should be first
634
            murl.printParams();
635
            docid = murlParams[1]; //get the docid value
636
            conn = util.getConnection();
637
            xmldoc = new DocumentImpl(conn, docid);
638
            
639
            //**************************************************
640
            //the style sheet handling code needs to be put here. 
641
            out.println(xmldoc.toString());
642
            //**************************************************
643
          }
644
          else
645
          {
646
            //throw new Exception("handleGetDocument: bad URL");
647
            System.err.println("handleGetDocument: bad URL");
648
          }
649
        }
650
        else if(murl.getURLType().equals("http"))
651
        {//get the document from the internet
652
          String[] murlParams = murl.getParam(0);
653
          if(murlParams[0].equals("httpurl"))
654
          {//httpurl is the param name for an http url.
655
            URL urlconn = new URL(murlParams[1]);  //create a new url obj.
656
            DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
657
            //bind a data stream.
658
            try
659
            { //display the document
660
              String line=null;
661
              while((line = htmldoc.readLine()) != null)
662
              {
663
                out.println(line); 
664
              }
665
            }
666
            catch(Exception e)
667
            {
668
              util.debugMessage("error viewing html document"); 
669
            }
670
          }
671
        }
672
      }
673
      catch (McdbException e) {
674
        response.setContentType("text/xml");
675
        e.toXml(out);
676
      } catch   (Throwable t) {
677
        response.setContentType("text/html");
678
        out.println(t.getMessage());
679
      } finally {
680
        util.returnConnection(conn);
681
      }
682
    }
683
  }   
684
  
685
  /** 
686
   * Handle the database getdocument request and return a XML document, 
687
   * possibly transformed from XML into HTML
688
   */
689
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
690
               HttpServletResponse response) 
691
               throws ClassNotFoundException, IOException, SQLException {
692
    String docidstr = null;
693
    String docid = null;
694
    String doc = null;
695
    Connection conn = null;
696
    
697
    try {
698
      // Find the document id number
699
      docidstr = ((String[])params.get("docid"))[0]; 
700
      docid = docidstr;
701
      conn = util.getConnection();
702
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
703
      // Get the document indicated from the db
704
      //doc = docreader.readXMLDocument(docid);
705

    
706
      // Return the document in XML or HTML format
707
      String qformat=null;
708
      if(params.containsKey("qformat"))
709
      {
710
        qformat = ((String[])params.get("qformat"))[0];
711
      }
712
      else
713
      {
714
        qformat = "html";        
715
      }
716
      if (qformat.equals("xml")) { 
717
        // set content type and other response header fields first
718
        response.setContentType("text/xml");
719
        xmldoc.toXml(out);
720
        //out.println(xmldoc);
721
      } else if (qformat.equals("html")) {
722
        response.setContentType("text/html");
723
        // Look up the document type
724
        String sourcetype = xmldoc.getDoctype();
725
        // Transform the document to the new doctype
726
        DBTransform dbt = new DBTransform(conn);
727
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
728
                                 "-//W3C//HTML//EN", out);
729
      }
730
    } catch (McdbException e) {
731
      response.setContentType("text/xml");
732
      e.toXml(out);
733
    } catch (Throwable t) {
734
      response.setContentType("text/html");
735
      out.println(t.getMessage());
736
    } finally {
737
      util.returnConnection(conn);
738
    }    
739

    
740
  }
741

    
742
  /** 
743
   * Handle the database putdocument request and write an XML document 
744
   * to the database connection
745
   */
746
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
747
               HttpServletResponse response, String user, String group) {
748

    
749
    Connection conn = null;
750

    
751
    try {
752
      // Get the document indicated
753
      String[] doctext = (String[])params.get("doctext");
754
      StringReader xml = null;
755
      try {
756
        xml = new StringReader(doctext[0]);
757

    
758
        String[] action = (String[])params.get("action");
759
        String[] docid = (String[])params.get("docid");
760
        String newdocid = null;
761

    
762
        String doAction = null;
763
        if (action[0].equals("insert")) {
764
          doAction = "INSERT";
765
        } else if (action[0].equals("update")) {
766
          doAction = "UPDATE";
767
        }
768

    
769
        try {
770
            // get a connection from the pool
771
            conn = util.getConnection();
772

    
773
            // write the document to the database
774
            try {
775
                String accNumber = docid[0];
776
                if (accNumber.equals("")) {
777
                    accNumber = null;
778
                }
779
                newdocid = DocumentImpl.write(conn, xml, doAction, accNumber, 
780
                                                                  user, group);
781
            } catch (NullPointerException npe) {
782
              newdocid = DocumentImpl.write(conn,xml,doAction,null,user,group);
783
            }
784
        } catch (Exception e) {
785
          response.setContentType("text/html");
786
          out.println(e.getMessage());
787
        } finally {
788
          util.returnConnection(conn);
789
        }    
790

    
791
        // set content type and other response header fields first
792
        response.setContentType("text/xml");
793
        out.println("<?xml version=\"1.0\"?>");
794
        out.println("<success>");
795
        out.println("<docid>" + newdocid + "</docid>"); 
796
        out.println("</success>");
797

    
798
      } catch (NullPointerException npe) {
799
        response.setContentType("text/xml");
800
        out.println("<?xml version=\"1.0\"?>");
801
        out.println("<error>");
802
        out.println(npe.getMessage()); 
803
        out.println("</error>");
804
      }
805
    } catch (Exception e) {
806
      response.setContentType("text/xml");
807
      out.println("<?xml version=\"1.0\"?>");
808
      out.println("<error>");
809
      out.println(e.getMessage()); 
810
      if (e instanceof SAXException) {
811
        Exception e2 = ((SAXException)e).getException();
812
        out.println("<error>");
813
        out.println(e2.getMessage()); 
814
        out.println("</error>");
815
      }
816
      //e.printStackTrace(out);
817
      out.println("</error>");
818
    }
819
  }
820

    
821
  /** 
822
   * Handle the database delete request and delete an XML document 
823
   * from the database connection
824
   */
825
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
826
               HttpServletResponse response, String user, String group) {
827

    
828
    String[] docid = (String[])params.get("docid");
829
    Connection conn = null;
830

    
831
    // delete the document from the database
832
    try {
833
      // get a connection from the pool
834
      conn = util.getConnection();
835
                                      // NOTE -- NEED TO TEST HERE
836
                                      // FOR EXISTENCE OF DOCID PARAM
837
                                      // BEFORE ACCESSING ARRAY
838
      try { 
839
        DocumentImpl.delete(conn, docid[0], user, group);
840
        response.setContentType("text/xml");
841
        out.println("<?xml version=\"1.0\"?>");
842
        out.println("<success>");
843
        out.println("Document deleted."); 
844
        out.println("</success>");
845
      } catch (AccessionNumberException ane) {
846
        response.setContentType("text/xml");
847
        out.println("<?xml version=\"1.0\"?>");
848
        out.println("<error>");
849
        out.println("Error deleting document!!!");
850
        out.println(ane.getMessage()); 
851
        out.println("</error>");
852
      }
853
    } catch (Exception e) {
854
      response.setContentType("text/xml");
855
      out.println("<?xml version=\"1.0\"?>");
856
      out.println("<error>");
857
      out.println(e.getMessage()); 
858
      out.println("</error>");
859
    } finally {
860
      util.returnConnection(conn);
861
    }  
862
  }
863
  
864
  /** 
865
   * Handle the validation request and return the results to the requestor
866
   */
867
  private void handleValidateAction(PrintWriter out, Hashtable params, 
868
               HttpServletResponse response) {
869

    
870
    // Get the document indicated
871
    String valtext = null;
872
    
873
    try {
874
      valtext = ((String[])params.get("valtext"))[0];
875
    } catch (Exception nullpe) {
876

    
877
      Connection conn = null;
878
      String docid = null;
879
      try {
880
        // Find the document id number
881
        docid = ((String[])params.get("docid"))[0]; 
882

    
883
        // get a connection from the pool
884
        conn = util.getConnection();
885

    
886
        // Get the document indicated from the db
887
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
888
        valtext = xmldoc.toString();
889

    
890
      } catch (NullPointerException npe) {
891
        response.setContentType("text/xml");
892
        out.println("<error>Error getting document ID: " + docid + "</error>");
893
        if ( conn != null ) { util.returnConnection(conn); }
894
        return;
895
      } catch (Exception e) {
896
        response.setContentType("text/html");
897
        out.println(e.getMessage()); 
898
      } finally {
899
        util.returnConnection(conn);
900
      }  
901
    }
902

    
903
    Connection conn = null;
904
    try {
905
      // get a connection from the pool
906
      conn = util.getConnection();
907
      DBValidate valobj = new DBValidate(saxparser,conn);
908
      boolean valid = valobj.validateString(valtext);
909

    
910
      // set content type and other response header fields first
911
      response.setContentType("text/xml");
912
      out.println(valobj.returnErrors());
913

    
914
    } catch (NullPointerException npe2) {
915
      // set content type and other response header fields first
916
      response.setContentType("text/xml");
917
      out.println("<error>Error validating document.</error>"); 
918
    } catch (Exception e) {
919
      response.setContentType("text/html");
920
      out.println(e.getMessage()); 
921
    } finally {
922
      util.returnConnection(conn);
923
    }  
924
  }
925

    
926
  /** 
927
   * Handle the document request and return the results to the requestor
928
   */
929
  private void handleGetDataDocumentAction(PrintWriter out, Hashtable params, 
930
               HttpServletResponse response) {
931
      boolean error_flag = false;
932
      String error_message = "";
933
      // Get the document indicated
934
      String[] datadoc = (String[])params.get("datadoc");
935
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
936
      // executescript = "test.bat";        // for testing only!!!
937
      
938
      // set content type and other response header fields first
939
      response.setContentType("application/octet-stream");
940
      if (defaultdatapath!=null) {
941
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
942
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
943
        }
944
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
945
        if (executescript!=null) {
946
          String command = null;
947
          File scriptfile = new File(executescript);
948
          if (scriptfile.exists()) {
949
            command=executescript+" "+datadoc[0]; // script includes path
950
        } else {     // look in defaultdatapath
951
            // on Win98 one MUST include the .bat extender
952
            command = defaultdatapath+executescript+" "+datadoc[0];  
953
        }
954
      System.out.println(command);
955
      try {
956
      Process proc = Runtime.getRuntime().exec(command);
957
      proc.waitFor();
958
      }
959
      catch (Exception eee) {
960
        System.out.println("Error running process!");
961
        error_flag = true;
962
        error_message = "Error running process!";}
963
      } // end executescript not null if
964
      File datafile = new File(defaultdatapath+datadoc[0]);
965
      try {
966
      FileInputStream fw = new FileInputStream(datafile);
967
      int x;
968
      while ((x = fw.read())!=-1) {
969
        out.write(x); }
970
        fw.close();
971
      } catch (Exception e) {
972
        System.out.println("Error in returning file\n"+e.getMessage());
973
        error_flag=true;
974
        error_message = error_message+"\nError in returning file\n"+
975
                        e.getMessage();
976
      }
977
    } // end defaultdatapath not null if
978
  }
979
  
980
  /** 
981
   * Handle the getdoctypes Action.
982
   * Read all doctypes from db connection in XML format
983
   */
984
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
985
                                       HttpServletResponse response) {
986

    
987
    Connection conn = null;
988
    
989
    try {
990

    
991
        // get connection from the pool
992
        conn = util.getConnection();
993
        DBUtil dbutil = new DBUtil(conn);
994
        String doctypes = dbutil.readDoctypes();
995
        out.println(doctypes);
996

    
997
    } catch (Exception e) {
998
      out.println("<?xml version=\"1.0\"?>");
999
      out.println("<error>");
1000
      out.println(e.getMessage());
1001
      out.println("</error>");
1002
    } finally {
1003
      util.returnConnection(conn);
1004
    }  
1005
    
1006
  }
1007

    
1008
  /** 
1009
   * Handle the getdataguide Action.
1010
   * Read Data Guide for a given doctype from db connection in XML format
1011
   */
1012
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1013
                                        HttpServletResponse response) {
1014

    
1015
    Connection conn = null;
1016
    String doctype = null;
1017
    String[] doctypeArr = (String[])params.get("doctype");
1018

    
1019
    // get only the first doctype specified in the list of doctypes
1020
    // it could be done for all doctypes in that list
1021
    if (doctypeArr != null) {
1022
        doctype = ((String[])params.get("doctype"))[0]; 
1023
    }
1024

    
1025
    try {
1026

    
1027
        // get connection from the pool
1028
        conn = util.getConnection();
1029
        DBUtil dbutil = new DBUtil(conn);
1030
        String dataguide = dbutil.readDataGuide(doctype);
1031
        out.println(dataguide);
1032

    
1033
    } catch (Exception e) {
1034
      out.println("<?xml version=\"1.0\"?>");
1035
      out.println("<error>");
1036
      out.println(e.getMessage());
1037
      out.println("</error>");
1038
    } finally {
1039
      util.returnConnection(conn);
1040
    }  
1041
    
1042
  }
1043

    
1044
}
(19-19/27)