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: 2001-01-04 16:04:43 -0800 (Thu, 04 Jan 2001) $'
11
 * '$Revision: 636 $'
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.FileOutputStream;
24
import java.io.InputStreamReader;
25
import java.io.DataInputStream;
26
import java.util.Enumeration;
27
import java.util.Hashtable;
28
import java.util.ResourceBundle; 
29
import java.util.PropertyResourceBundle;
30
import java.net.URL;
31
import java.net.MalformedURLException;
32
import java.sql.PreparedStatement;
33
import java.sql.ResultSet;
34
import java.sql.Connection;
35
import java.sql.SQLException;
36
import java.lang.reflect.*;
37
import java.net.*;
38
import java.util.zip.*;
39

    
40
import javax.servlet.ServletConfig;
41
import javax.servlet.ServletContext;
42
import javax.servlet.ServletException;
43
import javax.servlet.ServletInputStream;
44
import javax.servlet.http.HttpServlet;
45
import javax.servlet.http.HttpServletRequest;
46
import javax.servlet.http.HttpServletResponse;
47
import javax.servlet.http.HttpSession;
48
import javax.servlet.http.HttpUtils;
49
import javax.servlet.ServletOutputStream;
50

    
51
import oracle.xml.parser.v2.XSLStylesheet;
52
import oracle.xml.parser.v2.XSLException;
53
import oracle.xml.parser.v2.XMLDocumentFragment;
54
import oracle.xml.parser.v2.XSLProcessor;
55

    
56
import org.xml.sax.SAXException;
57

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

    
90
  private ServletConfig config = null;
91
  private ServletContext context = null;
92
  private Hashtable connectionPool = new Hashtable();
93
  private String resultStyleURL = null;
94
  private String xmlcatalogfile = null;
95
  private String saxparser = null;
96
  private String defaultdatapath = null; 
97
  private String servletpath = null; 
98
  private PropertyResourceBundle options = null;
99
  private MetaCatUtil util = null;
100

    
101
  // path to directory where data files 
102
  // that can be downloaded will be stored
103
  private String htmlpath = null; 
104
  // script to get data file and put it 
105
  // in defaultdocpath dir
106
  private String executescript  = null;  
107

    
108
  /**
109
   * Initialize the servlet by creating appropriate database connections
110
   */
111
  public void init( ServletConfig config ) throws ServletException {
112
    try {
113
      super.init( config );
114
      this.config = config;
115
      this.context = config.getServletContext(); 
116
      System.out.println("MetaCatServlet Initialize");
117

    
118
      util = new MetaCatUtil();
119

    
120
      // Get the configuration file information
121
      resultStyleURL = util.getOption("resultStyleURL");
122
      xmlcatalogfile = util.getOption("xmlcatalogfile");
123
      saxparser = util.getOption("saxparser");
124
      defaultdatapath = util.getOption("defaultdatapath");
125
      executescript = util.getOption("executescript"); 
126
      servletpath = util.getOption("servletpath");
127
      htmlpath = util.getOption("htmlpath");
128

    
129
//      try {
130
//        // Open a pool of db connections
131
//        connectionPool = util.getConnectionPool();
132
//      } catch (Exception e) {
133
//        System.err.println("Error creating pool of database connections");
134
//        System.err.println(e.getMessage());
135
//      }
136
    } catch ( ServletException ex ) {
137
      throw ex;
138
    }
139
  }
140

    
141
  /**
142
   * Close all db connections from the pool
143
   */
144
  public void destroy() {
145
    
146
    if (util != null) {
147
        util.closeConnections();
148
    }
149
  }
150

    
151
  /** Handle "GET" method requests from HTTP clients */
152
  public void doGet (HttpServletRequest request, HttpServletResponse response)
153
    throws ServletException, IOException {
154

    
155
    // Process the data and send back the response
156
    handleGetOrPost(request, response);
157
  }
158

    
159
  /** Handle "POST" method requests from HTTP clients */
160
  public void doPost( HttpServletRequest request, HttpServletResponse response)
161
    throws ServletException, IOException {
162

    
163
    // Process the data and send back the response
164
    handleGetOrPost(request, response);
165
  }
166

    
167
  /**
168
   * Control servlet response depending on the action parameter specified
169
   */
170
  private void handleGetOrPost(HttpServletRequest request, 
171
    HttpServletResponse response) 
172
    throws ServletException, IOException 
173
 {
174

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

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

    
211
      //pwout.println(name + " => " + value[0]);
212
      params.put(name,value); 
213
    }  
214
    
215
    //if the user clicked on the input images, decode which image
216
    //was clicked then set the action.
217
    String action = ((String[])params.get("action"))[0];  
218
    util.debugMessage("Line 213: Action is: " + action);
219

    
220
    //MBJELIMINATE String action = decodeMouseAction(params);
221
    //if(action.equals("error"))
222
    //{
223
      //util.debugMessage("Line 218: Action is: " + action);
224
      //action = ((String[])params.get("action"))[0];  
225
    //}
226
    
227
    // This block handles session management for the servlet
228
    // by looking up the current session information for all actions
229
    // other than "login" and "logout"
230
    String username = null;
231
    String groupname = null;
232

    
233
    // handle login action
234
    if (action.equals("login")) {
235

    
236
      handleLoginAction(response.getWriter(), params, request, response);
237

    
238
    // handle logout action  
239
    } else if (action.equals("logout")) {
240

    
241
      handleLogoutAction(response.getWriter(), params, request, response);
242

    
243
    // aware of session expiration on every request  
244
    } else {   
245

    
246
      HttpSession sess = request.getSession(true);
247
      if (sess.isNew()) { 
248
        // session expired or has not been stored b/w user requests
249
        username = "public";
250
      } else {
251
        username = (String)sess.getAttribute("username");
252
        groupname = (String)sess.getAttribute("groupname");
253
      }  
254
    }    
255

    
256
    // Now that we know the session is valid, we can delegate the request
257
    // to a particular action handler
258
    if(action.equals("query"))
259
    {
260
      handleQuery(response.getWriter(), params, response, username, groupname); 
261
    } 
262
    else if(action.equals("squery"))
263
    {
264
      if(params.containsKey("query"))
265
      {
266
        handleSQuery(response.getWriter(), params, response, username, groupname); 
267
      }
268
      else
269
      {
270
        PrintWriter out = response.getWriter();
271
        out.println("Illegal action squery without \"query\" parameter");
272
      }
273
    }
274
    else if (action.equals("read")) {
275
      //PrintWriter out = response.getWriter();
276
      try {
277
        handleReadAction(/*out,*/ params, response);
278
      } catch (ClassNotFoundException e) {
279
        System.out.println(e.getMessage());
280
      } catch (SQLException se) {
281
        System.out.println(se.getMessage());
282
      }
283
    } 
284
/*
285
    else if (action.equals("getrelateddocument")) {
286
      PrintWriter out = response.getWriter();
287
      try {
288
        handleGetRelatedDocumentAction(out, params, response);
289
      } catch (ClassNotFoundException e) {
290
        out.println(e.getMessage());
291
      } catch (SQLException se) {
292
        out.println(se.getMessage());
293
      }
294
    }
295
*/
296
    else if (action.equals("insert") || action.equals("update")) {
297
      PrintWriter out = response.getWriter();
298
      if ( (username != null) &&  !username.equals("public") ) {
299
        handleInsertOrUpdateAction(out, params, response, username, groupname);
300
      } else {  
301
        out.println("Permission denied for " + action);
302
      }  
303
    } else if (action.equals("delete")) {
304
      PrintWriter out = response.getWriter();
305
      if ( (username != null) &&  !username.equals("public") ) {
306
        handleDeleteAction(out, params, response, username, groupname);
307
      } else {  
308
        out.println("Permission denied for " + action);
309
      }  
310
    } else if (action.equals("validate")) {
311
      PrintWriter out = response.getWriter();
312
      handleValidateAction(out, params, response); 
313
    } else if (action.equals("getabstract")) {
314
      PrintWriter out = response.getWriter();
315
      try{
316
        handleViewAbstractAction(out, params, response);
317
      }
318
      catch(Exception e)
319
      {
320
        out.println("error viewing abstract: " + e.getMessage());
321
      }
322
    } else if (action.equals("getdatadoc")) {
323
      response.setContentType("application/zip");
324
      ServletOutputStream out = response.getOutputStream();
325
      handleGetDataDocumentAction(out, params, response);  
326
    } else if (action.equals("getdoctypes")) {
327
      PrintWriter out = response.getWriter();
328
      handleGetDoctypesAction(out, params, response);  
329
    } else if (action.equals("getdataguide")) {
330
      PrintWriter out = response.getWriter();
331
      handleGetDataGuideAction(out, params, response);  
332
    } else if (action.equals("login") || action.equals("logout")) {
333
    } else if (action.equals("protocoltest")) {
334
      String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
335
      try {
336
        testURL = ((String[])params.get("url"))[0];
337
      } catch (Throwable t) {
338
      }
339
      String phandler = System.getProperty("java.protocol.handler.pkgs");
340
      response.setContentType("text/html");
341
      PrintWriter out = response.getWriter();
342
      out.println("<body bgcolor=\"white\">");
343
      out.println("<p>Handler property: <code>" + phandler + "</code></p>");
344
      out.println("<p>Starting test for:<br>");
345
      out.println("    " + testURL + "</p>");
346
      try {
347
        URL u = new URL(testURL);
348
        out.println("<pre>");
349
        out.println("Protocol: " + u.getProtocol());
350
        out.println("    Host: " + u.getHost());
351
        out.println("    Port: " + u.getPort());
352
        out.println("    Path: " + u.getPath());
353
        out.println("     Ref: " + u.getRef());
354
        String pquery = u.getQuery();
355
        out.println("   Query: " + pquery);
356
        out.println("  Params: ");
357
        if (pquery != null) {
358
          Hashtable qparams = util.parseQuery(u.getQuery());
359
          for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
360
            String pname = (String)en.nextElement();
361
            String pvalue = (String)qparams.get(pname);
362
            out.println("    " + pname + ": " + pvalue);
363
          }
364
        }
365
        out.println("</pre>");
366
        out.println("</body>");
367
        out.close();
368
      } catch (MalformedURLException mue) {
369
        out.println(mue.getMessage());
370
        mue.printStackTrace(out);
371
        out.close();
372
      }
373
    } else {
374
      PrintWriter out = response.getWriter();
375
      out.println("Error: action not registered.  Please report this error.");
376
    }
377
    util.closeConnections();
378
    // Close the stream to the client
379
    //out.close();
380
  }
381
  
382
  /**
383
   * decodes the mouse click information coming from the client.
384
   * This function may be overwritten to provide specific functionality
385
   * for different applications.
386
   * @param params the parameters from the CGI
387
   * @return action the action to be performed or "error" if an error was
388
   * generated
389
   */
390
  protected String decodeMouseAction(Hashtable params)
391
  {
392
    // Determine what type of request the user made
393
    // if the action parameter is set, use it as a default
394
    // but if the ypos param is set, calculate the action needed
395
    String action=null;
396
    long ypos = 0;
397
    try {
398
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
399
      //out.println("<P>YPOS IS " + ypos);
400
      if (ypos <= 13) {
401
        action = "read";
402
      } else if (ypos > 13 && ypos <= 27) {
403
        action = "validate";
404
      } else if (ypos > 27) {
405
        action = "transform";
406
      }
407
      return action;
408
    } catch (Exception npe) {
409
      //
410
      // MBJ -- NOTE that this should be handled more gracefully with
411
      //        the new exception infrastructure -- this "error" return
412
      //        value is inappropriate
413
      //out.println("<P>Caught exception looking for Y value.");
414
      return "error";
415
    }  
416
  }
417

    
418
  /** 
419
   * Handle the login request. Create a new session object.
420
   * Do user authentication through the session.
421
   */
422
  private void handleLoginAction(PrintWriter out, Hashtable params, 
423
               HttpServletRequest request, HttpServletResponse response) {
424

    
425
    AuthSession sess = null;
426
    String un = ((String[])params.get("username"))[0];
427
    String pw = ((String[])params.get("password"))[0];
428
    String action = ((String[])params.get("action"))[0];
429
    String qformat = ((String[])params.get("qformat"))[0];
430
    
431
    try {
432
      sess = new AuthSession();
433
    } catch (Exception e) {
434
      out.println(e.getMessage());
435
      return;
436
    }
437
    
438
    boolean isValid = sess.authenticate(request, un, pw);
439

    
440
    // format and transform the output
441
    if (qformat.equals("html")) {
442
      Connection conn = null;
443
      try {
444
        conn = util.getConnection();
445
        DBTransform trans = new DBTransform(conn);
446
        response.setContentType("text/html");
447
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
448
                                   "-//W3C//HTML//EN", out);
449
        util.returnConnection(conn); 
450
      } catch(Exception e) {
451
        util.returnConnection(conn); 
452
      } 
453
      
454
    // any output is returned  
455
    } else {
456
      response.setContentType("text/xml");
457
      out.println(sess.getMessage()); 
458
    }
459
        
460
/* WITHOUT XSLT transformation
461
    // redirects response to html page
462
    if (qformat.equals("html")) {
463
      // user authentication successful
464
      if (isValid) {
465
        response.sendRedirect(
466
                 response.encodeRedirectUrl(htmlpath + "/metacat.html"));
467
      // unsuccessful user authentication 
468
      } else {
469
        response.sendRedirect(htmlpath + "/login.html");
470
      }
471
    // any output is returned  
472
    } else {
473
      response.setContentType("text/xml");
474
      out.println(sess.getMessage()); 
475
    }
476
*/        
477

    
478
  }    
479

    
480
  /** 
481
   * Handle the logout request. Close the connection.
482
   */
483
  private void handleLogoutAction(PrintWriter out, Hashtable params, 
484
               HttpServletRequest request, HttpServletResponse response) {
485

    
486
    String qformat = ((String[])params.get("qformat"))[0];
487

    
488
    // close the connection
489
    HttpSession sess = request.getSession(false);
490
    if (sess != null) { sess.invalidate();  }    
491

    
492
    // produce output
493
    StringBuffer output = new StringBuffer();
494
    output.append("<?xml version=\"1.0\"?>");
495
    output.append("<logout>");
496
    output.append("User logged out");
497
    output.append("</logout>");
498

    
499
    //format and transform the output
500
    if (qformat.equals("html")) {
501
      Connection conn = null;
502
      try {
503
        conn = util.getConnection();
504
        DBTransform trans = new DBTransform(conn);
505
        response.setContentType("text/html");
506
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN", 
507
                                   "-//W3C//HTML//EN", out);
508
        util.returnConnection(conn); 
509
      } catch(Exception e) {
510
        util.returnConnection(conn); 
511
      } 
512
    // any output is returned  
513
    } else {
514
      response.setContentType("text/xml");
515
      out.println(output.toString()); 
516
    }
517

    
518
/* WITHOUT XSLT transformation
519
    // redirects response to html page
520
    if (qformat.equals("html")) {
521
        response.sendRedirect(htmlpath + "/index.html"); 
522
      } catch(Exception e) {
523
        util.returnConnection(conn); 
524
      } 
525
    // any output is returned  
526
    } else {
527
      response.setContentType("text/xml");
528
      out.println(output.toString()); 
529
    }
530
*/
531
  }
532

    
533
  
534
  /**      
535
   * Retreive the squery xml, execute it and display it
536
   *
537
   * @param out the output stream to the client
538
   * @param params the Hashtable of parameters that should be included
539
   * in the squery.
540
   * @param response the response object linked to the client
541
   * @param conn the database connection 
542
   */
543
  protected void handleSQuery(PrintWriter out, Hashtable params, 
544
                 HttpServletResponse response, String user, String group)
545
  { 
546
    String xmlquery = ((String[])params.get("query"))[0];
547
    String qformat = ((String[])params.get("qformat"))[0];
548
    String resultdoc = null;
549
    String[] returndoc = null;
550
    if(params.contains("returndoc"))
551
    {
552
      returndoc = (String[])params.get("returndoc");
553
    }
554
    
555
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
556
    //String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
557

    
558
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
559
    
560
    //format and transform the results                                        
561
    if(qformat.equals("html")) {
562
      transformResultset(resultdoc, response, out);
563
    } else if(qformat.equals("xml")) {
564
      response.setContentType("text/xml");
565
      out.println(resultdoc);
566
    } else {
567
      out.println("invalid qformat: " + qformat); 
568
    }
569
  }
570
  
571
   /**
572
    * Create the xml query, execute it and display the results.
573
    *
574
    * @param out the output stream to the client
575
    * @param params the Hashtable of parameters that should be included
576
    * in the squery.
577
    * @param response the response object linked to the client
578
    */ 
579
  protected void handleQuery(PrintWriter out, Hashtable params, 
580
                 HttpServletResponse response, String user, String group)
581
  {
582
    //create the query and run it
583
    String[] returndoc = null;
584
    if(params.containsKey("returndoc"))
585
    {
586
      returndoc = (String[])params.get("returndoc");
587
    }
588
    String xmlquery = DBQuery.createSQuery(params);
589
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
590
    String qformat = ((String[])params.get("qformat"))[0];
591
    String resultdoc = null;
592
    
593
    resultdoc = createResultDocument(doclist, transformQuery(params));
594

    
595
    //format and transform the results                                        
596
    if(qformat.equals("html")) {
597
      transformResultset(resultdoc, response, out);
598
    } else if(qformat.equals("xml")) {
599
      response.setContentType("text/xml");
600
      out.println(resultdoc);
601
    } else { 
602
      out.println("invalid qformat: " + qformat); 
603
    }
604
  }
605
  
606
  /**
607
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
608
   * so it can properly be placed in the <query> tag of the resultset.
609
   * This method is overwritable so that other applications can customize
610
   * the structure of what is in the <query> tag.
611
   * 
612
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
613
   */
614
  protected String transformQuery(Hashtable params)
615
  {
616
    //DBQuery.createSQuery is a re-calling of a previously called 
617
    //function but it is necessary
618
    //so that overriding methods have access to the params hashtable
619
    String xmlquery = DBQuery.createSQuery(params);
620
    //the <?xml version="1.0"?> tag is the first 22 characters of the
621
    xmlquery = xmlquery.trim();
622
    int index = xmlquery.indexOf("?>");
623
    return xmlquery.substring(index + 2, xmlquery.length());
624
  }
625
  
626
  /**
627
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
628
   * string as a param instead of a hashtable.
629
   * 
630
   * @param xmlquery a string representing a query.
631
   */
632
  protected String transformQuery(String xmlquery)
633
  {
634
    xmlquery = xmlquery.trim();
635
    int index = xmlquery.indexOf("?>");
636
    return xmlquery.substring(index + 2, xmlquery.length());
637
  }
638
  
639
  /**
640
   * Run the query and return a hashtable of results.
641
   *
642
   * @param xmlquery the query to run
643
   */
644
  private Hashtable runQuery(String xmlquery, String user, String group, 
645
                             String[] returndoc)
646
  {
647
    Hashtable doclist=null;
648
    Connection conn = null;
649
    try
650
    {
651
      conn = util.getConnection();
652
      DBQuery queryobj = new DBQuery(conn, saxparser);
653
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
654
                                       returndoc);
655
      util.returnConnection(conn);
656
      return doclist;
657
    } 
658
    catch (Exception e) 
659
    {
660
      util.returnConnection(conn); 
661
      util.debugMessage("Error in runQuery: " + e.getMessage());
662
      doclist = null;
663
      return doclist;
664
    }    
665
  }
666
  
667
  /**
668
   * Transorms an xml resultset document to html and sends it to the browser
669
   *
670
   * @param resultdoc the string representation of the document that needs
671
   * to be transformed.
672
   * @param response the HttpServletResponse object bound to the client.
673
   * @param out the output stream to the client
674
   */ 
675
  protected void transformResultset(String resultdoc, 
676
                                    HttpServletResponse response,
677
                                    PrintWriter out)
678
  {
679
    Connection conn = null;
680
    try {
681
      conn = util.getConnection();
682
      DBTransform trans = new DBTransform(conn);
683
      response.setContentType("text/html");
684
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
685
                                 "-//W3C//HTML//EN", out);
686
      util.returnConnection(conn); 
687
    }
688
    catch(Exception e)
689
    {
690
      util.returnConnection(conn); 
691
    } 
692
  }
693
  
694
  /**
695
   * Transforms a hashtable of documents to an xml or html result.
696
   * If there is a returndoc, then it only displays documents of
697
   * whatever type returndoc represents.  If a result is found in a document
698
   * that is not of type returndoc then this attempts to find a relation 
699
   * between this document and one that satifies the returndoc doctype.
700
   *
701
   * @param doclist- the hashtable to transform
702
   * @param xmlquery- the query that returned the dolist result
703
   * @param resultdoc- the document type to backtrack to.
704
   */
705
  protected String createResultDocument(Hashtable doclist, String xmlquery)
706
  {
707
    // Create a buffer to hold the xml result
708
    StringBuffer resultset = new StringBuffer();
709
 
710
    // Print the resulting root nodes 
711
    String docid = null;
712
    String document = null;
713
    resultset.append("<?xml version=\"1.0\"?>\n");
714
    resultset.append("<resultset>\n");
715
      
716
    resultset.append("  <query>" + xmlquery + "</query>");   
717

    
718
    if(doclist != null)
719
    {
720
      Enumeration doclistkeys = doclist.keys(); 
721
      while (doclistkeys.hasMoreElements()) 
722
      {
723
        docid = (String)doclistkeys.nextElement();
724
        document = (String)doclist.get(docid);
725
        resultset.append("  <document>" + document + "</document>");
726
      }
727
    }
728

    
729
    resultset.append("</resultset>");
730
    //System.out.println(resultset.toString());
731
    return resultset.toString();
732
  }
733
  
734
  /**
735
   * Handle the request to view the abstract of a document.
736
   * The abstractpath CGI parameter gives the xml path to the abstract
737
   * node.  
738
   */
739
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
740
               HttpServletResponse response) throws IOException, SQLException
741
  {
742
    String abstractpath = null;
743
    String docid = null;
744
    Connection conn = null;
745
    response.setContentType("text/html");
746
    try
747
    {
748
      docid = ((String[])params.get("docid"))[0];
749
      if(params.containsKey("abstractpath"))
750
      {
751
        //the CGI parameter abstractpath holds the path to the abstract
752
        //that should be displayed.
753
        abstractpath = ((String[])params.get("abstractpath"))[0];
754
      }
755
      else
756
      {
757
        out.println("error: no abstractpath parameter"); 
758
      }
759
      conn = util.getConnection();
760
    
761
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
762
    
763
      out.println("<html><head><title>Abstract</title></head>");
764
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
765
      for(int i=0; i<abstracts.length; i++)
766
      {
767
        out.println("<p>" + (String)abstracts[i] + "</p>");
768
      }
769
      out.println("</body></html>");
770
    }
771
    catch (IOException ioe)
772
    {
773
       util.debugMessage("error in handlegetabstract: " + ioe.getMessage());
774
    }
775
    catch(SQLException sqle)
776
    {
777
      util.debugMessage("error in handlegetabstract: " + sqle.getMessage()); 
778
    }
779
    catch(Exception e)
780
    {
781
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
782
    }
783
    
784
    util.returnConnection(conn);
785
  }
786

    
787
  /** 
788
   * Handle the database getrelateddocument request and return a XML document, 
789
   * possibly transformed from XML into HTML
790
   */
791
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params,
792
               HttpServletResponse response, URL murl) 
793
               throws ClassNotFoundException, IOException, SQLException 
794
  {
795
    String docid = null;
796
    Connection conn = null;
797
      
798
    //if(params.containsKey("url"))
799
    //{//the identifier for the related document is contained in the URL param
800
      try
801
      {
802
        DocumentImpl xmldoc=null;
803
        //MetacatURL murl = new MetacatURL(((String[])params.get("url"))[0]);
804
        if(murl.getProtocol().equals("metacat"))
805
        {//get the document from the database if it is the right type of url
806
          //Hashtable murlParams = murl.getHashParams();
807
          Hashtable murlParams = util.parseQuery(murl.getQuery());
808
          if(murlParams.containsKey("docid"))
809
          {//the docid should be first
810
            docid = (String)murlParams.get("docid"); //get the docid value
811
            conn = util.getConnection();
812
            xmldoc = new DocumentImpl(conn, docid);
813
            String qformat = ((String[])params.get("qformat"))[0];
814
            if (qformat.equals("xml")) 
815
            { 
816
              // set content type and other response header fields first
817
              response.setContentType("text/xml");
818
              xmldoc.toXml(out);
819
              //out.println(xmldoc);
820
            } 
821
            else if (qformat.equals("html")) 
822
            {
823
              response.setContentType("text/html");
824
              // Look up the document type
825
              String sourcetype = xmldoc.getDoctype();
826
              // Transform the document to the new doctype
827
              DBTransform dbt = new DBTransform(conn);
828
              dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
829
                                 "-//W3C//HTML//EN", out);
830
            }
831

    
832
            util.returnConnection(conn);
833
          }
834
          else
835
          {
836
            //throw new Exception("handleGetDocument: bad URL");
837
            System.err.println("handleGetDocument: bad URL");
838
          }
839
        }
840
        else if(murl.getProtocol().equals("http"))
841
        {//get the document from the internet
842
          //Hashtable murlParams = murl.getHashParams();
843
          Hashtable murlParams = util.parseQuery(murl.getQuery());
844
          if(murlParams.containsKey("httpurl"))
845
          {//httpurl is the param name for an http url.
846
            URL urlconn = new URL((String)murlParams.get("httpurl"));  
847
            //create a new url obj.
848
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
849
            BufferedReader htmldoc = new BufferedReader(
850
                                   new InputStreamReader(urlconn.openStream()));
851
            //bind a data stream.
852
            try
853
            { //display the document
854
              String line=null;
855
              while((line = htmldoc.readLine()) != null)
856
              {
857
                out.println(line); 
858
              }
859
            }
860
            catch(Exception e)
861
            {
862
              util.debugMessage("error viewing html document"); 
863
            }
864
          }
865
        }
866
      }
867
      catch (McdbException e) {
868
        response.setContentType("text/xml");
869
        e.toXml(out);
870
      } catch   (Throwable t) {
871
        response.setContentType("text/html");
872
        out.println(t.getMessage());
873
      } finally {
874
        util.returnConnection(conn);
875
      }
876
    //} // end if
877
  }   
878
  
879
  /** 
880
   * Handle the database read request and return an XML document, 
881
   * possibly transformed from XML into HTML
882
   */
883
  private void handleReadAction(/*PrintWriter out,*/ Hashtable params, 
884
               HttpServletResponse response) 
885
               throws ClassNotFoundException, IOException, SQLException 
886
  {
887
     PrintWriter out;
888
    try {
889
      //MetacatURL murl = new MetacatURL(((String[])params.get("docid"))[0]);
890
      if(params.containsKey(new String("qformat")) && 
891
         ((String[])params.get("qformat"))[0].equals("bin"))
892
      {
893
        handleGetData(params, response);
894
      }
895
      else
896
      {
897
        out = response.getWriter();
898
        URL murl = new URL(((String[])params.get("docid"))[0]);
899
        handleGetRelatedDocumentAction(out, params, response, murl);
900
      }
901
    } catch (MalformedURLException mue) {
902
      System.out.println("in catch");
903
      out = response.getWriter();
904
      handleGetDocumentAction(out, params, response);
905
    }
906
  }
907
  
908
  /**
909
   * Handle the read of a data file.
910
   */
911
  private void handleGetData(Hashtable params, 
912
                             HttpServletResponse response)
913
  {
914
    String docid = null;
915
    try
916
    {
917
      URL murl = new URL(((String[])params.get("docid"))[0]);
918
      Hashtable murlParams = util.parseQuery(murl.getQuery());
919
      if(murlParams.containsKey("docid"))
920
      {
921
        docid = ((String[])murlParams.get("docid"))[0];
922
      }
923
    }
924
    catch(MalformedURLException mue)
925
    {
926
      docid = ((String[])params.get("docid"))[0];
927
    }
928
    
929
    File f = null;
930
    FileInputStream fin = null;
931
    Connection conn;
932
    
933
    try
934
    {
935
      ServletOutputStream sosout = response.getOutputStream();
936
      response.setContentType("application/octet-stream");
937
      StringBuffer sql = new StringBuffer();
938
      sql.append("select docname from xml_documents where docid like '");
939
      sql.append(docid).append("'");
940
      conn = util.openDBConnection();
941
      PreparedStatement pstmt = conn.prepareStatement(sql.toString());
942
      pstmt.execute();
943
      ResultSet rs = pstmt.getResultSet();
944
      boolean tablehasrows = rs.next();
945
      while(tablehasrows)
946
      {
947
        //get the file stream from the file then send it to the output stream
948
        String filepath = util.getOption("datafilepath");
949
        if(!filepath.endsWith("/"))
950
        {
951
          filepath += "/";
952
        }
953
        f = new File(filepath + rs.getString(1)); 
954
        fin = new FileInputStream(f);
955
        int b = fin.read();
956
        while(b != -1)
957
        {
958
          sosout.write(b);
959
          b = fin.read();
960
        }
961
        tablehasrows = rs.next();
962
      }
963
      
964
      fin.close();
965
      conn.close();
966
    }
967
    catch(Exception e)
968
    {
969
      System.out.println("error in handleGetData: " + e.getMessage());
970
      e.printStackTrace(System.out);
971
    }
972
  }
973

    
974
  /** 
975
   * Handle the database read request and return an XML document, 
976
   * possibly transformed from XML into HTML
977
   */
978
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
979
               HttpServletResponse response) 
980
               throws ClassNotFoundException, IOException, SQLException {
981
    String docidstr = null;
982
    String docid = null;
983
    String doc = null;
984
    Connection conn = null;
985
    
986
    try {
987
      // Find the document id number
988
      docidstr = ((String[])params.get("docid"))[0]; 
989
      docid = docidstr;
990
      
991
      conn = util.getConnection();
992
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
993
      // Get the document indicated from the db
994
      //doc = docreader.readXMLDocument(docid);
995

    
996
      // Return the document in XML or HTML format
997
      String qformat=null;
998
      if(params.containsKey("qformat"))
999
      {
1000
        qformat = ((String[])params.get("qformat"))[0];
1001
      }
1002
      else
1003
      {
1004
        qformat = "html";        
1005
      }
1006
      if (qformat.equals("xml")) { 
1007
        // set content type and other response header fields first
1008
        response.setContentType("text/xml");
1009
        xmldoc.toXml(out);
1010
        //out.println(xmldoc);
1011
      } else if (qformat.equals("html")) {
1012
        response.setContentType("text/html");
1013
        // Look up the document type
1014
        String sourcetype = xmldoc.getDoctype();
1015
        // Transform the document to the new doctype
1016
        DBTransform dbt = new DBTransform(conn);
1017
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
1018
                                 "-//W3C//HTML//EN", out);
1019
      }
1020
    } catch (McdbException e) {
1021
      response.setContentType("text/xml");
1022
      e.toXml(out);
1023
    } catch (Throwable t) {
1024
      response.setContentType("text/html");
1025
      out.println(t.getMessage());
1026
    } finally {
1027
      util.returnConnection(conn);
1028
    }    
1029

    
1030
  }
1031

    
1032
  /** 
1033
   * Handle the database putdocument request and write an XML document 
1034
   * to the database connection
1035
   */
1036
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
1037
               HttpServletResponse response, String user, String group) {
1038

    
1039
    Connection conn = null;
1040

    
1041
    try {
1042
      // Get the document indicated
1043
      String[] doctext = (String[])params.get("doctext");
1044

    
1045
      StringReader acl = null;
1046
      if(params.containsKey("acltext"))
1047
      {
1048
        String[] acltext = (String[])params.get("acltext");
1049
        try {
1050
          if ( !acltext[0].equals("") ) {
1051
            acl = new StringReader(acltext[0]);
1052
          }
1053
        } catch (NullPointerException npe) {}
1054
      }
1055
      StringReader dtd = null;
1056
      if(params.containsKey("dtdtext"))
1057
      {
1058
        String[] dtdtext = (String[])params.get("dtdtext");
1059
        try {
1060
          if ( !dtdtext[0].equals("") ) {
1061
            dtd = new StringReader(dtdtext[0]);
1062
          }
1063
        } catch (NullPointerException npe) {}
1064
      }
1065
      
1066
      StringReader xml = null;
1067
      try {
1068
        xml = new StringReader(doctext[0]);
1069

    
1070
        String[] action = (String[])params.get("action");
1071
        String[] docid = (String[])params.get("docid");
1072
        String newdocid = null;
1073

    
1074
        String doAction = null;
1075
        if (action[0].equals("insert")) {
1076
          doAction = "INSERT";
1077
        } else if (action[0].equals("update")) {
1078
          doAction = "UPDATE";
1079
        }
1080

    
1081
        try {
1082
            // get a connection from the pool
1083
            conn = util.getConnection();
1084

    
1085
            // write the document to the database
1086
            try {
1087
                String accNumber = docid[0];
1088
                if (accNumber.equals("")) {
1089
                    accNumber = null;
1090
                }
1091
                newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1092
                                              accNumber, user, group);
1093
                
1094
            } catch (NullPointerException npe) {
1095
              newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1096
                                            null, user, group);
1097
            }
1098
//        } catch (Exception e) {
1099
//          response.setContentType("text/html");
1100
//          out.println(e.getMessage());
1101
        } finally {
1102
          util.returnConnection(conn);
1103
        }    
1104

    
1105
        // set content type and other response header fields first
1106
        response.setContentType("text/xml");
1107
        out.println("<?xml version=\"1.0\"?>");
1108
        out.println("<success>");
1109
        out.println("<docid>" + newdocid + "</docid>"); 
1110
        out.println("</success>");
1111

    
1112
      } catch (NullPointerException npe) {
1113
        response.setContentType("text/xml");
1114
        out.println("<?xml version=\"1.0\"?>");
1115
        out.println("<error>");
1116
        out.println(npe.getMessage()); 
1117
        out.println("</error>");
1118
      }
1119
    } catch (Exception e) {
1120
      response.setContentType("text/xml");
1121
      out.println("<?xml version=\"1.0\"?>");
1122
      out.println("<error>");
1123
      out.println(e.getMessage()); 
1124
      if (e instanceof SAXException) {
1125
        Exception e2 = ((SAXException)e).getException();
1126
        out.println("<error>");
1127
        out.println(e2.getMessage()); 
1128
        out.println("</error>");
1129
      }
1130
      //e.printStackTrace(out);
1131
      out.println("</error>");
1132
    }
1133
  }
1134

    
1135
  /** 
1136
   * Handle the database delete request and delete an XML document 
1137
   * from the database connection
1138
   */
1139
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1140
               HttpServletResponse response, String user, String group) {
1141

    
1142
    String[] docid = (String[])params.get("docid");
1143
    Connection conn = null;
1144

    
1145
    // delete the document from the database
1146
    try {
1147
      // get a connection from the pool
1148
      conn = util.getConnection();
1149
                                      // NOTE -- NEED TO TEST HERE
1150
                                      // FOR EXISTENCE OF DOCID PARAM
1151
                                      // BEFORE ACCESSING ARRAY
1152
      try { 
1153
        DocumentImpl.delete(conn, docid[0], user, group);
1154
        response.setContentType("text/xml");
1155
        out.println("<?xml version=\"1.0\"?>");
1156
        out.println("<success>");
1157
        out.println("Document deleted."); 
1158
        out.println("</success>");
1159
      } catch (AccessionNumberException ane) {
1160
        response.setContentType("text/xml");
1161
        out.println("<?xml version=\"1.0\"?>");
1162
        out.println("<error>");
1163
        out.println("Error deleting document!!!");
1164
        out.println(ane.getMessage()); 
1165
        out.println("</error>");
1166
      }
1167
    } catch (Exception e) {
1168
      response.setContentType("text/xml");
1169
      out.println("<?xml version=\"1.0\"?>");
1170
      out.println("<error>");
1171
      out.println(e.getMessage()); 
1172
      out.println("</error>");
1173
    } finally {
1174
      util.returnConnection(conn);
1175
    }  
1176
  }
1177
  
1178
  /** 
1179
   * Handle the validation request and return the results to the requestor
1180
   */
1181
  private void handleValidateAction(PrintWriter out, Hashtable params, 
1182
               HttpServletResponse response) {
1183

    
1184
    // Get the document indicated
1185
    String valtext = null;
1186
    
1187
    try {
1188
      valtext = ((String[])params.get("valtext"))[0];
1189
    } catch (Exception nullpe) {
1190

    
1191
      Connection conn = null;
1192
      String docid = null;
1193
      try {
1194
        // Find the document id number
1195
        docid = ((String[])params.get("docid"))[0]; 
1196

    
1197
        // get a connection from the pool
1198
        conn = util.getConnection();
1199

    
1200
        // Get the document indicated from the db
1201
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1202
        valtext = xmldoc.toString();
1203

    
1204
      } catch (NullPointerException npe) {
1205
        response.setContentType("text/xml");
1206
        out.println("<error>Error getting document ID: " + docid + "</error>");
1207
        if ( conn != null ) { util.returnConnection(conn); }
1208
        return;
1209
      } catch (Exception e) {
1210
        response.setContentType("text/html");
1211
        out.println(e.getMessage()); 
1212
      } finally {
1213
        util.returnConnection(conn);
1214
      }  
1215
    }
1216

    
1217
    Connection conn = null;
1218
    try {
1219
      // get a connection from the pool
1220
      conn = util.getConnection();
1221
      DBValidate valobj = new DBValidate(saxparser,conn);
1222
      boolean valid = valobj.validateString(valtext);
1223

    
1224
      // set content type and other response header fields first
1225
      response.setContentType("text/xml");
1226
      out.println(valobj.returnErrors());
1227

    
1228
    } catch (NullPointerException npe2) {
1229
      // set content type and other response header fields first
1230
      response.setContentType("text/xml");
1231
      out.println("<error>Error validating document.</error>"); 
1232
    } catch (Exception e) {
1233
      response.setContentType("text/html");
1234
      out.println(e.getMessage()); 
1235
    } finally {
1236
      util.returnConnection(conn);
1237
    }  
1238
  }
1239

    
1240
  /** 
1241
   * Handle the document request and return the results to the requestor
1242
   * If a docid is passed in through the params then that document
1243
   * will be retrieved form the DB and put in the zip file.
1244
   * In addition if 1 or more relations parameters are passed, those file
1245
   * will be zipped as well.  Currently this is only implemented for 
1246
   * metacat:// and http:// files.  Support should be added for srb:// files
1247
   * as well.
1248
   */
1249
  private void handleGetDataDocumentAction(ServletOutputStream out, 
1250
               Hashtable params, 
1251
               HttpServletResponse response) {
1252
  //find the related files, get them from their source and zip them into 
1253
  //a zip file.
1254
  try
1255
  {
1256
    Connection conn = util.getConnection();
1257
    String currentDocid = ((String[])params.get("docid"))[0];
1258
    ZipOutputStream zout = new ZipOutputStream(out);
1259
    byte[] bytestring = null;
1260
    ZipEntry zentry = null;
1261
    DocumentImpl xmldoc = null;
1262
    String[] reldocs = null;
1263
    
1264
    if(params.containsKey("relation"))
1265
    { //get the relations from the parameters.
1266
      reldocs = ((String[])params.get("relation"));
1267
    }
1268
    else
1269
    { //let the for loop know that there are no relations to zip
1270
      reldocs = new String[0];
1271
    }
1272

    
1273
    //write the base file to the zip file.
1274
    xmldoc = new DocumentImpl(conn, currentDocid);
1275
    bytestring = (xmldoc.toString()).getBytes();
1276
    zentry = new ZipEntry(currentDocid + ".xml");
1277
    //create a new zip entry and write the file to the stream
1278
    zentry.setSize(bytestring.length);
1279
    zout.putNextEntry(zentry);
1280
    zout.write(bytestring, 0, bytestring.length);
1281
    zout.closeEntry(); //get ready for the next entry. 
1282

    
1283
    //zip up the related documents
1284
    for(int i=0; i<reldocs.length; i++)
1285
    {
1286
      //MetacatURL murl = new MetacatURL(((String)reldocs[i]));
1287
      URL murl = new URL(((String)reldocs[i]));
1288
      Hashtable qparams = util.parseQuery(murl.getQuery());
1289
      if(murl.getProtocol().equals("metacat"))
1290
      {
1291
        //get the document from the database
1292
        //xmldoc = new DocumentImpl(conn, (String)murl.getHashParam("docid"));
1293
        xmldoc = new DocumentImpl(conn, (String)qparams.get("docid"));
1294
        bytestring = (xmldoc.toString()).getBytes();
1295
        zentry = new ZipEntry(qparams.get("docid") + ".xml");
1296
        //create a new zip entry and write the file to the stream
1297
        zentry.setSize(bytestring.length);
1298
        zout.putNextEntry(zentry);
1299
        zout.write(bytestring, 0, bytestring.length);
1300
        zout.closeEntry(); //get ready for the next entry.
1301
      }
1302
      else if(murl.getProtocol().equals("http"))
1303
      {
1304
        //Hashtable murlParams = murl.getHashParams();
1305
        if(qparams.containsKey("httpurl"))
1306
        {//httpurl is the param name for an http url.
1307
          URL urlconn = new URL((String)qparams.get("httpurl"));  
1308
          //create a new url obj.
1309
          BufferedReader htmldoc = new BufferedReader(
1310
                                   new InputStreamReader(urlconn.openStream()));
1311
          //get the data from the web server
1312
          try
1313
          { //zip the document
1314
            String line=null;
1315
            zentry = new ZipEntry((String)qparams.get("filename"));
1316
            //get just the filename from the URL.
1317
            zout.putNextEntry(zentry);
1318
            //make a new entry in the zip file stream
1319
            while((line = htmldoc.readLine()) != null)
1320
            {
1321
              bytestring = (line.toString()).getBytes();
1322
              zout.write(bytestring, 0, bytestring.length);
1323
              //write out the file line by line
1324
            }
1325
            zout.closeEntry(); //close the entry in the file
1326
          }
1327
          catch(Exception e)
1328
          {
1329
            util.debugMessage("error downloading html document"); 
1330
          }
1331
        }
1332
      }
1333
    }
1334
    zout.finish();  //terminate the zip file
1335
    zout.close();   //close the stream.
1336
    util.returnConnection(conn); //return the connection to the pool
1337
  }
1338
  catch(Exception e)
1339
  {
1340
    System.out.println("Error creating zip file: " + e.getMessage()); 
1341
    e.printStackTrace(System.out);
1342
  }
1343
           
1344
   /*
1345
   //////////old code using a shell script/////////////////////////////////
1346
   
1347
      boolean error_flag = false;
1348
      String error_message = "";
1349
      // Get the document indicated
1350
      String[] datadoc = (String[])params.get("datadoc");
1351
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1352
      // executescript = "test.bat";        // for testing only!!!
1353
      
1354
      // set content type and other response header fields first
1355
      response.setContentType("application/octet-stream");
1356
      if (defaultdatapath!=null) {
1357
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1358
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1359
        }
1360
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1361
        if (executescript!=null) {
1362
          String command = null;
1363
          File scriptfile = new File(executescript);
1364
          if (scriptfile.exists()) {
1365
            command=executescript+" "+datadoc[0]; // script includes path
1366
        } else {     // look in defaultdatapath
1367
            // on Win98 one MUST include the .bat extender
1368
            command = defaultdatapath+executescript+" "+datadoc[0];  
1369
        }
1370
      System.out.println(command);
1371
      try {
1372
      Process proc = Runtime.getRuntime().exec(command);
1373
      proc.waitFor();
1374
      }
1375
      catch (Exception eee) {
1376
        System.out.println("Error running process!");
1377
        error_flag = true;
1378
        error_message = "Error running process!";}
1379
      } // end executescript not null if
1380
      File datafile = new File(defaultdatapath+datadoc[0]);
1381
      try {
1382
      FileInputStream fw = new FileInputStream(datafile);
1383
      int x;
1384
      while ((x = fw.read())!=-1) {
1385
        out.write(x); }
1386
        fw.close();
1387
      } catch (Exception e) {
1388
        System.out.println("Error in returning file\n"+e.getMessage());
1389
        error_flag=true;
1390
        error_message = error_message+"\nError in returning file\n"+
1391
                        e.getMessage();
1392
      }
1393
    } // end defaultdatapath not null if
1394
    */
1395
  }
1396
  
1397
  /** 
1398
   * Handle the getdoctypes Action.
1399
   * Read all doctypes from db connection in XML format
1400
   */
1401
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1402
                                       HttpServletResponse response) {
1403

    
1404
    Connection conn = null;
1405
    
1406
    try {
1407

    
1408
        // get connection from the pool
1409
        conn = util.getConnection();
1410
        DBUtil dbutil = new DBUtil(conn);
1411
        String doctypes = dbutil.readDoctypes();
1412
        out.println(doctypes);
1413

    
1414
    } catch (Exception e) {
1415
      out.println("<?xml version=\"1.0\"?>");
1416
      out.println("<error>");
1417
      out.println(e.getMessage());
1418
      out.println("</error>");
1419
    } finally {
1420
      util.returnConnection(conn);
1421
    }  
1422
    
1423
  }
1424

    
1425
  /** 
1426
   * Handle the getdataguide Action.
1427
   * Read Data Guide for a given doctype from db connection in XML format
1428
   */
1429
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1430
                                        HttpServletResponse response) {
1431

    
1432
    Connection conn = null;
1433
    String doctype = null;
1434
    String[] doctypeArr = (String[])params.get("doctype");
1435

    
1436
    // get only the first doctype specified in the list of doctypes
1437
    // it could be done for all doctypes in that list
1438
    if (doctypeArr != null) {
1439
        doctype = ((String[])params.get("doctype"))[0]; 
1440
    }
1441

    
1442
    try {
1443

    
1444
        // get connection from the pool
1445
        conn = util.getConnection();
1446
        DBUtil dbutil = new DBUtil(conn);
1447
        String dataguide = dbutil.readDataGuide(doctype);
1448
        out.println(dataguide);
1449

    
1450
    } catch (Exception e) {
1451
      out.println("<?xml version=\"1.0\"?>");
1452
      out.println("<error>");
1453
      out.println(e.getMessage());
1454
      out.println("</error>");
1455
    } finally {
1456
      util.returnConnection(conn);
1457
    }  
1458
    
1459
  }
1460

    
1461
}
(28-28/39)