Project

General

Profile

1 51 jones
/**
2 203 jones
 *  '$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 361 berkley
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7 348 jones
 *    Release: @release@
8 154 jones
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 51 jones
 */
13
14
package edu.ucsb.nceas.metacat;
15
16 46 jones
import java.io.PrintWriter;
17
import java.io.IOException;
18 50 jones
import java.io.Reader;
19
import java.io.StringReader;
20 59 jones
import java.io.BufferedReader;
21 185 jones
import java.io.File;
22
import java.io.FileInputStream;
23 458 berkley
import java.io.FileOutputStream;
24
import java.io.InputStreamReader;
25 453 berkley
import java.io.DataInputStream;
26 46 jones
import java.util.Enumeration;
27
import java.util.Hashtable;
28 341 berkley
import java.util.ResourceBundle;
29 82 jones
import java.util.PropertyResourceBundle;
30 50 jones
import java.net.URL;
31
import java.net.MalformedURLException;
32 85 jones
import java.sql.PreparedStatement;
33
import java.sql.ResultSet;
34 50 jones
import java.sql.Connection;
35 55 jones
import java.sql.SQLException;
36 361 berkley
import java.lang.reflect.*;
37 453 berkley
import java.net.*;
38 458 berkley
import java.util.zip.*;
39 46 jones
40
import javax.servlet.ServletConfig;
41
import javax.servlet.ServletContext;
42
import javax.servlet.ServletException;
43 48 jones
import javax.servlet.ServletInputStream;
44 46 jones
import javax.servlet.http.HttpServlet;
45
import javax.servlet.http.HttpServletRequest;
46
import javax.servlet.http.HttpServletResponse;
47 210 bojilova
import javax.servlet.http.HttpSession;
48 47 jones
import javax.servlet.http.HttpUtils;
49 458 berkley
import javax.servlet.ServletOutputStream;
50 46 jones
51 50 jones
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 204 jones
import org.xml.sax.SAXException;
57
58 46 jones
/**
59
 * A metadata catalog server implemented as a Java Servlet
60 154 jones
 *
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 205 jones
 * 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=getdocument -- display an XML document in XML or HTML<br>
70
 * doctype -- document type list returned by the query (publicID)<br>
71 154 jones
 * 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 205 jones
 * doctext -- XML text of the document to load into the database<br>
75 183 jones
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
76 205 jones
 * valtext -- XML text to be validated<br>
77
 * action=getdatadoc -- retreive a stored datadocument<br>
78 302 bojilova
 * action=getdoctypes -- retreive all doctypes (publicID)<br>
79
 * action=getdataguide -- retreive a Data Guide<br>
80 205 jones
 * datadoc -- data document name (id)<br>
81
 * <p>
82
 * The particular combination of parameters that are valid for each
83
 * particular action value is quite specific.  This documentation
84
 * will be reorganized to reflect this information.
85 46 jones
 */
86
public class MetaCatServlet extends HttpServlet {
87
88 370 berkley
  private ServletConfig config = null;
89
  private ServletContext context = null;
90
  private Hashtable connectionPool = new Hashtable();
91
  private String resultStyleURL = null;
92
  private String xmlcatalogfile = null;
93
  private String saxparser = null;
94
  private String defaultdatapath = null;
95
  private String servletpath = null;
96 380 jones
  private PropertyResourceBundle options = null;
97
  private MetaCatUtil util = null;
98
99
  // path to directory where data files
100
  // that can be downloaded will be stored
101 370 berkley
  private String htmlpath = null;
102 380 jones
  // script to get data file and put it
103
  // in defaultdocpath dir
104 370 berkley
  private String executescript  = null;
105 46 jones
106 50 jones
  /**
107
   * Initialize the servlet by creating appropriate database connections
108
   */
109 46 jones
  public void init( ServletConfig config ) throws ServletException {
110
    try {
111
      super.init( config );
112
      this.config = config;
113 332 bojilova
      this.context = config.getServletContext();
114 184 jones
      System.out.println("MetaCatServlet Initialize");
115 82 jones
116 184 jones
      util = new MetaCatUtil();
117
118 83 jones
      // Get the configuration file information
119 184 jones
      resultStyleURL = util.getOption("resultStyleURL");
120
      xmlcatalogfile = util.getOption("xmlcatalogfile");
121
      saxparser = util.getOption("saxparser");
122
      defaultdatapath = util.getOption("defaultdatapath");
123
      executescript = util.getOption("executescript");
124 360 bojilova
      servletpath = util.getOption("servletpath");
125
      htmlpath = util.getOption("htmlpath");
126 82 jones
127 46 jones
      try {
128 309 bojilova
        // Open a pool of db connections
129
        connectionPool = util.getConnectionPool();
130
      } catch (Exception e) {
131
        System.err.println("Error creating pool of database connections");
132
        System.err.println(e.getMessage());
133
      }
134 46 jones
    } catch ( ServletException ex ) {
135
      throw ex;
136
    }
137
  }
138
139 320 bojilova
  /**
140
   * Close all db connections from the pool
141
   */
142
  public void destroy() {
143
144
    if (util != null) {
145
        util.closeConnections();
146
    }
147
  }
148
149 50 jones
  /** Handle "GET" method requests from HTTP clients */
150 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
151
    throws ServletException, IOException {
152
153 48 jones
    // Process the data and send back the response
154 59 jones
    handleGetOrPost(request, response);
155 48 jones
  }
156
157 50 jones
  /** Handle "POST" method requests from HTTP clients */
158 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
159
    throws ServletException, IOException {
160
161
    // Process the data and send back the response
162 59 jones
    handleGetOrPost(request, response);
163 48 jones
  }
164
165 49 jones
  /**
166 50 jones
   * Control servlet response depending on the action parameter specified
167 49 jones
   */
168 382 berkley
  private void handleGetOrPost(HttpServletRequest request,
169 59 jones
    HttpServletResponse response)
170 355 berkley
    throws ServletException, IOException
171
 {
172 48 jones
173 309 bojilova
    if ( util == null ) {
174
        util = new MetaCatUtil();
175
    }
176
    if ( connectionPool == null ) {
177
      try {
178
        // Open a pool of db connections
179
        connectionPool = util.getConnectionPool();
180
      } catch (Exception e) {
181
        System.err.println("Error creating pool of database connections");
182
        System.err.println(e.getMessage());
183
      }
184
    }
185 49 jones
    // Get a handle to the output stream back to the client
186 458 berkley
    //PrintWriter out = response.getWriter();
187 102 jones
    //response.setContentType("text/html");
188 49 jones
189 59 jones
    String name = null;
190
    String[] value = null;
191 103 jones
    String[] docid = new String[3];
192 59 jones
    Hashtable params = new Hashtable();
193
    Enumeration paramlist = request.getParameterNames();
194
    while (paramlist.hasMoreElements()) {
195
      name = (String)paramlist.nextElement();
196
      value = request.getParameterValues(name);
197 103 jones
198
      // Decode the docid and mouse click information
199
      if (name.endsWith(".y")) {
200
        docid[0] = name.substring(0,name.length()-2);
201
        //out.println("docid => " + docid[0]);
202
        params.put("docid", docid);
203
        name = "ypos";
204
      }
205
      if (name.endsWith(".x")) {
206
        name = "xpos";
207 373 berkley
      }
208 103 jones
209 102 jones
      //out.println(name + " => " + value[0]);
210 373 berkley
      params.put(name,value);
211
    }
212 355 berkley
213 509 bojilova
    //if the user clicked on the input images, decode which image
214
    //was clicked then set the action.
215 505 jones
    String action = ((String[])params.get("action"))[0];
216
    util.debugMessage("Line 213: Action is: " + action);
217 509 bojilova
218 505 jones
    //MBJELIMINATE String action = decodeMouseAction(params);
219
    //if(action.equals("error"))
220
    //{
221 509 bojilova
      //util.debugMessage("Line 218: Action is: " + action);
222 505 jones
      //action = ((String[])params.get("action"))[0];
223
    //}
224 355 berkley
225 380 jones
    // This block handles session management for the servlet
226
    // by looking up the current session information for all actions
227 509 bojilova
    // other than "login" and "logout"
228 425 bojilova
    String username = null;
229
    String groupname = null;
230 509 bojilova
231
    // handle login action
232
    if (action.equals("login")) {
233
234 458 berkley
      handleLoginAction(response.getWriter(), params, request, response);
235 509 bojilova
236 210 bojilova
    // handle logout action
237 509 bojilova
    } else if (action.equals("logout")) {
238 361 berkley
239 509 bojilova
      handleLogoutAction(response.getWriter(), params, request, response);
240 361 berkley
241 251 bojilova
    // aware of session expiration on every request
242 343 jones
    } else {
243 509 bojilova
244 332 bojilova
      HttpSession sess = request.getSession(true);
245
      if (sess.isNew()) {
246 251 bojilova
        // session expired or has not been stored b/w user requests
247 441 bojilova
        username = "public";
248 425 bojilova
      } else {
249
        username = (String)sess.getAttribute("username");
250
        groupname = (String)sess.getAttribute("groupname");
251
      }
252 210 bojilova
    }
253 219 jones
254 380 jones
    // Now that we know the session is valid, we can delegate the request
255
    // to a particular action handler
256 361 berkley
    if(action.equals("query"))
257
    {
258 458 berkley
      handleQuery(response.getWriter(), params, response, username, groupname);
259 373 berkley
    }
260 371 berkley
    else if(action.equals("squery"))
261 361 berkley
    {
262 373 berkley
      if(params.containsKey("query"))
263
      {
264 458 berkley
        handleSQuery(response.getWriter(), params, response, username, groupname);
265 373 berkley
      }
266
      else
267
      {
268 458 berkley
        PrintWriter out = response.getWriter();
269 373 berkley
        out.println("Illegal action squery without \"query\" parameter");
270
      }
271
    }
272 361 berkley
    else if (action.equals("getdocument")) {
273 458 berkley
      PrintWriter out = response.getWriter();
274 87 jones
      try {
275
        handleGetDocumentAction(out, params, response);
276
      } catch (ClassNotFoundException e) {
277 103 jones
        out.println(e.getMessage());
278 87 jones
      } catch (SQLException se) {
279 103 jones
        out.println(se.getMessage());
280 87 jones
      }
281 453 berkley
    }
282
    else if (action.equals("getrelateddocument")) {
283 458 berkley
      PrintWriter out = response.getWriter();
284 453 berkley
      try {
285
        handleGetRelatedDocumentAction(out, params, response);
286
      } catch (ClassNotFoundException e) {
287
        out.println(e.getMessage());
288
      } catch (SQLException se) {
289
        out.println(se.getMessage());
290
      }
291
    }
292
    else if (action.equals("insert") || action.equals("update")) {
293 458 berkley
      PrintWriter out = response.getWriter();
294 509 bojilova
      if ( (username != null) &&  !username.equals("public") ) {
295 425 bojilova
        handleInsertOrUpdateAction(out, params, response, username, groupname);
296
      } else {
297
        out.println("Permission denied for " + action);
298
      }
299 203 jones
    } else if (action.equals("delete")) {
300 458 berkley
      PrintWriter out = response.getWriter();
301 509 bojilova
      if ( (username != null) &&  !username.equals("public") ) {
302 425 bojilova
        handleDeleteAction(out, params, response, username, groupname);
303
      } else {
304
        out.println("Permission denied for " + action);
305
      }
306 68 higgins
    } else if (action.equals("validate")) {
307 458 berkley
      PrintWriter out = response.getWriter();
308 437 berkley
      handleValidateAction(out, params, response);
309
    } else if (action.equals("getabstract")) {
310 458 berkley
      PrintWriter out = response.getWriter();
311 437 berkley
      try{
312
        handleViewAbstractAction(out, params, response);
313
      }
314
      catch(Exception e)
315
      {
316
        out.println("error viewing abstract: " + e.getMessage());
317
      }
318 91 higgins
    } else if (action.equals("getdatadoc")) {
319 458 berkley
      response.setContentType("application/zip");
320
      ServletOutputStream out = response.getOutputStream();
321 91 higgins
      handleGetDataDocumentAction(out, params, response);
322 302 bojilova
    } else if (action.equals("getdoctypes")) {
323 458 berkley
      PrintWriter out = response.getWriter();
324 302 bojilova
      handleGetDoctypesAction(out, params, response);
325
    } else if (action.equals("getdataguide")) {
326 458 berkley
      PrintWriter out = response.getWriter();
327 302 bojilova
      handleGetDataGuideAction(out, params, response);
328 509 bojilova
    } else if (action.equals("login") || action.equals("logout")) {
329 50 jones
    } else {
330 458 berkley
      PrintWriter out = response.getWriter();
331 50 jones
      out.println("Error: action not registered.  Please report this error.");
332 46 jones
    }
333 465 berkley
    util.closeConnections();
334 49 jones
    // Close the stream to the client
335 458 berkley
    //out.close();
336 46 jones
  }
337 355 berkley
338
  /**
339
   * decodes the mouse click information coming from the client.
340
   * This function may be overwritten to provide specific functionality
341
   * for different applications.
342
   * @param params the parameters from the CGI
343
   * @return action the action to be performed or "error" if an error was
344
   * generated
345
   */
346 375 berkley
  protected String decodeMouseAction(Hashtable params)
347 355 berkley
  {
348
    // Determine what type of request the user made
349
    // if the action parameter is set, use it as a default
350
    // but if the ypos param is set, calculate the action needed
351
    String action=null;
352
    long ypos = 0;
353
    try {
354
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
355
      //out.println("<P>YPOS IS " + ypos);
356
      if (ypos <= 13) {
357
        action = "getdocument";
358
      } else if (ypos > 13 && ypos <= 27) {
359
        action = "validate";
360
      } else if (ypos > 27) {
361
        action = "transform";
362
      }
363
      return action;
364
    } catch (Exception npe) {
365 380 jones
      //
366
      // MBJ -- NOTE that this should be handled more gracefully with
367
      //        the new exception infrastructure -- this "error" return
368
      //        value is inappropriate
369 355 berkley
      //out.println("<P>Caught exception looking for Y value.");
370
      return "error";
371 382 berkley
    }
372 355 berkley
  }
373 49 jones
374 50 jones
  /**
375 509 bojilova
   * Handle the login request. Create a new session object.
376 503 bojilova
   * Do user authentication through the session.
377 210 bojilova
   */
378
  private void handleLoginAction(PrintWriter out, Hashtable params,
379
               HttpServletRequest request, HttpServletResponse response) {
380 251 bojilova
381 503 bojilova
    AuthSession sess = null;
382 228 bojilova
    String un = ((String[])params.get("username"))[0];
383
    String pw = ((String[])params.get("password"))[0];
384 297 bojilova
    String action = ((String[])params.get("action"))[0];
385 509 bojilova
    String qformat = ((String[])params.get("qformat"))[0];
386 332 bojilova
387 297 bojilova
    try {
388 509 bojilova
      sess = new AuthSession();
389 297 bojilova
    } catch (Exception e) {
390
      out.println(e.getMessage());
391 509 bojilova
      return;
392 297 bojilova
    }
393 411 bojilova
394 509 bojilova
    boolean isValid = sess.authenticate(request, un, pw);
395
396
    // format and transform the output
397
    if (qformat.equals("html")) {
398
      Connection conn = null;
399 503 bojilova
      try {
400 509 bojilova
        conn = util.getConnection();
401
        DBTransform trans = new DBTransform(conn);
402
        response.setContentType("text/html");
403
        // user authentication successful
404 503 bojilova
        if (isValid) {
405 509 bojilova
        //  trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
406
        //                             "-//W3C//HTML//EN", out);
407
          response.sendRedirect(
408 503 bojilova
                   response.encodeRedirectUrl(htmlpath + "/metacat.html"));
409 509 bojilova
410
        // unsuccessful user authentication
411 503 bojilova
        } else {
412 509 bojilova
        //  trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//nologin//EN",
413
        //                             "-//W3C//HTML//EN", out);
414
          response.sendRedirect(htmlpath + "/login.html");
415 503 bojilova
        }
416 509 bojilova
        util.returnConnection(conn);
417
      } catch(Exception e) {
418
        util.returnConnection(conn);
419
      }
420
421
    // any output is returned
422
    } else {
423
      response.setContentType("text/xml");
424
      out.println(sess.getMessage());
425 503 bojilova
    }
426 509 bojilova
427
//    if (action.equals("Login Client")) {
428
//      out.println(sess.getMessage());
429
//    } else {
430
//      try {
431
//        if (isValid) {
432
//          if (un.equals("public")) {
433
//            response.sendRedirect(
434
//                   response.encodeRedirectUrl(htmlpath + "/index.html"));
435
//          } else {
436
//            response.sendRedirect(
437
//                   response.encodeRedirectUrl(htmlpath + "/metacat.html"));
438
//          }
439
//        } else {
440
//          response.sendRedirect(htmlpath + "/login.html");
441
//        }
442
//      } catch ( java.io.IOException ioe) {
443
//        String message = "handleLoginAction() - " +
444
//                    "Error on redirect of HttpServletResponse: " +
445
//                    ioe.getMessage();
446
//        out.println(message);
447
//      }
448
//    }
449 370 berkley
  }
450 509 bojilova
451
  /**
452
   * Handle the logout request. Close the connection.
453
   */
454
  private void handleLogoutAction(PrintWriter out, Hashtable params,
455
               HttpServletRequest request, HttpServletResponse response) {
456
457
    String qformat = ((String[])params.get("qformat"))[0];
458
459
    // close the connection
460
    HttpSession sess = request.getSession(false);
461
    if (sess != null) { sess.invalidate();  }
462
463
    // produce output
464
    StringBuffer output = new StringBuffer();
465
    output.append("<?xml version=\"1.0\"?>");
466
    output.append("<success>");
467
    output.append("User logout.");
468
    output.append("</success>");
469
470
    //format and transform the output
471
    if (qformat.equals("html")) {
472
      Connection conn = null;
473
      try {
474
        conn = util.getConnection();
475
        DBTransform trans = new DBTransform(conn);
476
        response.setContentType("text/html");
477
        //trans.transformXMLDocument(output, "-//NCEAS//logout//EN",
478
        //                           "-//W3C//HTML//EN", out);
479
        response.sendRedirect(htmlpath + "/index.html");
480
        util.returnConnection(conn);
481
      } catch(Exception e) {
482
        util.returnConnection(conn);
483
      }
484
    // any output is returned
485
    } else {
486
      response.setContentType("text/xml");
487
      out.println(output.toString());
488
    }
489
490
  }
491
492 370 berkley
493 373 berkley
  /**
494 380 jones
   * Retreive the squery xml, execute it and display it
495
   *
496
   * @param out the output stream to the client
497
   * @param params the Hashtable of parameters that should be included
498
   * in the squery.
499
   * @param response the response object linked to the client
500
   * @param conn the database connection
501
   */
502
  protected void handleSQuery(PrintWriter out, Hashtable params,
503 441 bojilova
                 HttpServletResponse response, String user, String group)
504 373 berkley
  {
505 380 jones
    String xmlquery = ((String[])params.get("query"))[0];
506
    String qformat = ((String[])params.get("qformat"))[0];
507 465 berkley
    String resultdoc = null;
508
    String[] returndoc = null;
509
    if(params.contains("returndoc"))
510
    {
511
      returndoc = (String[])params.get("returndoc");
512
    }
513
514
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
515
    //String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
516 444 berkley
517 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
518
519 380 jones
    //format and transform the results
520
    if(qformat.equals("html")) {
521
      transformResultset(resultdoc, response, out);
522
    } else if(qformat.equals("xml")) {
523
      response.setContentType("text/xml");
524
      out.println(resultdoc);
525
    } else {
526
      out.println("invalid qformat: " + qformat);
527
    }
528 341 berkley
  }
529
530
   /**
531 380 jones
    * Create the xml query, execute it and display the results.
532
    *
533
    * @param out the output stream to the client
534
    * @param params the Hashtable of parameters that should be included
535 370 berkley
    * in the squery.
536 380 jones
    * @param response the response object linked to the client
537 370 berkley
    */
538 375 berkley
  protected void handleQuery(PrintWriter out, Hashtable params,
539 441 bojilova
                 HttpServletResponse response, String user, String group)
540 341 berkley
  {
541 370 berkley
    //create the query and run it
542 465 berkley
    String[] returndoc = null;
543
    if(params.containsKey("returndoc"))
544
    {
545
      returndoc = (String[])params.get("returndoc");
546
    }
547 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
548 465 berkley
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
549
    String qformat = ((String[])params.get("qformat"))[0];
550
    String resultdoc = null;
551
552
    resultdoc = createResultDocument(doclist, transformQuery(params));
553 425 bojilova
554 370 berkley
    //format and transform the results
555 380 jones
    if(qformat.equals("html")) {
556 370 berkley
      transformResultset(resultdoc, response, out);
557 380 jones
    } else if(qformat.equals("xml")) {
558 370 berkley
      response.setContentType("text/xml");
559
      out.println(resultdoc);
560 443 berkley
    } else {
561 370 berkley
      out.println("invalid qformat: " + qformat);
562
    }
563 341 berkley
  }
564
565
  /**
566 384 berkley
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
567
   * so it can properly be placed in the <query> tag of the resultset.
568
   * This method is overwritable so that other applications can customize
569
   * the structure of what is in the <query> tag.
570
   *
571
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
572
   */
573
  protected String transformQuery(Hashtable params)
574
  {
575
    //DBQuery.createSQuery is a re-calling of a previously called
576
    //function but it is necessary
577
    //so that overriding methods have access to the params hashtable
578
    String xmlquery = DBQuery.createSQuery(params);
579
    //the <?xml version="1.0"?> tag is the first 22 characters of the
580
    xmlquery = xmlquery.trim();
581
    int index = xmlquery.indexOf("?>");
582
    return xmlquery.substring(index + 2, xmlquery.length());
583
  }
584
585
  /**
586 443 berkley
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
587
   * string as a param instead of a hashtable.
588
   *
589
   * @param xmlquery a string representing a query.
590
   */
591
  protected String transformQuery(String xmlquery)
592
  {
593
    xmlquery = xmlquery.trim();
594
    int index = xmlquery.indexOf("?>");
595
    return xmlquery.substring(index + 2, xmlquery.length());
596
  }
597
598
  /**
599 380 jones
   * Run the query and return a hashtable of results.
600
   *
601
   * @param xmlquery the query to run
602
   */
603 465 berkley
  private Hashtable runQuery(String xmlquery, String user, String group,
604
                             String[] returndoc)
605 341 berkley
  {
606
    Hashtable doclist=null;
607
    Connection conn = null;
608
    try
609
    {
610 441 bojilova
      conn = util.getConnection();
611
      DBQuery queryobj = new DBQuery(conn, saxparser);
612 465 berkley
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
613
                                       returndoc);
614 441 bojilova
      util.returnConnection(conn);
615
      return doclist;
616 341 berkley
    }
617
    catch (Exception e)
618
    {
619 441 bojilova
      util.returnConnection(conn);
620 341 berkley
      util.debugMessage("Error in runQuery: " + e.getMessage());
621
      doclist = null;
622
      return doclist;
623
    }
624
  }
625
626 380 jones
  /**
627 370 berkley
   * Transorms an xml resultset document to html and sends it to the browser
628 380 jones
   *
629 370 berkley
   * @param resultdoc the string representation of the document that needs
630
   * to be transformed.
631
   * @param response the HttpServletResponse object bound to the client.
632
   * @param out the output stream to the client
633 375 berkley
   */
634
  protected void transformResultset(String resultdoc,
635 380 jones
                                    HttpServletResponse response,
636
                                    PrintWriter out)
637 370 berkley
  {
638
    Connection conn = null;
639 380 jones
    try {
640 370 berkley
      conn = util.getConnection();
641
      DBTransform trans = new DBTransform(conn);
642
      response.setContentType("text/html");
643
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
644
                                 "-//W3C//HTML//EN", out);
645 382 berkley
      util.returnConnection(conn);
646
    }
647
    catch(Exception e)
648
    {
649 441 bojilova
      util.returnConnection(conn);
650 370 berkley
    }
651
  }
652
653 355 berkley
  /**
654
   * Transforms a hashtable of documents to an xml or html result.
655 465 berkley
   * If there is a returndoc, then it only displays documents of
656
   * whatever type returndoc represents.  If a result is found in a document
657
   * that is not of type returndoc then this attempts to find a relation
658
   * between this document and one that satifies the returndoc doctype.
659 380 jones
   *
660 355 berkley
   * @param doclist- the hashtable to transform
661
   * @param xmlquery- the query that returned the dolist result
662 465 berkley
   * @param resultdoc- the document type to backtrack to.
663 355 berkley
   */
664 375 berkley
  protected String createResultDocument(Hashtable doclist, String xmlquery)
665 341 berkley
  {
666
    // Create a buffer to hold the xml result
667
    StringBuffer resultset = new StringBuffer();
668
669 382 berkley
    // Print the resulting root nodes
670 341 berkley
    String docid = null;
671
    String document = null;
672
    resultset.append("<?xml version=\"1.0\"?>\n");
673
    resultset.append("<resultset>\n");
674 465 berkley
675 384 berkley
    resultset.append("  <query>" + xmlquery + "</query>");
676 478 berkley
677
    if(doclist != null)
678 341 berkley
    {
679 478 berkley
      Enumeration doclistkeys = doclist.keys();
680
      while (doclistkeys.hasMoreElements())
681
      {
682
        docid = (String)doclistkeys.nextElement();
683
        document = (String)doclist.get(docid);
684
        resultset.append("  <document>" + document + "</document>");
685
      }
686
    }
687
688 341 berkley
    resultset.append("</resultset>");
689 444 berkley
    //System.out.println(resultset.toString());
690 370 berkley
    return resultset.toString();
691 341 berkley
  }
692 437 berkley
693
  /**
694
   * Handle the request to view the abstract of a document.
695 444 berkley
   * The abstractpath CGI parameter gives the xml path to the abstract
696
   * node.
697 437 berkley
   */
698
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
699
               HttpServletResponse response) throws IOException, SQLException
700
  {
701
    String abstractpath = null;
702
    String docid = null;
703
    Connection conn = null;
704
    response.setContentType("text/html");
705
    try
706
    {
707
      docid = ((String[])params.get("docid"))[0];
708
      if(params.containsKey("abstractpath"))
709
      {
710 444 berkley
        //the CGI parameter abstractpath holds the path to the abstract
711
        //that should be displayed.
712 437 berkley
        abstractpath = ((String[])params.get("abstractpath"))[0];
713
      }
714
      else
715
      {
716
        out.println("error: no abstractpath parameter");
717
      }
718
      conn = util.getConnection();
719
720
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
721
722 444 berkley
      out.println("<html><head><title>Abstract</title></head>");
723
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
724 437 berkley
      for(int i=0; i<abstracts.length; i++)
725
      {
726
        out.println("<p>" + (String)abstracts[i] + "</p>");
727
      }
728
      out.println("</body></html>");
729
    }
730
    catch (IOException ioe)
731
    {
732 444 berkley
       util.debugMessage("error in handlegetabstract: " + ioe.getMessage());
733 437 berkley
    }
734
    catch(SQLException sqle)
735
    {
736 444 berkley
      util.debugMessage("error in handlegetabstract: " + sqle.getMessage());
737 437 berkley
    }
738
    catch(Exception e)
739
    {
740 444 berkley
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
741 437 berkley
    }
742
743
    util.returnConnection(conn);
744
  }
745 181 jones
746 50 jones
  /**
747 453 berkley
   * Handle the database getrelateddocument request and return a XML document,
748
   * possibly transformed from XML into HTML
749
   */
750
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params,
751
               HttpServletResponse response)
752
               throws ClassNotFoundException, IOException, SQLException
753
  {
754
    String docid = null;
755
    Connection conn = null;
756
757
    if(params.containsKey("url"))
758
    {//the identifier for the related document is contained in the URL param
759
      try
760
      {
761
        DocumentImpl xmldoc=null;
762
        metacatURL murl = new metacatURL(((String[])params.get("url"))[0]);
763
        if(murl.getURLType().equals("metacat"))
764
        {//get the document from the database if it is the right type of url
765 473 berkley
          Hashtable murlParams = murl.getHashParams();
766
          if(murlParams.containsKey("docid"))
767 453 berkley
          {//the docid should be first
768 473 berkley
            docid = (String)murlParams.get("docid"); //get the docid value
769 453 berkley
            conn = util.getConnection();
770
            xmldoc = new DocumentImpl(conn, docid);
771 485 berkley
            String qformat = ((String[])params.get("qformat"))[0];
772
            if (qformat.equals("xml"))
773
            {
774
              // set content type and other response header fields first
775
              response.setContentType("text/xml");
776
              xmldoc.toXml(out);
777
              //out.println(xmldoc);
778
            }
779
            else if (qformat.equals("html"))
780
            {
781
              response.setContentType("text/html");
782
              // Look up the document type
783
              String sourcetype = xmldoc.getDoctype();
784
              // Transform the document to the new doctype
785
              DBTransform dbt = new DBTransform(conn);
786
              dbt.transformXMLDocument(xmldoc.toString(), sourcetype,
787
                                 "-//W3C//HTML//EN", out);
788
            }
789
790 473 berkley
            util.returnConnection(conn);
791 453 berkley
          }
792
          else
793
          {
794
            //throw new Exception("handleGetDocument: bad URL");
795
            System.err.println("handleGetDocument: bad URL");
796
          }
797
        }
798
        else if(murl.getURLType().equals("http"))
799
        {//get the document from the internet
800 473 berkley
          Hashtable murlParams = murl.getHashParams();
801
          if(murlParams.containsKey("httpurl"))
802 453 berkley
          {//httpurl is the param name for an http url.
803 473 berkley
            URL urlconn = new URL((String)murlParams.get("httpurl"));
804
            //create a new url obj.
805 458 berkley
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
806
            BufferedReader htmldoc = new BufferedReader(
807
                                   new InputStreamReader(urlconn.openStream()));
808 453 berkley
            //bind a data stream.
809
            try
810
            { //display the document
811
              String line=null;
812
              while((line = htmldoc.readLine()) != null)
813
              {
814
                out.println(line);
815
              }
816
            }
817
            catch(Exception e)
818
            {
819
              util.debugMessage("error viewing html document");
820
            }
821
          }
822
        }
823
      }
824
      catch (McdbException e) {
825
        response.setContentType("text/xml");
826
        e.toXml(out);
827
      } catch   (Throwable t) {
828
        response.setContentType("text/html");
829
        out.println(t.getMessage());
830
      } finally {
831
        util.returnConnection(conn);
832
      }
833
    }
834
  }
835
836
  /**
837 50 jones
   * Handle the database getdocument request and return a XML document,
838
   * possibly transformed from XML into HTML
839
   */
840 382 berkley
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
841 87 jones
               HttpServletResponse response)
842
               throws ClassNotFoundException, IOException, SQLException {
843 102 jones
    String docidstr = null;
844 162 bojilova
    String docid = null;
845 102 jones
    String doc = null;
846 309 bojilova
    Connection conn = null;
847
848 102 jones
    try {
849 87 jones
      // Find the document id number
850 102 jones
      docidstr = ((String[])params.get("docid"))[0];
851 162 bojilova
      docid = docidstr;
852 309 bojilova
      conn = util.getConnection();
853 393 jones
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
854
      // Get the document indicated from the db
855
      //doc = docreader.readXMLDocument(docid);
856 85 jones
857 87 jones
      // Return the document in XML or HTML format
858 437 berkley
      String qformat=null;
859
      if(params.containsKey("qformat"))
860
      {
861
        qformat = ((String[])params.get("qformat"))[0];
862
      }
863
      else
864
      {
865
        qformat = "html";
866
      }
867
      if (qformat.equals("xml")) {
868 85 jones
        // set content type and other response header fields first
869
        response.setContentType("text/xml");
870 431 jones
        xmldoc.toXml(out);
871
        //out.println(xmldoc);
872 85 jones
      } else if (qformat.equals("html")) {
873 437 berkley
        response.setContentType("text/html");
874 87 jones
        // Look up the document type
875 393 jones
        String sourcetype = xmldoc.getDoctype();
876 87 jones
        // Transform the document to the new doctype
877 393 jones
        DBTransform dbt = new DBTransform(conn);
878
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype,
879
                                 "-//W3C//HTML//EN", out);
880 85 jones
      }
881 343 jones
    } catch (McdbException e) {
882
      response.setContentType("text/xml");
883
      e.toXml(out);
884
    } catch (Throwable t) {
885 309 bojilova
      response.setContentType("text/html");
886 343 jones
      out.println(t.getMessage());
887 309 bojilova
    } finally {
888 320 bojilova
      util.returnConnection(conn);
889 309 bojilova
    }
890
891 49 jones
  }
892 55 jones
893
  /**
894
   * Handle the database putdocument request and write an XML document
895
   * to the database connection
896
   */
897 382 berkley
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
898 425 bojilova
               HttpServletResponse response, String user, String group) {
899 59 jones
900 309 bojilova
    Connection conn = null;
901
902 204 jones
    try {
903
      // Get the document indicated
904
      String[] doctext = (String[])params.get("doctext");
905
      StringReader xml = null;
906
      try {
907
        xml = new StringReader(doctext[0]);
908 59 jones
909 204 jones
        String[] action = (String[])params.get("action");
910
        String[] docid = (String[])params.get("docid");
911
        String newdocid = null;
912 203 jones
913 204 jones
        String doAction = null;
914
        if (action[0].equals("insert")) {
915
          doAction = "INSERT";
916
        } else if (action[0].equals("update")) {
917
          doAction = "UPDATE";
918
        }
919 203 jones
920 204 jones
        try {
921 309 bojilova
            // get a connection from the pool
922
            conn = util.getConnection();
923 408 jones
924 309 bojilova
            // write the document to the database
925
            try {
926
                String accNumber = docid[0];
927
                if (accNumber.equals("")) {
928
                    accNumber = null;
929
                }
930 425 bojilova
                newdocid = DocumentImpl.write(conn, xml, doAction, accNumber,
931 465 berkley
                                              user, group);
932
933 309 bojilova
            } catch (NullPointerException npe) {
934 425 bojilova
              newdocid = DocumentImpl.write(conn,xml,doAction,null,user,group);
935 309 bojilova
            }
936 462 bojilova
//        } catch (Exception e) {
937
//          response.setContentType("text/html");
938
//          out.println(e.getMessage());
939 309 bojilova
        } finally {
940 320 bojilova
          util.returnConnection(conn);
941 309 bojilova
        }
942
943 204 jones
        // set content type and other response header fields first
944
        response.setContentType("text/xml");
945
        out.println("<?xml version=\"1.0\"?>");
946
        out.println("<success>");
947
        out.println("<docid>" + newdocid + "</docid>");
948
        out.println("</success>");
949
950 203 jones
      } catch (NullPointerException npe) {
951 204 jones
        response.setContentType("text/xml");
952
        out.println("<?xml version=\"1.0\"?>");
953
        out.println("<error>");
954
        out.println(npe.getMessage());
955
        out.println("</error>");
956 55 jones
      }
957 204 jones
    } catch (Exception e) {
958
      response.setContentType("text/xml");
959
      out.println("<?xml version=\"1.0\"?>");
960
      out.println("<error>");
961
      out.println(e.getMessage());
962
      if (e instanceof SAXException) {
963
        Exception e2 = ((SAXException)e).getException();
964
        out.println("<error>");
965
        out.println(e2.getMessage());
966
        out.println("</error>");
967
      }
968
      //e.printStackTrace(out);
969
      out.println("</error>");
970 203 jones
    }
971 55 jones
  }
972 203 jones
973
  /**
974
   * Handle the database delete request and delete an XML document
975
   * from the database connection
976
   */
977
  private void handleDeleteAction(PrintWriter out, Hashtable params,
978 425 bojilova
               HttpServletResponse response, String user, String group) {
979 203 jones
980
    String[] docid = (String[])params.get("docid");
981 309 bojilova
    Connection conn = null;
982 203 jones
983
    // delete the document from the database
984
    try {
985 309 bojilova
      // get a connection from the pool
986
      conn = util.getConnection();
987 203 jones
                                      // NOTE -- NEED TO TEST HERE
988 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
989 203 jones
                                      // BEFORE ACCESSING ARRAY
990 375 berkley
      try {
991 425 bojilova
        DocumentImpl.delete(conn, docid[0], user, group);
992 204 jones
        response.setContentType("text/xml");
993
        out.println("<?xml version=\"1.0\"?>");
994
        out.println("<success>");
995 203 jones
        out.println("Document deleted.");
996 204 jones
        out.println("</success>");
997 203 jones
      } catch (AccessionNumberException ane) {
998 204 jones
        response.setContentType("text/xml");
999
        out.println("<?xml version=\"1.0\"?>");
1000
        out.println("<error>");
1001
        out.println("Error deleting document!!!");
1002 203 jones
        out.println(ane.getMessage());
1003 204 jones
        out.println("</error>");
1004 203 jones
      }
1005 204 jones
    } catch (Exception e) {
1006
      response.setContentType("text/xml");
1007
      out.println("<?xml version=\"1.0\"?>");
1008
      out.println("<error>");
1009
      out.println(e.getMessage());
1010
      out.println("</error>");
1011 309 bojilova
    } finally {
1012 320 bojilova
      util.returnConnection(conn);
1013 309 bojilova
    }
1014 203 jones
  }
1015 68 higgins
1016
  /**
1017 380 jones
   * Handle the validation request and return the results to the requestor
1018 68 higgins
   */
1019 185 jones
  private void handleValidateAction(PrintWriter out, Hashtable params,
1020
               HttpServletResponse response) {
1021 68 higgins
1022 103 jones
    // Get the document indicated
1023
    String valtext = null;
1024 309 bojilova
1025 103 jones
    try {
1026
      valtext = ((String[])params.get("valtext"))[0];
1027
    } catch (Exception nullpe) {
1028 68 higgins
1029 309 bojilova
      Connection conn = null;
1030 162 bojilova
      String docid = null;
1031 103 jones
      try {
1032
        // Find the document id number
1033 185 jones
        docid = ((String[])params.get("docid"))[0];
1034 309 bojilova
1035
        // get a connection from the pool
1036
        conn = util.getConnection();
1037 393 jones
1038 309 bojilova
        // Get the document indicated from the db
1039 393 jones
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1040
        valtext = xmldoc.toString();
1041 185 jones
1042 103 jones
      } catch (NullPointerException npe) {
1043 253 jones
        response.setContentType("text/xml");
1044
        out.println("<error>Error getting document ID: " + docid + "</error>");
1045 320 bojilova
        if ( conn != null ) { util.returnConnection(conn); }
1046 380 jones
        return;
1047 309 bojilova
      } catch (Exception e) {
1048
        response.setContentType("text/html");
1049
        out.println(e.getMessage());
1050
      } finally {
1051 320 bojilova
        util.returnConnection(conn);
1052 309 bojilova
      }
1053 103 jones
    }
1054 68 higgins
1055 309 bojilova
    Connection conn = null;
1056 103 jones
    try {
1057 309 bojilova
      // get a connection from the pool
1058
      conn = util.getConnection();
1059 253 jones
      DBValidate valobj = new DBValidate(saxparser,conn);
1060 185 jones
      boolean valid = valobj.validateString(valtext);
1061 68 higgins
1062
      // set content type and other response header fields first
1063 253 jones
      response.setContentType("text/xml");
1064
      out.println(valobj.returnErrors());
1065
1066 103 jones
    } catch (NullPointerException npe2) {
1067
      // set content type and other response header fields first
1068 253 jones
      response.setContentType("text/xml");
1069
      out.println("<error>Error validating document.</error>");
1070 309 bojilova
    } catch (Exception e) {
1071
      response.setContentType("text/html");
1072
      out.println(e.getMessage());
1073
    } finally {
1074 320 bojilova
      util.returnConnection(conn);
1075 309 bojilova
    }
1076 103 jones
  }
1077 87 jones
1078
  /**
1079 380 jones
   * Handle the document request and return the results to the requestor
1080 458 berkley
   * If a docid is passed in through the params then that document
1081
   * will be retrieved form the DB and put in the zip file.
1082
   * In addition if 1 or more relations parameters are passed, those file
1083
   * will be zipped as well.  Currently this is only implemented for
1084
   * metacat:// and http:// files.  Support should be added for srb:// files
1085
   * as well.
1086 91 higgins
   */
1087 458 berkley
  private void handleGetDataDocumentAction(ServletOutputStream out,
1088
               Hashtable params,
1089 185 jones
               HttpServletResponse response) {
1090 458 berkley
  //find the related files, get them from their source and zip them into
1091
  //a zip file.
1092
  try
1093
  {
1094
    Connection conn = util.getConnection();
1095
    String currentDocid = ((String[])params.get("docid"))[0];
1096
    ZipOutputStream zout = new ZipOutputStream(out);
1097
    byte[] bytestring = null;
1098
    ZipEntry zentry = null;
1099
    DocumentImpl xmldoc = null;
1100
    String[] reldocs = null;
1101
1102
    if(params.containsKey("relation"))
1103
    { //get the relations from the parameters.
1104
      reldocs = ((String[])params.get("relation"));
1105
    }
1106
    else
1107
    { //let the for loop know that there are no relations to zip
1108
      reldocs = new String[0];
1109
    }
1110
1111
    //write the base file to the zip file.
1112
    xmldoc = new DocumentImpl(conn, currentDocid);
1113
    bytestring = (xmldoc.toString()).getBytes();
1114
    zentry = new ZipEntry(currentDocid + ".xml");
1115
    //create a new zip entry and write the file to the stream
1116
    zentry.setSize(bytestring.length);
1117
    zout.putNextEntry(zentry);
1118
    zout.write(bytestring, 0, bytestring.length);
1119
    zout.closeEntry(); //get ready for the next entry.
1120
1121
    //zip up the related documents
1122
    for(int i=0; i<reldocs.length; i++)
1123
    {
1124
      metacatURL murl = new metacatURL(((String)reldocs[i]));
1125
      if(murl.getURLType().equals("metacat"))
1126
      {
1127
        //get the document from the database
1128 473 berkley
        xmldoc = new DocumentImpl(conn, (String)murl.getHashParam("docid"));
1129 458 berkley
        bytestring = (xmldoc.toString()).getBytes();
1130 473 berkley
        zentry = new ZipEntry(murl.getHashParam("docid") + ".xml");
1131 458 berkley
        //create a new zip entry and write the file to the stream
1132
        zentry.setSize(bytestring.length);
1133
        zout.putNextEntry(zentry);
1134
        zout.write(bytestring, 0, bytestring.length);
1135
        zout.closeEntry(); //get ready for the next entry.
1136
      }
1137
      else if(murl.getURLType().equals("http"))
1138
      {
1139 473 berkley
        Hashtable murlParams = murl.getHashParams();
1140
        if(murlParams.containsKey("httpurl"))
1141 458 berkley
        {//httpurl is the param name for an http url.
1142 473 berkley
          URL urlconn = new URL((String)murlParams.get("httpurl"));
1143
          //create a new url obj.
1144 458 berkley
          BufferedReader htmldoc = new BufferedReader(
1145
                                   new InputStreamReader(urlconn.openStream()));
1146
          //get the data from the web server
1147
          try
1148
          { //zip the document
1149
            String line=null;
1150 473 berkley
            zentry = new ZipEntry((String)murlParams.get("filename"));
1151 458 berkley
            //get just the filename from the URL.
1152
            zout.putNextEntry(zentry);
1153
            //make a new entry in the zip file stream
1154
            while((line = htmldoc.readLine()) != null)
1155
            {
1156
              bytestring = (line.toString()).getBytes();
1157
              zout.write(bytestring, 0, bytestring.length);
1158
              //write out the file line by line
1159
            }
1160
            zout.closeEntry(); //close the entry in the file
1161
          }
1162
          catch(Exception e)
1163
          {
1164
            util.debugMessage("error downloading html document");
1165
          }
1166
        }
1167
      }
1168
    }
1169
    zout.finish();  //terminate the zip file
1170
    zout.close();   //close the stream.
1171
    util.returnConnection(conn); //return the connection to the pool
1172
  }
1173
  catch(Exception e)
1174
  {
1175
    System.out.println("Error creating zip file: " + e.getMessage());
1176
    e.printStackTrace(System.out);
1177
  }
1178
1179
   /*
1180
   //////////old code using a shell script/////////////////////////////////
1181
1182 91 higgins
      boolean error_flag = false;
1183
      String error_message = "";
1184
      // Get the document indicated
1185
      String[] datadoc = (String[])params.get("datadoc");
1186 185 jones
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1187
      // executescript = "test.bat";        // for testing only!!!
1188 91 higgins
1189
      // set content type and other response header fields first
1190
      response.setContentType("application/octet-stream");
1191 185 jones
      if (defaultdatapath!=null) {
1192
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1193
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1194 91 higgins
        }
1195 185 jones
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1196
        if (executescript!=null) {
1197
          String command = null;
1198
          File scriptfile = new File(executescript);
1199
          if (scriptfile.exists()) {
1200
            command=executescript+" "+datadoc[0]; // script includes path
1201
        } else {     // look in defaultdatapath
1202
            // on Win98 one MUST include the .bat extender
1203
            command = defaultdatapath+executescript+" "+datadoc[0];
1204
        }
1205 91 higgins
      System.out.println(command);
1206
      try {
1207
      Process proc = Runtime.getRuntime().exec(command);
1208
      proc.waitFor();
1209
      }
1210
      catch (Exception eee) {
1211
        System.out.println("Error running process!");
1212
        error_flag = true;
1213
        error_message = "Error running process!";}
1214
      } // end executescript not null if
1215
      File datafile = new File(defaultdatapath+datadoc[0]);
1216
      try {
1217
      FileInputStream fw = new FileInputStream(datafile);
1218
      int x;
1219 185 jones
      while ((x = fw.read())!=-1) {
1220 91 higgins
        out.write(x); }
1221 185 jones
        fw.close();
1222
      } catch (Exception e) {
1223 91 higgins
        System.out.println("Error in returning file\n"+e.getMessage());
1224
        error_flag=true;
1225 185 jones
        error_message = error_message+"\nError in returning file\n"+
1226
                        e.getMessage();
1227
      }
1228
    } // end defaultdatapath not null if
1229 458 berkley
    */
1230 91 higgins
  }
1231 302 bojilova
1232
  /**
1233
   * Handle the getdoctypes Action.
1234
   * Read all doctypes from db connection in XML format
1235
   */
1236
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1237
                                       HttpServletResponse response) {
1238
1239 309 bojilova
    Connection conn = null;
1240
1241 302 bojilova
    try {
1242
1243 309 bojilova
        // get connection from the pool
1244
        conn = util.getConnection();
1245
        DBUtil dbutil = new DBUtil(conn);
1246 302 bojilova
        String doctypes = dbutil.readDoctypes();
1247
        out.println(doctypes);
1248
1249
    } catch (Exception e) {
1250
      out.println("<?xml version=\"1.0\"?>");
1251
      out.println("<error>");
1252
      out.println(e.getMessage());
1253
      out.println("</error>");
1254 309 bojilova
    } finally {
1255 320 bojilova
      util.returnConnection(conn);
1256 309 bojilova
    }
1257 302 bojilova
1258
  }
1259
1260
  /**
1261
   * Handle the getdataguide Action.
1262
   * Read Data Guide for a given doctype from db connection in XML format
1263
   */
1264
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
1265
                                        HttpServletResponse response) {
1266
1267 309 bojilova
    Connection conn = null;
1268 316 bojilova
    String doctype = null;
1269
    String[] doctypeArr = (String[])params.get("doctype");
1270 309 bojilova
1271 316 bojilova
    // get only the first doctype specified in the list of doctypes
1272
    // it could be done for all doctypes in that list
1273
    if (doctypeArr != null) {
1274
        doctype = ((String[])params.get("doctype"))[0];
1275
    }
1276
1277 302 bojilova
    try {
1278
1279 309 bojilova
        // get connection from the pool
1280
        conn = util.getConnection();
1281
        DBUtil dbutil = new DBUtil(conn);
1282 316 bojilova
        String dataguide = dbutil.readDataGuide(doctype);
1283 302 bojilova
        out.println(dataguide);
1284
1285
    } catch (Exception e) {
1286
      out.println("<?xml version=\"1.0\"?>");
1287
      out.println("<error>");
1288
      out.println(e.getMessage());
1289
      out.println("</error>");
1290 309 bojilova
    } finally {
1291 320 bojilova
      util.returnConnection(conn);
1292 309 bojilova
    }
1293 302 bojilova
1294
  }
1295
1296 46 jones
}