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 566 jones
 * action=read -- display an XML document in XML or HTML<br>
70 205 jones
 * 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 598 bojilova
 * 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 183 jones
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
78 205 jones
 * valtext -- XML text to be validated<br>
79
 * action=getdatadoc -- retreive a stored datadocument<br>
80 302 bojilova
 * action=getdoctypes -- retreive all doctypes (publicID)<br>
81
 * action=getdataguide -- retreive a Data Guide<br>
82 205 jones
 * 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 46 jones
 */
88
public class MetaCatServlet extends HttpServlet {
89
90 370 berkley
  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 380 jones
  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 370 berkley
  private String htmlpath = null;
104 380 jones
  // script to get data file and put it
105
  // in defaultdocpath dir
106 370 berkley
  private String executescript  = null;
107 46 jones
108 50 jones
  /**
109
   * Initialize the servlet by creating appropriate database connections
110
   */
111 46 jones
  public void init( ServletConfig config ) throws ServletException {
112
    try {
113
      super.init( config );
114
      this.config = config;
115 332 bojilova
      this.context = config.getServletContext();
116 184 jones
      System.out.println("MetaCatServlet Initialize");
117 82 jones
118 184 jones
      util = new MetaCatUtil();
119
120 83 jones
      // Get the configuration file information
121 184 jones
      resultStyleURL = util.getOption("resultStyleURL");
122
      xmlcatalogfile = util.getOption("xmlcatalogfile");
123
      saxparser = util.getOption("saxparser");
124
      defaultdatapath = util.getOption("defaultdatapath");
125 593 berkley
      executescript = util.getOption("executescript");
126 360 bojilova
      servletpath = util.getOption("servletpath");
127
      htmlpath = util.getOption("htmlpath");
128 598 bojilova
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 46 jones
    } catch ( ServletException ex ) {
137
      throw ex;
138
    }
139
  }
140
141 320 bojilova
  /**
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 50 jones
  /** Handle "GET" method requests from HTTP clients */
152 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
153
    throws ServletException, IOException {
154
155 48 jones
    // Process the data and send back the response
156 59 jones
    handleGetOrPost(request, response);
157 48 jones
  }
158
159 50 jones
  /** Handle "POST" method requests from HTTP clients */
160 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
161
    throws ServletException, IOException {
162
163
    // Process the data and send back the response
164 59 jones
    handleGetOrPost(request, response);
165 48 jones
  }
166
167 49 jones
  /**
168 50 jones
   * Control servlet response depending on the action parameter specified
169 49 jones
   */
170 382 berkley
  private void handleGetOrPost(HttpServletRequest request,
171 59 jones
    HttpServletResponse response)
172 355 berkley
    throws ServletException, IOException
173
 {
174 48 jones
175 309 bojilova
    if ( util == null ) {
176
        util = new MetaCatUtil();
177
    }
178 598 bojilova
    if ( connectionPool.isEmpty() ) {
179 309 bojilova
      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 49 jones
    // Get a handle to the output stream back to the client
188 566 jones
    //PrintWriter pwout = response.getWriter();
189 102 jones
    //response.setContentType("text/html");
190 49 jones
191 59 jones
    String name = null;
192
    String[] value = null;
193 103 jones
    String[] docid = new String[3];
194 59 jones
    Hashtable params = new Hashtable();
195
    Enumeration paramlist = request.getParameterNames();
196
    while (paramlist.hasMoreElements()) {
197
      name = (String)paramlist.nextElement();
198
      value = request.getParameterValues(name);
199 103 jones
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 373 berkley
      }
210 103 jones
211 566 jones
      //pwout.println(name + " => " + value[0]);
212 373 berkley
      params.put(name,value);
213
    }
214 355 berkley
215 509 bojilova
    //if the user clicked on the input images, decode which image
216
    //was clicked then set the action.
217 505 jones
    String action = ((String[])params.get("action"))[0];
218
    util.debugMessage("Line 213: Action is: " + action);
219 509 bojilova
220 505 jones
    //MBJELIMINATE String action = decodeMouseAction(params);
221
    //if(action.equals("error"))
222
    //{
223 509 bojilova
      //util.debugMessage("Line 218: Action is: " + action);
224 505 jones
      //action = ((String[])params.get("action"))[0];
225
    //}
226 355 berkley
227 380 jones
    // This block handles session management for the servlet
228
    // by looking up the current session information for all actions
229 509 bojilova
    // other than "login" and "logout"
230 425 bojilova
    String username = null;
231
    String groupname = null;
232 509 bojilova
233
    // handle login action
234
    if (action.equals("login")) {
235
236 458 berkley
      handleLoginAction(response.getWriter(), params, request, response);
237 509 bojilova
238 210 bojilova
    // handle logout action
239 509 bojilova
    } else if (action.equals("logout")) {
240 361 berkley
241 509 bojilova
      handleLogoutAction(response.getWriter(), params, request, response);
242 361 berkley
243 251 bojilova
    // aware of session expiration on every request
244 343 jones
    } else {
245 509 bojilova
246 332 bojilova
      HttpSession sess = request.getSession(true);
247
      if (sess.isNew()) {
248 251 bojilova
        // session expired or has not been stored b/w user requests
249 441 bojilova
        username = "public";
250 425 bojilova
      } else {
251
        username = (String)sess.getAttribute("username");
252
        groupname = (String)sess.getAttribute("groupname");
253
      }
254 210 bojilova
    }
255 219 jones
256 380 jones
    // Now that we know the session is valid, we can delegate the request
257
    // to a particular action handler
258 361 berkley
    if(action.equals("query"))
259
    {
260 458 berkley
      handleQuery(response.getWriter(), params, response, username, groupname);
261 373 berkley
    }
262 371 berkley
    else if(action.equals("squery"))
263 361 berkley
    {
264 373 berkley
      if(params.containsKey("query"))
265
      {
266 458 berkley
        handleSQuery(response.getWriter(), params, response, username, groupname);
267 373 berkley
      }
268
      else
269
      {
270 458 berkley
        PrintWriter out = response.getWriter();
271 373 berkley
        out.println("Illegal action squery without \"query\" parameter");
272
      }
273
    }
274 566 jones
    else if (action.equals("read")) {
275 458 berkley
      PrintWriter out = response.getWriter();
276 87 jones
      try {
277 566 jones
        handleReadAction(out, params, response);
278 87 jones
      } catch (ClassNotFoundException e) {
279 103 jones
        out.println(e.getMessage());
280 87 jones
      } catch (SQLException se) {
281 103 jones
        out.println(se.getMessage());
282 87 jones
      }
283 453 berkley
    }
284 566 jones
/*
285 453 berkley
    else if (action.equals("getrelateddocument")) {
286 458 berkley
      PrintWriter out = response.getWriter();
287 453 berkley
      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 566 jones
*/
296 453 berkley
    else if (action.equals("insert") || action.equals("update")) {
297 458 berkley
      PrintWriter out = response.getWriter();
298 509 bojilova
      if ( (username != null) &&  !username.equals("public") ) {
299 425 bojilova
        handleInsertOrUpdateAction(out, params, response, username, groupname);
300
      } else {
301
        out.println("Permission denied for " + action);
302
      }
303 203 jones
    } else if (action.equals("delete")) {
304 458 berkley
      PrintWriter out = response.getWriter();
305 509 bojilova
      if ( (username != null) &&  !username.equals("public") ) {
306 425 bojilova
        handleDeleteAction(out, params, response, username, groupname);
307
      } else {
308
        out.println("Permission denied for " + action);
309
      }
310 68 higgins
    } else if (action.equals("validate")) {
311 458 berkley
      PrintWriter out = response.getWriter();
312 437 berkley
      handleValidateAction(out, params, response);
313
    } else if (action.equals("getabstract")) {
314 458 berkley
      PrintWriter out = response.getWriter();
315 437 berkley
      try{
316
        handleViewAbstractAction(out, params, response);
317
      }
318
      catch(Exception e)
319
      {
320
        out.println("error viewing abstract: " + e.getMessage());
321
      }
322 91 higgins
    } else if (action.equals("getdatadoc")) {
323 458 berkley
      response.setContentType("application/zip");
324
      ServletOutputStream out = response.getOutputStream();
325 91 higgins
      handleGetDataDocumentAction(out, params, response);
326 302 bojilova
    } else if (action.equals("getdoctypes")) {
327 458 berkley
      PrintWriter out = response.getWriter();
328 302 bojilova
      handleGetDoctypesAction(out, params, response);
329
    } else if (action.equals("getdataguide")) {
330 458 berkley
      PrintWriter out = response.getWriter();
331 302 bojilova
      handleGetDataGuideAction(out, params, response);
332 509 bojilova
    } else if (action.equals("login") || action.equals("logout")) {
333 566 jones
    } 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 50 jones
    } else {
374 458 berkley
      PrintWriter out = response.getWriter();
375 50 jones
      out.println("Error: action not registered.  Please report this error.");
376 46 jones
    }
377 465 berkley
    util.closeConnections();
378 49 jones
    // Close the stream to the client
379 458 berkley
    //out.close();
380 46 jones
  }
381 355 berkley
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 375 berkley
  protected String decodeMouseAction(Hashtable params)
391 355 berkley
  {
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 566 jones
        action = "read";
402 355 berkley
      } 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 380 jones
      //
410
      // MBJ -- NOTE that this should be handled more gracefully with
411
      //        the new exception infrastructure -- this "error" return
412
      //        value is inappropriate
413 355 berkley
      //out.println("<P>Caught exception looking for Y value.");
414
      return "error";
415 382 berkley
    }
416 355 berkley
  }
417 49 jones
418 50 jones
  /**
419 509 bojilova
   * Handle the login request. Create a new session object.
420 503 bojilova
   * Do user authentication through the session.
421 210 bojilova
   */
422
  private void handleLoginAction(PrintWriter out, Hashtable params,
423
               HttpServletRequest request, HttpServletResponse response) {
424 251 bojilova
425 503 bojilova
    AuthSession sess = null;
426 228 bojilova
    String un = ((String[])params.get("username"))[0];
427
    String pw = ((String[])params.get("password"))[0];
428 297 bojilova
    String action = ((String[])params.get("action"))[0];
429 509 bojilova
    String qformat = ((String[])params.get("qformat"))[0];
430 332 bojilova
431 297 bojilova
    try {
432 509 bojilova
      sess = new AuthSession();
433 297 bojilova
    } catch (Exception e) {
434
      out.println(e.getMessage());
435 509 bojilova
      return;
436 297 bojilova
    }
437 411 bojilova
438 509 bojilova
    boolean isValid = sess.authenticate(request, un, pw);
439
440
    // format and transform the output
441
    if (qformat.equals("html")) {
442
      Connection conn = null;
443 503 bojilova
      try {
444 509 bojilova
        conn = util.getConnection();
445
        DBTransform trans = new DBTransform(conn);
446
        response.setContentType("text/html");
447 510 bojilova
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
448
                                   "-//W3C//HTML//EN", out);
449 509 bojilova
        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 503 bojilova
    }
459 510 bojilova
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 509 bojilova
478 370 berkley
  }
479 509 bojilova
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 510 bojilova
    output.append("<logout>");
496
    output.append("User logged out");
497
    output.append("</logout>");
498 509 bojilova
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 510 bojilova
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
507
                                   "-//W3C//HTML//EN", out);
508 509 bojilova
        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 510 bojilova
/* 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 509 bojilova
  }
532
533 370 berkley
534 373 berkley
  /**
535 380 jones
   * 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 441 bojilova
                 HttpServletResponse response, String user, String group)
545 373 berkley
  {
546 380 jones
    String xmlquery = ((String[])params.get("query"))[0];
547
    String qformat = ((String[])params.get("qformat"))[0];
548 465 berkley
    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 444 berkley
558 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
559
560 380 jones
    //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 341 berkley
  }
570
571
   /**
572 380 jones
    * 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 370 berkley
    * in the squery.
577 380 jones
    * @param response the response object linked to the client
578 370 berkley
    */
579 375 berkley
  protected void handleQuery(PrintWriter out, Hashtable params,
580 441 bojilova
                 HttpServletResponse response, String user, String group)
581 341 berkley
  {
582 370 berkley
    //create the query and run it
583 465 berkley
    String[] returndoc = null;
584
    if(params.containsKey("returndoc"))
585
    {
586
      returndoc = (String[])params.get("returndoc");
587
    }
588 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
589 465 berkley
    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 425 bojilova
595 370 berkley
    //format and transform the results
596 380 jones
    if(qformat.equals("html")) {
597 370 berkley
      transformResultset(resultdoc, response, out);
598 380 jones
    } else if(qformat.equals("xml")) {
599 370 berkley
      response.setContentType("text/xml");
600
      out.println(resultdoc);
601 443 berkley
    } else {
602 370 berkley
      out.println("invalid qformat: " + qformat);
603
    }
604 341 berkley
  }
605
606
  /**
607 384 berkley
   * 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 443 berkley
   * 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 380 jones
   * Run the query and return a hashtable of results.
641
   *
642
   * @param xmlquery the query to run
643
   */
644 465 berkley
  private Hashtable runQuery(String xmlquery, String user, String group,
645
                             String[] returndoc)
646 341 berkley
  {
647
    Hashtable doclist=null;
648
    Connection conn = null;
649
    try
650
    {
651 441 bojilova
      conn = util.getConnection();
652
      DBQuery queryobj = new DBQuery(conn, saxparser);
653 465 berkley
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
654
                                       returndoc);
655 441 bojilova
      util.returnConnection(conn);
656
      return doclist;
657 341 berkley
    }
658
    catch (Exception e)
659
    {
660 441 bojilova
      util.returnConnection(conn);
661 341 berkley
      util.debugMessage("Error in runQuery: " + e.getMessage());
662
      doclist = null;
663
      return doclist;
664
    }
665
  }
666
667 380 jones
  /**
668 370 berkley
   * Transorms an xml resultset document to html and sends it to the browser
669 380 jones
   *
670 370 berkley
   * @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 375 berkley
   */
675
  protected void transformResultset(String resultdoc,
676 380 jones
                                    HttpServletResponse response,
677
                                    PrintWriter out)
678 370 berkley
  {
679
    Connection conn = null;
680 380 jones
    try {
681 370 berkley
      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 382 berkley
      util.returnConnection(conn);
687
    }
688
    catch(Exception e)
689
    {
690 441 bojilova
      util.returnConnection(conn);
691 370 berkley
    }
692
  }
693
694 355 berkley
  /**
695
   * Transforms a hashtable of documents to an xml or html result.
696 465 berkley
   * 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 380 jones
   *
701 355 berkley
   * @param doclist- the hashtable to transform
702
   * @param xmlquery- the query that returned the dolist result
703 465 berkley
   * @param resultdoc- the document type to backtrack to.
704 355 berkley
   */
705 375 berkley
  protected String createResultDocument(Hashtable doclist, String xmlquery)
706 341 berkley
  {
707
    // Create a buffer to hold the xml result
708
    StringBuffer resultset = new StringBuffer();
709
710 382 berkley
    // Print the resulting root nodes
711 341 berkley
    String docid = null;
712
    String document = null;
713
    resultset.append("<?xml version=\"1.0\"?>\n");
714
    resultset.append("<resultset>\n");
715 465 berkley
716 384 berkley
    resultset.append("  <query>" + xmlquery + "</query>");
717 478 berkley
718
    if(doclist != null)
719 341 berkley
    {
720 478 berkley
      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 341 berkley
    resultset.append("</resultset>");
730 444 berkley
    //System.out.println(resultset.toString());
731 370 berkley
    return resultset.toString();
732 341 berkley
  }
733 437 berkley
734
  /**
735
   * Handle the request to view the abstract of a document.
736 444 berkley
   * The abstractpath CGI parameter gives the xml path to the abstract
737
   * node.
738 437 berkley
   */
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 444 berkley
        //the CGI parameter abstractpath holds the path to the abstract
752
        //that should be displayed.
753 437 berkley
        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 444 berkley
      out.println("<html><head><title>Abstract</title></head>");
764
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
765 437 berkley
      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 444 berkley
       util.debugMessage("error in handlegetabstract: " + ioe.getMessage());
774 437 berkley
    }
775
    catch(SQLException sqle)
776
    {
777 444 berkley
      util.debugMessage("error in handlegetabstract: " + sqle.getMessage());
778 437 berkley
    }
779
    catch(Exception e)
780
    {
781 444 berkley
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
782 437 berkley
    }
783
784
    util.returnConnection(conn);
785
  }
786 181 jones
787 50 jones
  /**
788 453 berkley
   * Handle the database getrelateddocument request and return a XML document,
789
   * possibly transformed from XML into HTML
790
   */
791 566 jones
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params,
792
               HttpServletResponse response, URL murl)
793 453 berkley
               throws ClassNotFoundException, IOException, SQLException
794
  {
795
    String docid = null;
796
    Connection conn = null;
797
798 566 jones
    //if(params.containsKey("url"))
799
    //{//the identifier for the related document is contained in the URL param
800 453 berkley
      try
801
      {
802
        DocumentImpl xmldoc=null;
803 566 jones
        //MetacatURL murl = new MetacatURL(((String[])params.get("url"))[0]);
804
        if(murl.getProtocol().equals("metacat"))
805 453 berkley
        {//get the document from the database if it is the right type of url
806 566 jones
          //Hashtable murlParams = murl.getHashParams();
807
          Hashtable murlParams = util.parseQuery(murl.getQuery());
808 473 berkley
          if(murlParams.containsKey("docid"))
809 453 berkley
          {//the docid should be first
810 473 berkley
            docid = (String)murlParams.get("docid"); //get the docid value
811 453 berkley
            conn = util.getConnection();
812
            xmldoc = new DocumentImpl(conn, docid);
813 485 berkley
            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 473 berkley
            util.returnConnection(conn);
833 453 berkley
          }
834
          else
835
          {
836
            //throw new Exception("handleGetDocument: bad URL");
837
            System.err.println("handleGetDocument: bad URL");
838
          }
839
        }
840 566 jones
        else if(murl.getProtocol().equals("http"))
841 453 berkley
        {//get the document from the internet
842 566 jones
          //Hashtable murlParams = murl.getHashParams();
843
          Hashtable murlParams = util.parseQuery(murl.getQuery());
844 473 berkley
          if(murlParams.containsKey("httpurl"))
845 453 berkley
          {//httpurl is the param name for an http url.
846 473 berkley
            URL urlconn = new URL((String)murlParams.get("httpurl"));
847
            //create a new url obj.
848 458 berkley
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
849
            BufferedReader htmldoc = new BufferedReader(
850
                                   new InputStreamReader(urlconn.openStream()));
851 453 berkley
            //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 566 jones
    //} // end if
877 453 berkley
  }
878
879
  /**
880 566 jones
   * Handle the database read request and return an XML document,
881 50 jones
   * possibly transformed from XML into HTML
882
   */
883 566 jones
  private void handleReadAction(PrintWriter out, Hashtable params,
884
               HttpServletResponse response)
885
               throws ClassNotFoundException, IOException, SQLException
886
  {
887 598 bojilova
    //out.println(((String[])params.get("docid"))[0]);
888 566 jones
    try {
889
      //MetacatURL murl = new MetacatURL(((String[])params.get("docid"))[0]);
890
      URL murl = new URL(((String[])params.get("docid"))[0]);
891
      handleGetRelatedDocumentAction(out, params, response, murl);
892
    } catch (MalformedURLException mue) {
893
      handleGetDocumentAction(out, params, response);
894
    }
895
  }
896
897
  /**
898
   * Handle the database read request and return an XML document,
899
   * possibly transformed from XML into HTML
900
   */
901 382 berkley
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
902 87 jones
               HttpServletResponse response)
903
               throws ClassNotFoundException, IOException, SQLException {
904 102 jones
    String docidstr = null;
905 162 bojilova
    String docid = null;
906 102 jones
    String doc = null;
907 309 bojilova
    Connection conn = null;
908
909 102 jones
    try {
910 87 jones
      // Find the document id number
911 102 jones
      docidstr = ((String[])params.get("docid"))[0];
912 162 bojilova
      docid = docidstr;
913 309 bojilova
      conn = util.getConnection();
914 393 jones
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
915
      // Get the document indicated from the db
916
      //doc = docreader.readXMLDocument(docid);
917 85 jones
918 87 jones
      // Return the document in XML or HTML format
919 437 berkley
      String qformat=null;
920
      if(params.containsKey("qformat"))
921
      {
922
        qformat = ((String[])params.get("qformat"))[0];
923
      }
924
      else
925
      {
926
        qformat = "html";
927
      }
928
      if (qformat.equals("xml")) {
929 85 jones
        // set content type and other response header fields first
930
        response.setContentType("text/xml");
931 431 jones
        xmldoc.toXml(out);
932
        //out.println(xmldoc);
933 85 jones
      } else if (qformat.equals("html")) {
934 437 berkley
        response.setContentType("text/html");
935 87 jones
        // Look up the document type
936 393 jones
        String sourcetype = xmldoc.getDoctype();
937 87 jones
        // Transform the document to the new doctype
938 393 jones
        DBTransform dbt = new DBTransform(conn);
939
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype,
940
                                 "-//W3C//HTML//EN", out);
941 85 jones
      }
942 343 jones
    } catch (McdbException e) {
943
      response.setContentType("text/xml");
944
      e.toXml(out);
945
    } catch (Throwable t) {
946 309 bojilova
      response.setContentType("text/html");
947 343 jones
      out.println(t.getMessage());
948 309 bojilova
    } finally {
949 320 bojilova
      util.returnConnection(conn);
950 309 bojilova
    }
951
952 49 jones
  }
953 55 jones
954
  /**
955
   * Handle the database putdocument request and write an XML document
956
   * to the database connection
957
   */
958 382 berkley
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
959 425 bojilova
               HttpServletResponse response, String user, String group) {
960 59 jones
961 309 bojilova
    Connection conn = null;
962
963 204 jones
    try {
964
      // Get the document indicated
965
      String[] doctext = (String[])params.get("doctext");
966 557 bojilova
967
      StringReader acl = null;
968 598 bojilova
      if(params.contains("acltext"))
969 557 bojilova
      {
970 598 bojilova
        String[] acltext = (String[])params.get("acltext");
971 557 bojilova
        try {
972
          acl = new StringReader(acltext[0]);
973
        } catch (NullPointerException npe) {}
974
      }
975 598 bojilova
      StringReader dtd = null;
976
      if(params.contains("dtdtext"))
977
      {
978
        String[] dtdtext = (String[])params.get("dtdtext");
979
        try {
980
          dtd = new StringReader(dtdtext[0]);
981
        } catch (NullPointerException npe) {}
982
      }
983 557 bojilova
984 204 jones
      StringReader xml = null;
985
      try {
986
        xml = new StringReader(doctext[0]);
987 59 jones
988 204 jones
        String[] action = (String[])params.get("action");
989
        String[] docid = (String[])params.get("docid");
990
        String newdocid = null;
991 203 jones
992 204 jones
        String doAction = null;
993
        if (action[0].equals("insert")) {
994
          doAction = "INSERT";
995
        } else if (action[0].equals("update")) {
996
          doAction = "UPDATE";
997
        }
998 203 jones
999 204 jones
        try {
1000 309 bojilova
            // get a connection from the pool
1001
            conn = util.getConnection();
1002 408 jones
1003 309 bojilova
            // write the document to the database
1004
            try {
1005
                String accNumber = docid[0];
1006
                if (accNumber.equals("")) {
1007
                    accNumber = null;
1008
                }
1009 598 bojilova
                newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1010 557 bojilova
                                              accNumber, user, group);
1011 465 berkley
1012 309 bojilova
            } catch (NullPointerException npe) {
1013 598 bojilova
              newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1014 557 bojilova
                                            null, user, group);
1015 309 bojilova
            }
1016 462 bojilova
//        } catch (Exception e) {
1017
//          response.setContentType("text/html");
1018
//          out.println(e.getMessage());
1019 309 bojilova
        } finally {
1020 320 bojilova
          util.returnConnection(conn);
1021 309 bojilova
        }
1022
1023 204 jones
        // set content type and other response header fields first
1024
        response.setContentType("text/xml");
1025
        out.println("<?xml version=\"1.0\"?>");
1026
        out.println("<success>");
1027
        out.println("<docid>" + newdocid + "</docid>");
1028
        out.println("</success>");
1029
1030 203 jones
      } catch (NullPointerException npe) {
1031 204 jones
        response.setContentType("text/xml");
1032
        out.println("<?xml version=\"1.0\"?>");
1033
        out.println("<error>");
1034
        out.println(npe.getMessage());
1035
        out.println("</error>");
1036 55 jones
      }
1037 204 jones
    } catch (Exception e) {
1038
      response.setContentType("text/xml");
1039
      out.println("<?xml version=\"1.0\"?>");
1040
      out.println("<error>");
1041
      out.println(e.getMessage());
1042
      if (e instanceof SAXException) {
1043
        Exception e2 = ((SAXException)e).getException();
1044
        out.println("<error>");
1045
        out.println(e2.getMessage());
1046
        out.println("</error>");
1047
      }
1048
      //e.printStackTrace(out);
1049
      out.println("</error>");
1050 203 jones
    }
1051 55 jones
  }
1052 203 jones
1053
  /**
1054
   * Handle the database delete request and delete an XML document
1055
   * from the database connection
1056
   */
1057
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1058 425 bojilova
               HttpServletResponse response, String user, String group) {
1059 203 jones
1060
    String[] docid = (String[])params.get("docid");
1061 309 bojilova
    Connection conn = null;
1062 203 jones
1063
    // delete the document from the database
1064
    try {
1065 309 bojilova
      // get a connection from the pool
1066
      conn = util.getConnection();
1067 203 jones
                                      // NOTE -- NEED TO TEST HERE
1068 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
1069 203 jones
                                      // BEFORE ACCESSING ARRAY
1070 375 berkley
      try {
1071 425 bojilova
        DocumentImpl.delete(conn, docid[0], user, group);
1072 204 jones
        response.setContentType("text/xml");
1073
        out.println("<?xml version=\"1.0\"?>");
1074
        out.println("<success>");
1075 203 jones
        out.println("Document deleted.");
1076 204 jones
        out.println("</success>");
1077 203 jones
      } catch (AccessionNumberException ane) {
1078 204 jones
        response.setContentType("text/xml");
1079
        out.println("<?xml version=\"1.0\"?>");
1080
        out.println("<error>");
1081
        out.println("Error deleting document!!!");
1082 203 jones
        out.println(ane.getMessage());
1083 204 jones
        out.println("</error>");
1084 203 jones
      }
1085 204 jones
    } catch (Exception e) {
1086
      response.setContentType("text/xml");
1087
      out.println("<?xml version=\"1.0\"?>");
1088
      out.println("<error>");
1089
      out.println(e.getMessage());
1090
      out.println("</error>");
1091 309 bojilova
    } finally {
1092 320 bojilova
      util.returnConnection(conn);
1093 309 bojilova
    }
1094 203 jones
  }
1095 68 higgins
1096
  /**
1097 380 jones
   * Handle the validation request and return the results to the requestor
1098 68 higgins
   */
1099 185 jones
  private void handleValidateAction(PrintWriter out, Hashtable params,
1100
               HttpServletResponse response) {
1101 68 higgins
1102 103 jones
    // Get the document indicated
1103
    String valtext = null;
1104 309 bojilova
1105 103 jones
    try {
1106
      valtext = ((String[])params.get("valtext"))[0];
1107
    } catch (Exception nullpe) {
1108 68 higgins
1109 309 bojilova
      Connection conn = null;
1110 162 bojilova
      String docid = null;
1111 103 jones
      try {
1112
        // Find the document id number
1113 185 jones
        docid = ((String[])params.get("docid"))[0];
1114 309 bojilova
1115
        // get a connection from the pool
1116
        conn = util.getConnection();
1117 393 jones
1118 309 bojilova
        // Get the document indicated from the db
1119 393 jones
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1120
        valtext = xmldoc.toString();
1121 185 jones
1122 103 jones
      } catch (NullPointerException npe) {
1123 253 jones
        response.setContentType("text/xml");
1124
        out.println("<error>Error getting document ID: " + docid + "</error>");
1125 320 bojilova
        if ( conn != null ) { util.returnConnection(conn); }
1126 380 jones
        return;
1127 309 bojilova
      } catch (Exception e) {
1128
        response.setContentType("text/html");
1129
        out.println(e.getMessage());
1130
      } finally {
1131 320 bojilova
        util.returnConnection(conn);
1132 309 bojilova
      }
1133 103 jones
    }
1134 68 higgins
1135 309 bojilova
    Connection conn = null;
1136 103 jones
    try {
1137 309 bojilova
      // get a connection from the pool
1138
      conn = util.getConnection();
1139 253 jones
      DBValidate valobj = new DBValidate(saxparser,conn);
1140 185 jones
      boolean valid = valobj.validateString(valtext);
1141 68 higgins
1142
      // set content type and other response header fields first
1143 253 jones
      response.setContentType("text/xml");
1144
      out.println(valobj.returnErrors());
1145
1146 103 jones
    } catch (NullPointerException npe2) {
1147
      // set content type and other response header fields first
1148 253 jones
      response.setContentType("text/xml");
1149
      out.println("<error>Error validating document.</error>");
1150 309 bojilova
    } catch (Exception e) {
1151
      response.setContentType("text/html");
1152
      out.println(e.getMessage());
1153
    } finally {
1154 320 bojilova
      util.returnConnection(conn);
1155 309 bojilova
    }
1156 103 jones
  }
1157 87 jones
1158
  /**
1159 380 jones
   * Handle the document request and return the results to the requestor
1160 458 berkley
   * If a docid is passed in through the params then that document
1161
   * will be retrieved form the DB and put in the zip file.
1162
   * In addition if 1 or more relations parameters are passed, those file
1163
   * will be zipped as well.  Currently this is only implemented for
1164
   * metacat:// and http:// files.  Support should be added for srb:// files
1165
   * as well.
1166 91 higgins
   */
1167 458 berkley
  private void handleGetDataDocumentAction(ServletOutputStream out,
1168
               Hashtable params,
1169 185 jones
               HttpServletResponse response) {
1170 458 berkley
  //find the related files, get them from their source and zip them into
1171
  //a zip file.
1172
  try
1173
  {
1174
    Connection conn = util.getConnection();
1175
    String currentDocid = ((String[])params.get("docid"))[0];
1176
    ZipOutputStream zout = new ZipOutputStream(out);
1177
    byte[] bytestring = null;
1178
    ZipEntry zentry = null;
1179
    DocumentImpl xmldoc = null;
1180
    String[] reldocs = null;
1181
1182
    if(params.containsKey("relation"))
1183
    { //get the relations from the parameters.
1184
      reldocs = ((String[])params.get("relation"));
1185
    }
1186
    else
1187
    { //let the for loop know that there are no relations to zip
1188
      reldocs = new String[0];
1189
    }
1190
1191
    //write the base file to the zip file.
1192
    xmldoc = new DocumentImpl(conn, currentDocid);
1193
    bytestring = (xmldoc.toString()).getBytes();
1194
    zentry = new ZipEntry(currentDocid + ".xml");
1195
    //create a new zip entry and write the file to the stream
1196
    zentry.setSize(bytestring.length);
1197
    zout.putNextEntry(zentry);
1198
    zout.write(bytestring, 0, bytestring.length);
1199
    zout.closeEntry(); //get ready for the next entry.
1200
1201
    //zip up the related documents
1202
    for(int i=0; i<reldocs.length; i++)
1203
    {
1204 566 jones
      //MetacatURL murl = new MetacatURL(((String)reldocs[i]));
1205
      URL murl = new URL(((String)reldocs[i]));
1206
      Hashtable qparams = util.parseQuery(murl.getQuery());
1207
      if(murl.getProtocol().equals("metacat"))
1208 458 berkley
      {
1209
        //get the document from the database
1210 566 jones
        //xmldoc = new DocumentImpl(conn, (String)murl.getHashParam("docid"));
1211
        xmldoc = new DocumentImpl(conn, (String)qparams.get("docid"));
1212 458 berkley
        bytestring = (xmldoc.toString()).getBytes();
1213 566 jones
        zentry = new ZipEntry(qparams.get("docid") + ".xml");
1214 458 berkley
        //create a new zip entry and write the file to the stream
1215
        zentry.setSize(bytestring.length);
1216
        zout.putNextEntry(zentry);
1217
        zout.write(bytestring, 0, bytestring.length);
1218
        zout.closeEntry(); //get ready for the next entry.
1219
      }
1220 566 jones
      else if(murl.getProtocol().equals("http"))
1221 458 berkley
      {
1222 566 jones
        //Hashtable murlParams = murl.getHashParams();
1223
        if(qparams.containsKey("httpurl"))
1224 458 berkley
        {//httpurl is the param name for an http url.
1225 566 jones
          URL urlconn = new URL((String)qparams.get("httpurl"));
1226 473 berkley
          //create a new url obj.
1227 458 berkley
          BufferedReader htmldoc = new BufferedReader(
1228
                                   new InputStreamReader(urlconn.openStream()));
1229
          //get the data from the web server
1230
          try
1231
          { //zip the document
1232
            String line=null;
1233 566 jones
            zentry = new ZipEntry((String)qparams.get("filename"));
1234 458 berkley
            //get just the filename from the URL.
1235
            zout.putNextEntry(zentry);
1236
            //make a new entry in the zip file stream
1237
            while((line = htmldoc.readLine()) != null)
1238
            {
1239
              bytestring = (line.toString()).getBytes();
1240
              zout.write(bytestring, 0, bytestring.length);
1241
              //write out the file line by line
1242
            }
1243
            zout.closeEntry(); //close the entry in the file
1244
          }
1245
          catch(Exception e)
1246
          {
1247
            util.debugMessage("error downloading html document");
1248
          }
1249
        }
1250
      }
1251
    }
1252
    zout.finish();  //terminate the zip file
1253
    zout.close();   //close the stream.
1254
    util.returnConnection(conn); //return the connection to the pool
1255
  }
1256
  catch(Exception e)
1257
  {
1258
    System.out.println("Error creating zip file: " + e.getMessage());
1259
    e.printStackTrace(System.out);
1260
  }
1261
1262
   /*
1263
   //////////old code using a shell script/////////////////////////////////
1264
1265 91 higgins
      boolean error_flag = false;
1266
      String error_message = "";
1267
      // Get the document indicated
1268
      String[] datadoc = (String[])params.get("datadoc");
1269 185 jones
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1270
      // executescript = "test.bat";        // for testing only!!!
1271 91 higgins
1272
      // set content type and other response header fields first
1273
      response.setContentType("application/octet-stream");
1274 185 jones
      if (defaultdatapath!=null) {
1275
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1276
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1277 91 higgins
        }
1278 185 jones
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1279
        if (executescript!=null) {
1280
          String command = null;
1281
          File scriptfile = new File(executescript);
1282
          if (scriptfile.exists()) {
1283
            command=executescript+" "+datadoc[0]; // script includes path
1284
        } else {     // look in defaultdatapath
1285
            // on Win98 one MUST include the .bat extender
1286
            command = defaultdatapath+executescript+" "+datadoc[0];
1287
        }
1288 91 higgins
      System.out.println(command);
1289
      try {
1290
      Process proc = Runtime.getRuntime().exec(command);
1291
      proc.waitFor();
1292
      }
1293
      catch (Exception eee) {
1294
        System.out.println("Error running process!");
1295
        error_flag = true;
1296
        error_message = "Error running process!";}
1297
      } // end executescript not null if
1298
      File datafile = new File(defaultdatapath+datadoc[0]);
1299
      try {
1300
      FileInputStream fw = new FileInputStream(datafile);
1301
      int x;
1302 185 jones
      while ((x = fw.read())!=-1) {
1303 91 higgins
        out.write(x); }
1304 185 jones
        fw.close();
1305
      } catch (Exception e) {
1306 91 higgins
        System.out.println("Error in returning file\n"+e.getMessage());
1307
        error_flag=true;
1308 185 jones
        error_message = error_message+"\nError in returning file\n"+
1309
                        e.getMessage();
1310
      }
1311
    } // end defaultdatapath not null if
1312 458 berkley
    */
1313 91 higgins
  }
1314 302 bojilova
1315
  /**
1316
   * Handle the getdoctypes Action.
1317
   * Read all doctypes from db connection in XML format
1318
   */
1319
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1320
                                       HttpServletResponse response) {
1321
1322 309 bojilova
    Connection conn = null;
1323
1324 302 bojilova
    try {
1325
1326 309 bojilova
        // get connection from the pool
1327
        conn = util.getConnection();
1328
        DBUtil dbutil = new DBUtil(conn);
1329 302 bojilova
        String doctypes = dbutil.readDoctypes();
1330
        out.println(doctypes);
1331
1332
    } catch (Exception e) {
1333
      out.println("<?xml version=\"1.0\"?>");
1334
      out.println("<error>");
1335
      out.println(e.getMessage());
1336
      out.println("</error>");
1337 309 bojilova
    } finally {
1338 320 bojilova
      util.returnConnection(conn);
1339 309 bojilova
    }
1340 302 bojilova
1341
  }
1342
1343
  /**
1344
   * Handle the getdataguide Action.
1345
   * Read Data Guide for a given doctype from db connection in XML format
1346
   */
1347
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
1348
                                        HttpServletResponse response) {
1349
1350 309 bojilova
    Connection conn = null;
1351 316 bojilova
    String doctype = null;
1352
    String[] doctypeArr = (String[])params.get("doctype");
1353 309 bojilova
1354 316 bojilova
    // get only the first doctype specified in the list of doctypes
1355
    // it could be done for all doctypes in that list
1356
    if (doctypeArr != null) {
1357
        doctype = ((String[])params.get("doctype"))[0];
1358
    }
1359
1360 302 bojilova
    try {
1361
1362 309 bojilova
        // get connection from the pool
1363
        conn = util.getConnection();
1364
        DBUtil dbutil = new DBUtil(conn);
1365 316 bojilova
        String dataguide = dbutil.readDataGuide(doctype);
1366 302 bojilova
        out.println(dataguide);
1367
1368
    } catch (Exception e) {
1369
      out.println("<?xml version=\"1.0\"?>");
1370
      out.println("<error>");
1371
      out.println(e.getMessage());
1372
      out.println("</error>");
1373 309 bojilova
    } finally {
1374 320 bojilova
      util.returnConnection(conn);
1375 309 bojilova
    }
1376 302 bojilova
1377
  }
1378
1379 46 jones
}