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
    //if the user clicked on the input images, decode which image
214
    //was clicked then set the action.
215
    String action = decodeMouseAction(params);
216
    if(action.equals("error"))
217
    {
218
      action = ((String[])params.get("action"))[0];
219 103 jones
    }
220 355 berkley
221 380 jones
    // This block handles session management for the servlet
222
    // by looking up the current session information for all actions
223
    // other than "Login" and "Logout"
224 210 bojilova
    // handle login action
225 425 bojilova
    String username = null;
226
    String groupname = null;
227 297 bojilova
    if (action.equals("Login") || action.equals("Login Client")) {
228 458 berkley
      handleLoginAction(response.getWriter(), params, request, response);
229 210 bojilova
    // handle logout action
230 345 bojilova
    } else if (action.equals("Logout") || action.equals("Logout Client")) {
231 210 bojilova
      HttpSession sess = request.getSession(false);
232 251 bojilova
      if (sess != null) { sess.invalidate();  }
233 345 bojilova
      if (action.equals("Logout Client")) {
234 458 berkley
        PrintWriter out = response.getWriter();
235 345 bojilova
        out.println("<?xml version=\"1.0\"?>");
236
        out.println("<success>");
237
        out.println("User logout.");
238
        out.println("</success>");
239
        return;
240
      }
241 361 berkley
242 360 bojilova
      response.sendRedirect(htmlpath + "/index.html");
243 361 berkley
244 251 bojilova
    // aware of session expiration on every request
245 343 jones
    } else {
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 328 bojilova
        // redirect to default page for query only access
250 441 bojilova
        //  response.sendRedirect(htmlpath + "/sexpire.html");
251
        username = "public";
252 425 bojilova
      } else {
253
        username = (String)sess.getAttribute("username");
254
        groupname = (String)sess.getAttribute("groupname");
255
      }
256 210 bojilova
    }
257 219 jones
258 380 jones
    // Now that we know the session is valid, we can delegate the request
259
    // to a particular action handler
260 361 berkley
    if(action.equals("query"))
261
    {
262 458 berkley
      handleQuery(response.getWriter(), params, response, username, groupname);
263 373 berkley
    }
264 371 berkley
    else if(action.equals("squery"))
265 361 berkley
    {
266 373 berkley
      if(params.containsKey("query"))
267
      {
268 458 berkley
        handleSQuery(response.getWriter(), params, response, username, groupname);
269 373 berkley
      }
270
      else
271
      {
272 458 berkley
        PrintWriter out = response.getWriter();
273 373 berkley
        out.println("Illegal action squery without \"query\" parameter");
274
      }
275
    }
276 361 berkley
    else if (action.equals("getdocument")) {
277 458 berkley
      PrintWriter out = response.getWriter();
278 87 jones
      try {
279
        handleGetDocumentAction(out, params, response);
280
      } catch (ClassNotFoundException e) {
281 103 jones
        out.println(e.getMessage());
282 87 jones
      } catch (SQLException se) {
283 103 jones
        out.println(se.getMessage());
284 87 jones
      }
285 453 berkley
    }
286
    else if (action.equals("getrelateddocument")) {
287 458 berkley
      PrintWriter out = response.getWriter();
288 453 berkley
      try {
289
        handleGetRelatedDocumentAction(out, params, response);
290
      } catch (ClassNotFoundException e) {
291
        out.println(e.getMessage());
292
      } catch (SQLException se) {
293
        out.println(se.getMessage());
294
      }
295
    }
296
    else if (action.equals("insert") || action.equals("update")) {
297 458 berkley
      PrintWriter out = response.getWriter();
298 425 bojilova
      if ( !username.equals("public") && (username != null) ) {
299
        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 425 bojilova
      if ( !username.equals("public") && (username != null) ) {
306
        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 297 bojilova
    } else if (action.equals("Login") || action.equals("Login Client")) {
333 50 jones
    } else {
334 458 berkley
      PrintWriter out = response.getWriter();
335 50 jones
      out.println("Error: action not registered.  Please report this error.");
336 46 jones
    }
337 465 berkley
    util.closeConnections();
338 49 jones
    // Close the stream to the client
339 458 berkley
    //out.close();
340 46 jones
  }
341 355 berkley
342
  /**
343
   * decodes the mouse click information coming from the client.
344
   * This function may be overwritten to provide specific functionality
345
   * for different applications.
346
   * @param params the parameters from the CGI
347
   * @return action the action to be performed or "error" if an error was
348
   * generated
349
   */
350 375 berkley
  protected String decodeMouseAction(Hashtable params)
351 355 berkley
  {
352
    // Determine what type of request the user made
353
    // if the action parameter is set, use it as a default
354
    // but if the ypos param is set, calculate the action needed
355
    String action=null;
356
    long ypos = 0;
357
    try {
358
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
359
      //out.println("<P>YPOS IS " + ypos);
360
      if (ypos <= 13) {
361
        action = "getdocument";
362
      } else if (ypos > 13 && ypos <= 27) {
363
        action = "validate";
364
      } else if (ypos > 27) {
365
        action = "transform";
366
      }
367
      return action;
368
    } catch (Exception npe) {
369 380 jones
      //
370
      // MBJ -- NOTE that this should be handled more gracefully with
371
      //        the new exception infrastructure -- this "error" return
372
      //        value is inappropriate
373 355 berkley
      //out.println("<P>Caught exception looking for Y value.");
374
      return "error";
375 382 berkley
    }
376 355 berkley
  }
377 49 jones
378 50 jones
  /**
379 210 bojilova
   * Handle the Login request. Create a new session object.
380
   * Make a user authentication through SRB RMI Connection.
381
   */
382
  private void handleLoginAction(PrintWriter out, Hashtable params,
383
               HttpServletRequest request, HttpServletResponse response) {
384 251 bojilova
385 297 bojilova
    MetaCatSession sess = null;
386 228 bojilova
    String un = ((String[])params.get("username"))[0];
387
    String pw = ((String[])params.get("password"))[0];
388 297 bojilova
    String action = ((String[])params.get("action"))[0];
389 332 bojilova
390 297 bojilova
    try {
391
        sess = new MetaCatSession(request, un, pw);
392
    } catch (Exception e) {
393
      out.println(e.getMessage());
394
    }
395 411 bojilova
396
    String output = null;
397
    output = sess.userLogin(response, un, pw, action, htmlpath);
398
    out.println(output);
399 297 bojilova
400 370 berkley
  }
401
402 373 berkley
  /**
403 380 jones
   * Retreive the squery xml, execute it and display it
404
   *
405
   * @param out the output stream to the client
406
   * @param params the Hashtable of parameters that should be included
407
   * in the squery.
408
   * @param response the response object linked to the client
409
   * @param conn the database connection
410
   */
411
  protected void handleSQuery(PrintWriter out, Hashtable params,
412 441 bojilova
                 HttpServletResponse response, String user, String group)
413 373 berkley
  {
414 380 jones
    String xmlquery = ((String[])params.get("query"))[0];
415
    String qformat = ((String[])params.get("qformat"))[0];
416 465 berkley
    String resultdoc = null;
417
    String[] returndoc = null;
418
    if(params.contains("returndoc"))
419
    {
420
      returndoc = (String[])params.get("returndoc");
421
    }
422
423
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
424
    //String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
425 444 berkley
426 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
427
428 380 jones
    //format and transform the results
429
    if(qformat.equals("html")) {
430
      transformResultset(resultdoc, response, out);
431
    } else if(qformat.equals("xml")) {
432
      response.setContentType("text/xml");
433
      out.println(resultdoc);
434
    } else {
435
      out.println("invalid qformat: " + qformat);
436
    }
437 341 berkley
  }
438
439
   /**
440 380 jones
    * Create the xml query, execute it and display the results.
441
    *
442
    * @param out the output stream to the client
443
    * @param params the Hashtable of parameters that should be included
444 370 berkley
    * in the squery.
445 380 jones
    * @param response the response object linked to the client
446 370 berkley
    */
447 375 berkley
  protected void handleQuery(PrintWriter out, Hashtable params,
448 441 bojilova
                 HttpServletResponse response, String user, String group)
449 341 berkley
  {
450 370 berkley
    //create the query and run it
451 465 berkley
    String[] returndoc = null;
452
    if(params.containsKey("returndoc"))
453
    {
454
      returndoc = (String[])params.get("returndoc");
455
    }
456 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
457 465 berkley
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
458
    String qformat = ((String[])params.get("qformat"))[0];
459
    String resultdoc = null;
460
461
    resultdoc = createResultDocument(doclist, transformQuery(params));
462 425 bojilova
463 370 berkley
    //format and transform the results
464 380 jones
    if(qformat.equals("html")) {
465 370 berkley
      transformResultset(resultdoc, response, out);
466 380 jones
    } else if(qformat.equals("xml")) {
467 370 berkley
      response.setContentType("text/xml");
468
      out.println(resultdoc);
469 443 berkley
    } else {
470 370 berkley
      out.println("invalid qformat: " + qformat);
471
    }
472 341 berkley
  }
473
474
  /**
475 384 berkley
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
476
   * so it can properly be placed in the <query> tag of the resultset.
477
   * This method is overwritable so that other applications can customize
478
   * the structure of what is in the <query> tag.
479
   *
480
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
481
   */
482
  protected String transformQuery(Hashtable params)
483
  {
484
    //DBQuery.createSQuery is a re-calling of a previously called
485
    //function but it is necessary
486
    //so that overriding methods have access to the params hashtable
487
    String xmlquery = DBQuery.createSQuery(params);
488
    //the <?xml version="1.0"?> tag is the first 22 characters of the
489
    xmlquery = xmlquery.trim();
490
    int index = xmlquery.indexOf("?>");
491
    return xmlquery.substring(index + 2, xmlquery.length());
492
  }
493
494
  /**
495 443 berkley
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
496
   * string as a param instead of a hashtable.
497
   *
498
   * @param xmlquery a string representing a query.
499
   */
500
  protected String transformQuery(String xmlquery)
501
  {
502
    xmlquery = xmlquery.trim();
503
    int index = xmlquery.indexOf("?>");
504
    return xmlquery.substring(index + 2, xmlquery.length());
505
  }
506
507
  /**
508 380 jones
   * Run the query and return a hashtable of results.
509
   *
510
   * @param xmlquery the query to run
511
   */
512 465 berkley
  private Hashtable runQuery(String xmlquery, String user, String group,
513
                             String[] returndoc)
514 341 berkley
  {
515
    Hashtable doclist=null;
516
    Connection conn = null;
517
    try
518
    {
519 441 bojilova
      conn = util.getConnection();
520
      DBQuery queryobj = new DBQuery(conn, saxparser);
521 465 berkley
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
522
                                       returndoc);
523 441 bojilova
      util.returnConnection(conn);
524
      return doclist;
525 341 berkley
    }
526
    catch (Exception e)
527
    {
528 441 bojilova
      util.returnConnection(conn);
529 341 berkley
      util.debugMessage("Error in runQuery: " + e.getMessage());
530
      doclist = null;
531
      return doclist;
532
    }
533
  }
534
535 380 jones
  /**
536 370 berkley
   * Transorms an xml resultset document to html and sends it to the browser
537 380 jones
   *
538 370 berkley
   * @param resultdoc the string representation of the document that needs
539
   * to be transformed.
540
   * @param response the HttpServletResponse object bound to the client.
541
   * @param out the output stream to the client
542 375 berkley
   */
543
  protected void transformResultset(String resultdoc,
544 380 jones
                                    HttpServletResponse response,
545
                                    PrintWriter out)
546 370 berkley
  {
547
    Connection conn = null;
548 380 jones
    try {
549 370 berkley
      conn = util.getConnection();
550
      DBTransform trans = new DBTransform(conn);
551
      response.setContentType("text/html");
552
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
553
                                 "-//W3C//HTML//EN", out);
554 382 berkley
      util.returnConnection(conn);
555
    }
556
    catch(Exception e)
557
    {
558 441 bojilova
      util.returnConnection(conn);
559 370 berkley
    }
560
  }
561
562 355 berkley
  /**
563
   * Transforms a hashtable of documents to an xml or html result.
564 465 berkley
   * If there is a returndoc, then it only displays documents of
565
   * whatever type returndoc represents.  If a result is found in a document
566
   * that is not of type returndoc then this attempts to find a relation
567
   * between this document and one that satifies the returndoc doctype.
568 380 jones
   *
569 355 berkley
   * @param doclist- the hashtable to transform
570
   * @param xmlquery- the query that returned the dolist result
571 465 berkley
   * @param resultdoc- the document type to backtrack to.
572 355 berkley
   */
573 375 berkley
  protected String createResultDocument(Hashtable doclist, String xmlquery)
574 341 berkley
  {
575
    // Create a buffer to hold the xml result
576
    StringBuffer resultset = new StringBuffer();
577
578 382 berkley
    // Print the resulting root nodes
579 341 berkley
    String docid = null;
580
    String document = null;
581
    resultset.append("<?xml version=\"1.0\"?>\n");
582
    resultset.append("<resultset>\n");
583 465 berkley
584 384 berkley
    resultset.append("  <query>" + xmlquery + "</query>");
585 465 berkley
586 341 berkley
    Enumeration doclistkeys = doclist.keys();
587
    while (doclistkeys.hasMoreElements())
588
    {
589
      docid = (String)doclistkeys.nextElement();
590
      document = (String)doclist.get(docid);
591
      resultset.append("  <document>" + document + "</document>");
592 373 berkley
    }
593 341 berkley
    resultset.append("</resultset>");
594 444 berkley
    //System.out.println(resultset.toString());
595 370 berkley
    return resultset.toString();
596 341 berkley
  }
597 437 berkley
598
  /**
599
   * Handle the request to view the abstract of a document.
600 444 berkley
   * The abstractpath CGI parameter gives the xml path to the abstract
601
   * node.
602 437 berkley
   */
603
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
604
               HttpServletResponse response) throws IOException, SQLException
605
  {
606
    String abstractpath = null;
607
    String docid = null;
608
    Connection conn = null;
609
    response.setContentType("text/html");
610
    try
611
    {
612
      docid = ((String[])params.get("docid"))[0];
613
      if(params.containsKey("abstractpath"))
614
      {
615 444 berkley
        //the CGI parameter abstractpath holds the path to the abstract
616
        //that should be displayed.
617 437 berkley
        abstractpath = ((String[])params.get("abstractpath"))[0];
618
      }
619
      else
620
      {
621
        out.println("error: no abstractpath parameter");
622
      }
623
      conn = util.getConnection();
624
625
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
626
627 444 berkley
      out.println("<html><head><title>Abstract</title></head>");
628
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
629 437 berkley
      for(int i=0; i<abstracts.length; i++)
630
      {
631
        out.println("<p>" + (String)abstracts[i] + "</p>");
632
      }
633
      out.println("</body></html>");
634
    }
635
    catch (IOException ioe)
636
    {
637 444 berkley
       util.debugMessage("error in handlegetabstract: " + ioe.getMessage());
638 437 berkley
    }
639
    catch(SQLException sqle)
640
    {
641 444 berkley
      util.debugMessage("error in handlegetabstract: " + sqle.getMessage());
642 437 berkley
    }
643
    catch(Exception e)
644
    {
645 444 berkley
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
646 437 berkley
    }
647
648
    util.returnConnection(conn);
649
  }
650 181 jones
651 50 jones
  /**
652 453 berkley
   * Handle the database getrelateddocument request and return a XML document,
653
   * possibly transformed from XML into HTML
654
   */
655
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params,
656
               HttpServletResponse response)
657
               throws ClassNotFoundException, IOException, SQLException
658
  {
659
    String docid = null;
660
    Connection conn = null;
661
662
    if(params.containsKey("url"))
663
    {//the identifier for the related document is contained in the URL param
664
      try
665
      {
666
        DocumentImpl xmldoc=null;
667
        metacatURL murl = new metacatURL(((String[])params.get("url"))[0]);
668
        if(murl.getURLType().equals("metacat"))
669
        {//get the document from the database if it is the right type of url
670
          String[] murlParams = murl.getParam(0);
671
          if(murlParams[0].equals("docid"))
672
          {//the docid should be first
673 465 berkley
            //murl.printParams();
674 453 berkley
            docid = murlParams[1]; //get the docid value
675
            conn = util.getConnection();
676
            xmldoc = new DocumentImpl(conn, docid);
677
678
            //**************************************************
679
            //the style sheet handling code needs to be put here.
680
            out.println(xmldoc.toString());
681
            //**************************************************
682
          }
683
          else
684
          {
685
            //throw new Exception("handleGetDocument: bad URL");
686
            System.err.println("handleGetDocument: bad URL");
687
          }
688
        }
689
        else if(murl.getURLType().equals("http"))
690
        {//get the document from the internet
691
          String[] murlParams = murl.getParam(0);
692
          if(murlParams[0].equals("httpurl"))
693
          {//httpurl is the param name for an http url.
694
            URL urlconn = new URL(murlParams[1]);  //create a new url obj.
695 458 berkley
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
696
            BufferedReader htmldoc = new BufferedReader(
697
                                   new InputStreamReader(urlconn.openStream()));
698 453 berkley
            //bind a data stream.
699
            try
700
            { //display the document
701
              String line=null;
702
              while((line = htmldoc.readLine()) != null)
703
              {
704
                out.println(line);
705
              }
706
            }
707
            catch(Exception e)
708
            {
709
              util.debugMessage("error viewing html document");
710
            }
711
          }
712
        }
713
      }
714
      catch (McdbException e) {
715
        response.setContentType("text/xml");
716
        e.toXml(out);
717
      } catch   (Throwable t) {
718
        response.setContentType("text/html");
719
        out.println(t.getMessage());
720
      } finally {
721
        util.returnConnection(conn);
722
      }
723
    }
724
  }
725
726
  /**
727 50 jones
   * Handle the database getdocument request and return a XML document,
728
   * possibly transformed from XML into HTML
729
   */
730 382 berkley
  private void handleGetDocumentAction(PrintWriter out, Hashtable params,
731 87 jones
               HttpServletResponse response)
732
               throws ClassNotFoundException, IOException, SQLException {
733 102 jones
    String docidstr = null;
734 162 bojilova
    String docid = null;
735 102 jones
    String doc = null;
736 309 bojilova
    Connection conn = null;
737
738 102 jones
    try {
739 87 jones
      // Find the document id number
740 102 jones
      docidstr = ((String[])params.get("docid"))[0];
741 162 bojilova
      docid = docidstr;
742 309 bojilova
      conn = util.getConnection();
743 393 jones
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
744
      // Get the document indicated from the db
745
      //doc = docreader.readXMLDocument(docid);
746 85 jones
747 87 jones
      // Return the document in XML or HTML format
748 437 berkley
      String qformat=null;
749
      if(params.containsKey("qformat"))
750
      {
751
        qformat = ((String[])params.get("qformat"))[0];
752
      }
753
      else
754
      {
755
        qformat = "html";
756
      }
757
      if (qformat.equals("xml")) {
758 85 jones
        // set content type and other response header fields first
759
        response.setContentType("text/xml");
760 431 jones
        xmldoc.toXml(out);
761
        //out.println(xmldoc);
762 85 jones
      } else if (qformat.equals("html")) {
763 437 berkley
        response.setContentType("text/html");
764 87 jones
        // Look up the document type
765 393 jones
        String sourcetype = xmldoc.getDoctype();
766 87 jones
        // Transform the document to the new doctype
767 393 jones
        DBTransform dbt = new DBTransform(conn);
768
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype,
769
                                 "-//W3C//HTML//EN", out);
770 85 jones
      }
771 343 jones
    } catch (McdbException e) {
772
      response.setContentType("text/xml");
773
      e.toXml(out);
774
    } catch (Throwable t) {
775 309 bojilova
      response.setContentType("text/html");
776 343 jones
      out.println(t.getMessage());
777 309 bojilova
    } finally {
778 320 bojilova
      util.returnConnection(conn);
779 309 bojilova
    }
780
781 49 jones
  }
782 55 jones
783
  /**
784
   * Handle the database putdocument request and write an XML document
785
   * to the database connection
786
   */
787 382 berkley
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
788 425 bojilova
               HttpServletResponse response, String user, String group) {
789 59 jones
790 309 bojilova
    Connection conn = null;
791
792 204 jones
    try {
793
      // Get the document indicated
794
      String[] doctext = (String[])params.get("doctext");
795
      StringReader xml = null;
796
      try {
797
        xml = new StringReader(doctext[0]);
798 59 jones
799 204 jones
        String[] action = (String[])params.get("action");
800
        String[] docid = (String[])params.get("docid");
801
        String newdocid = null;
802 203 jones
803 204 jones
        String doAction = null;
804
        if (action[0].equals("insert")) {
805
          doAction = "INSERT";
806
        } else if (action[0].equals("update")) {
807
          doAction = "UPDATE";
808
        }
809 203 jones
810 204 jones
        try {
811 309 bojilova
            // get a connection from the pool
812
            conn = util.getConnection();
813 408 jones
814 309 bojilova
            // write the document to the database
815
            try {
816
                String accNumber = docid[0];
817
                if (accNumber.equals("")) {
818
                    accNumber = null;
819
                }
820 425 bojilova
                newdocid = DocumentImpl.write(conn, xml, doAction, accNumber,
821 465 berkley
                                              user, group);
822
                DocumentImpl xmldoc = new DocumentImpl(conn, newdocid);
823
824
               //if this is a package file then write the package info to
825
               //the xml_relation table. relationHandler checks to see
826
               //if it is a package file so you don't have to do it here.
827
               relationHandler rth = new relationHandler(xmldoc);
828
829 309 bojilova
            } catch (NullPointerException npe) {
830 425 bojilova
              newdocid = DocumentImpl.write(conn,xml,doAction,null,user,group);
831 309 bojilova
            }
832 462 bojilova
//        } catch (Exception e) {
833
//          response.setContentType("text/html");
834
//          out.println(e.getMessage());
835 309 bojilova
        } finally {
836 320 bojilova
          util.returnConnection(conn);
837 309 bojilova
        }
838
839 204 jones
        // set content type and other response header fields first
840
        response.setContentType("text/xml");
841
        out.println("<?xml version=\"1.0\"?>");
842
        out.println("<success>");
843
        out.println("<docid>" + newdocid + "</docid>");
844
        out.println("</success>");
845
846 203 jones
      } catch (NullPointerException npe) {
847 204 jones
        response.setContentType("text/xml");
848
        out.println("<?xml version=\"1.0\"?>");
849
        out.println("<error>");
850
        out.println(npe.getMessage());
851
        out.println("</error>");
852 55 jones
      }
853 204 jones
    } catch (Exception e) {
854
      response.setContentType("text/xml");
855
      out.println("<?xml version=\"1.0\"?>");
856
      out.println("<error>");
857
      out.println(e.getMessage());
858
      if (e instanceof SAXException) {
859
        Exception e2 = ((SAXException)e).getException();
860
        out.println("<error>");
861
        out.println(e2.getMessage());
862
        out.println("</error>");
863
      }
864
      //e.printStackTrace(out);
865
      out.println("</error>");
866 203 jones
    }
867 55 jones
  }
868 203 jones
869
  /**
870
   * Handle the database delete request and delete an XML document
871
   * from the database connection
872
   */
873
  private void handleDeleteAction(PrintWriter out, Hashtable params,
874 425 bojilova
               HttpServletResponse response, String user, String group) {
875 203 jones
876
    String[] docid = (String[])params.get("docid");
877 309 bojilova
    Connection conn = null;
878 203 jones
879
    // delete the document from the database
880
    try {
881 309 bojilova
      // get a connection from the pool
882
      conn = util.getConnection();
883 203 jones
                                      // NOTE -- NEED TO TEST HERE
884 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
885 203 jones
                                      // BEFORE ACCESSING ARRAY
886 375 berkley
      try {
887 425 bojilova
        DocumentImpl.delete(conn, docid[0], user, group);
888 204 jones
        response.setContentType("text/xml");
889
        out.println("<?xml version=\"1.0\"?>");
890
        out.println("<success>");
891 203 jones
        out.println("Document deleted.");
892 204 jones
        out.println("</success>");
893 203 jones
      } catch (AccessionNumberException ane) {
894 204 jones
        response.setContentType("text/xml");
895
        out.println("<?xml version=\"1.0\"?>");
896
        out.println("<error>");
897
        out.println("Error deleting document!!!");
898 203 jones
        out.println(ane.getMessage());
899 204 jones
        out.println("</error>");
900 203 jones
      }
901 204 jones
    } catch (Exception e) {
902
      response.setContentType("text/xml");
903
      out.println("<?xml version=\"1.0\"?>");
904
      out.println("<error>");
905
      out.println(e.getMessage());
906
      out.println("</error>");
907 309 bojilova
    } finally {
908 320 bojilova
      util.returnConnection(conn);
909 309 bojilova
    }
910 203 jones
  }
911 68 higgins
912
  /**
913 380 jones
   * Handle the validation request and return the results to the requestor
914 68 higgins
   */
915 185 jones
  private void handleValidateAction(PrintWriter out, Hashtable params,
916
               HttpServletResponse response) {
917 68 higgins
918 103 jones
    // Get the document indicated
919
    String valtext = null;
920 309 bojilova
921 103 jones
    try {
922
      valtext = ((String[])params.get("valtext"))[0];
923
    } catch (Exception nullpe) {
924 68 higgins
925 309 bojilova
      Connection conn = null;
926 162 bojilova
      String docid = null;
927 103 jones
      try {
928
        // Find the document id number
929 185 jones
        docid = ((String[])params.get("docid"))[0];
930 309 bojilova
931
        // get a connection from the pool
932
        conn = util.getConnection();
933 393 jones
934 309 bojilova
        // Get the document indicated from the db
935 393 jones
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
936
        valtext = xmldoc.toString();
937 185 jones
938 103 jones
      } catch (NullPointerException npe) {
939 253 jones
        response.setContentType("text/xml");
940
        out.println("<error>Error getting document ID: " + docid + "</error>");
941 320 bojilova
        if ( conn != null ) { util.returnConnection(conn); }
942 380 jones
        return;
943 309 bojilova
      } catch (Exception e) {
944
        response.setContentType("text/html");
945
        out.println(e.getMessage());
946
      } finally {
947 320 bojilova
        util.returnConnection(conn);
948 309 bojilova
      }
949 103 jones
    }
950 68 higgins
951 309 bojilova
    Connection conn = null;
952 103 jones
    try {
953 309 bojilova
      // get a connection from the pool
954
      conn = util.getConnection();
955 253 jones
      DBValidate valobj = new DBValidate(saxparser,conn);
956 185 jones
      boolean valid = valobj.validateString(valtext);
957 68 higgins
958
      // set content type and other response header fields first
959 253 jones
      response.setContentType("text/xml");
960
      out.println(valobj.returnErrors());
961
962 103 jones
    } catch (NullPointerException npe2) {
963
      // set content type and other response header fields first
964 253 jones
      response.setContentType("text/xml");
965
      out.println("<error>Error validating document.</error>");
966 309 bojilova
    } catch (Exception e) {
967
      response.setContentType("text/html");
968
      out.println(e.getMessage());
969
    } finally {
970 320 bojilova
      util.returnConnection(conn);
971 309 bojilova
    }
972 103 jones
  }
973 87 jones
974
  /**
975 380 jones
   * Handle the document request and return the results to the requestor
976 458 berkley
   * If a docid is passed in through the params then that document
977
   * will be retrieved form the DB and put in the zip file.
978
   * In addition if 1 or more relations parameters are passed, those file
979
   * will be zipped as well.  Currently this is only implemented for
980
   * metacat:// and http:// files.  Support should be added for srb:// files
981
   * as well.
982 91 higgins
   */
983 458 berkley
  private void handleGetDataDocumentAction(ServletOutputStream out,
984
               Hashtable params,
985 185 jones
               HttpServletResponse response) {
986 458 berkley
  //find the related files, get them from their source and zip them into
987
  //a zip file.
988
  try
989
  {
990
    Connection conn = util.getConnection();
991
    String currentDocid = ((String[])params.get("docid"))[0];
992
    ZipOutputStream zout = new ZipOutputStream(out);
993
    byte[] bytestring = null;
994
    ZipEntry zentry = null;
995
    DocumentImpl xmldoc = null;
996
    String[] reldocs = null;
997
998
    if(params.containsKey("relation"))
999
    { //get the relations from the parameters.
1000
      reldocs = ((String[])params.get("relation"));
1001
    }
1002
    else
1003
    { //let the for loop know that there are no relations to zip
1004
      reldocs = new String[0];
1005
    }
1006
1007
    //write the base file to the zip file.
1008
    xmldoc = new DocumentImpl(conn, currentDocid);
1009
    bytestring = (xmldoc.toString()).getBytes();
1010
    zentry = new ZipEntry(currentDocid + ".xml");
1011
    //create a new zip entry and write the file to the stream
1012
    zentry.setSize(bytestring.length);
1013
    zout.putNextEntry(zentry);
1014
    zout.write(bytestring, 0, bytestring.length);
1015
    zout.closeEntry(); //get ready for the next entry.
1016
1017
    //zip up the related documents
1018
    for(int i=0; i<reldocs.length; i++)
1019
    {
1020
      metacatURL murl = new metacatURL(((String)reldocs[i]));
1021
      if(murl.getURLType().equals("metacat"))
1022
      {
1023
        //get the document from the database
1024
        xmldoc = new DocumentImpl(conn, (murl.getParam(0))[1]);
1025
        bytestring = (xmldoc.toString()).getBytes();
1026
        zentry = new ZipEntry((murl.getParam(0))[1] + ".xml");
1027
        //create a new zip entry and write the file to the stream
1028
        zentry.setSize(bytestring.length);
1029
        zout.putNextEntry(zentry);
1030
        zout.write(bytestring, 0, bytestring.length);
1031
        zout.closeEntry(); //get ready for the next entry.
1032
      }
1033
      else if(murl.getURLType().equals("http"))
1034
      {
1035
        String[] murlParams = murl.getParam(0);
1036
        if(murlParams[0].equals("httpurl"))
1037
        {//httpurl is the param name for an http url.
1038
          URL urlconn = new URL(murlParams[1]);  //create a new url obj.
1039
          BufferedReader htmldoc = new BufferedReader(
1040
                                   new InputStreamReader(urlconn.openStream()));
1041
          //get the data from the web server
1042
          try
1043
          { //zip the document
1044
            String line=null;
1045
            zentry = new ZipEntry((murl.getParam(1))[1]);
1046
            //get just the filename from the URL.
1047
            zout.putNextEntry(zentry);
1048
            //make a new entry in the zip file stream
1049
            while((line = htmldoc.readLine()) != null)
1050
            {
1051
              bytestring = (line.toString()).getBytes();
1052
              zout.write(bytestring, 0, bytestring.length);
1053
              //write out the file line by line
1054
            }
1055
            zout.closeEntry(); //close the entry in the file
1056
          }
1057
          catch(Exception e)
1058
          {
1059
            util.debugMessage("error downloading html document");
1060
          }
1061
        }
1062
      }
1063
    }
1064
    zout.finish();  //terminate the zip file
1065
    zout.close();   //close the stream.
1066
    util.returnConnection(conn); //return the connection to the pool
1067
  }
1068
  catch(Exception e)
1069
  {
1070
    System.out.println("Error creating zip file: " + e.getMessage());
1071
    e.printStackTrace(System.out);
1072
  }
1073
1074
   /*
1075
   //////////old code using a shell script/////////////////////////////////
1076
1077 91 higgins
      boolean error_flag = false;
1078
      String error_message = "";
1079
      // Get the document indicated
1080
      String[] datadoc = (String[])params.get("datadoc");
1081 185 jones
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1082
      // executescript = "test.bat";        // for testing only!!!
1083 91 higgins
1084
      // set content type and other response header fields first
1085
      response.setContentType("application/octet-stream");
1086 185 jones
      if (defaultdatapath!=null) {
1087
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1088
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1089 91 higgins
        }
1090 185 jones
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1091
        if (executescript!=null) {
1092
          String command = null;
1093
          File scriptfile = new File(executescript);
1094
          if (scriptfile.exists()) {
1095
            command=executescript+" "+datadoc[0]; // script includes path
1096
        } else {     // look in defaultdatapath
1097
            // on Win98 one MUST include the .bat extender
1098
            command = defaultdatapath+executescript+" "+datadoc[0];
1099
        }
1100 91 higgins
      System.out.println(command);
1101
      try {
1102
      Process proc = Runtime.getRuntime().exec(command);
1103
      proc.waitFor();
1104
      }
1105
      catch (Exception eee) {
1106
        System.out.println("Error running process!");
1107
        error_flag = true;
1108
        error_message = "Error running process!";}
1109
      } // end executescript not null if
1110
      File datafile = new File(defaultdatapath+datadoc[0]);
1111
      try {
1112
      FileInputStream fw = new FileInputStream(datafile);
1113
      int x;
1114 185 jones
      while ((x = fw.read())!=-1) {
1115 91 higgins
        out.write(x); }
1116 185 jones
        fw.close();
1117
      } catch (Exception e) {
1118 91 higgins
        System.out.println("Error in returning file\n"+e.getMessage());
1119
        error_flag=true;
1120 185 jones
        error_message = error_message+"\nError in returning file\n"+
1121
                        e.getMessage();
1122
      }
1123
    } // end defaultdatapath not null if
1124 458 berkley
    */
1125 91 higgins
  }
1126 302 bojilova
1127
  /**
1128
   * Handle the getdoctypes Action.
1129
   * Read all doctypes from db connection in XML format
1130
   */
1131
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1132
                                       HttpServletResponse response) {
1133
1134 309 bojilova
    Connection conn = null;
1135
1136 302 bojilova
    try {
1137
1138 309 bojilova
        // get connection from the pool
1139
        conn = util.getConnection();
1140
        DBUtil dbutil = new DBUtil(conn);
1141 302 bojilova
        String doctypes = dbutil.readDoctypes();
1142
        out.println(doctypes);
1143
1144
    } catch (Exception e) {
1145
      out.println("<?xml version=\"1.0\"?>");
1146
      out.println("<error>");
1147
      out.println(e.getMessage());
1148
      out.println("</error>");
1149 309 bojilova
    } finally {
1150 320 bojilova
      util.returnConnection(conn);
1151 309 bojilova
    }
1152 302 bojilova
1153
  }
1154
1155
  /**
1156
   * Handle the getdataguide Action.
1157
   * Read Data Guide for a given doctype from db connection in XML format
1158
   */
1159
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
1160
                                        HttpServletResponse response) {
1161
1162 309 bojilova
    Connection conn = null;
1163 316 bojilova
    String doctype = null;
1164
    String[] doctypeArr = (String[])params.get("doctype");
1165 309 bojilova
1166 316 bojilova
    // get only the first doctype specified in the list of doctypes
1167
    // it could be done for all doctypes in that list
1168
    if (doctypeArr != null) {
1169
        doctype = ((String[])params.get("doctype"))[0];
1170
    }
1171
1172 302 bojilova
    try {
1173
1174 309 bojilova
        // get connection from the pool
1175
        conn = util.getConnection();
1176
        DBUtil dbutil = new DBUtil(conn);
1177 316 bojilova
        String dataguide = dbutil.readDataGuide(doctype);
1178 302 bojilova
        out.println(dataguide);
1179
1180
    } catch (Exception e) {
1181
      out.println("<?xml version=\"1.0\"?>");
1182
      out.println("<error>");
1183
      out.println(e.getMessage());
1184
      out.println("</error>");
1185 309 bojilova
    } finally {
1186 320 bojilova
      util.returnConnection(conn);
1187 309 bojilova
    }
1188 302 bojilova
1189
  }
1190
1191 46 jones
}