Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: bojilova $'
10
 *     '$Date: 2000-10-31 15:26:43 -0800 (Tue, 31 Oct 2000) $'
11
 * '$Revision: 509 $'
12
 */
13

    
14
package edu.ucsb.nceas.metacat;
15

    
16
import java.io.PrintWriter;
17
import java.io.IOException;
18
import java.io.Reader;
19
import java.io.StringReader;
20
import java.io.BufferedReader;
21
import java.io.File;
22
import java.io.FileInputStream;
23
import java.io.FileOutputStream;
24
import java.io.InputStreamReader;
25
import java.io.DataInputStream;
26
import java.util.Enumeration;
27
import java.util.Hashtable;
28
import java.util.ResourceBundle; 
29
import java.util.PropertyResourceBundle;
30
import java.net.URL;
31
import java.net.MalformedURLException;
32
import java.sql.PreparedStatement;
33
import java.sql.ResultSet;
34
import java.sql.Connection;
35
import java.sql.SQLException;
36
import java.lang.reflect.*;
37
import java.net.*;
38
import java.util.zip.*;
39

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

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

    
56
import org.xml.sax.SAXException;
57

    
58
/**
59
 * A metadata catalog server implemented as a Java Servlet
60
 *
61
 * <p>Valid parameters are:<br>
62
 * action=query -- query the values of all elements and attributes
63
 *                     and return a result set of nodes<br>
64
 * action=squery -- structured query (see pathquery.dtd)<br>
65
 * action=insert -- insert an XML document into the database store<br>
66
 * action=update -- update an XML document that is in the database store<br>
67
 * action=delete --  delete an XML document from the database store<br>
68
 * action=validate -- vallidate the xml contained in valtext<br>
69
 * action=getdocument -- display an XML document in XML or HTML<br>
70
 * doctype -- document type list returned by the query (publicID)<br>
71
 * qformat=xml -- display resultset from query in XML<br>
72
 * qformat=html -- display resultset from query in HTML<br>
73
 * docid=34 -- display the document with the document ID number 34<br>
74
 * doctext -- XML text of the document to load into the database<br>
75
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
76
 * valtext -- XML text to be validated<br>
77
 * action=getdatadoc -- retreive a stored datadocument<br>
78
 * action=getdoctypes -- retreive all doctypes (publicID)<br>
79
 * action=getdataguide -- retreive a Data Guide<br>
80
 * 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
 */
86
public class MetaCatServlet extends HttpServlet {
87

    
88
  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
  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
  private String htmlpath = null; 
102
  // script to get data file and put it 
103
  // in defaultdocpath dir
104
  private String executescript  = null;  
105

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

    
116
      util = new MetaCatUtil();
117

    
118
      // Get the configuration file information
119
      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
      servletpath = util.getOption("servletpath");
125
      htmlpath = util.getOption("htmlpath");
126

    
127
      try {
128
        // 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
    } catch ( ServletException ex ) {
135
      throw ex;
136
    }
137
  }
138

    
139
  /**
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
  /** Handle "GET" method requests from HTTP clients */
150
  public void doGet (HttpServletRequest request, HttpServletResponse response)
151
    throws ServletException, IOException {
152

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

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

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

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

    
173
    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
    // Get a handle to the output stream back to the client
186
    //PrintWriter out = response.getWriter();
187
    //response.setContentType("text/html");
188
  
189
    String name = null;
190
    String[] value = null;
191
    String[] docid = new String[3];
192
    Hashtable params = new Hashtable();
193
    Enumeration paramlist = request.getParameterNames();
194
    while (paramlist.hasMoreElements()) {
195
      name = (String)paramlist.nextElement();
196
      value = request.getParameterValues(name);
197

    
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
      } 
208

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

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

    
231
    // handle login action
232
    if (action.equals("login")) {
233

    
234
      handleLoginAction(response.getWriter(), params, request, response);
235

    
236
    // handle logout action  
237
    } else if (action.equals("logout")) {
238

    
239
      handleLogoutAction(response.getWriter(), params, request, response);
240

    
241
    // aware of session expiration on every request  
242
    } else {   
243

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

    
254
    // Now that we know the session is valid, we can delegate the request
255
    // to a particular action handler
256
    if(action.equals("query"))
257
    {
258
      handleQuery(response.getWriter(), params, response, username, groupname); 
259
    } 
260
    else if(action.equals("squery"))
261
    {
262
      if(params.containsKey("query"))
263
      {
264
        handleSQuery(response.getWriter(), params, response, username, groupname); 
265
      }
266
      else
267
      {
268
        PrintWriter out = response.getWriter();
269
        out.println("Illegal action squery without \"query\" parameter");
270
      }
271
    }
272
    else if (action.equals("getdocument")) {
273
      PrintWriter out = response.getWriter();
274
      try {
275
        handleGetDocumentAction(out, params, response);
276
      } catch (ClassNotFoundException e) {
277
        out.println(e.getMessage());
278
      } catch (SQLException se) {
279
        out.println(se.getMessage());
280
      }
281
    } 
282
    else if (action.equals("getrelateddocument")) {
283
      PrintWriter out = response.getWriter();
284
      try {
285
        handleGetRelatedDocumentAction(out, params, response);
286
      } catch (ClassNotFoundException e) {
287
        out.println(e.getMessage());
288
      } catch (SQLException se) {
289
        out.println(se.getMessage());
290
      }
291
    }
292
    else if (action.equals("insert") || action.equals("update")) {
293
      PrintWriter out = response.getWriter();
294
      if ( (username != null) &&  !username.equals("public") ) {
295
        handleInsertOrUpdateAction(out, params, response, username, groupname);
296
      } else {  
297
        out.println("Permission denied for " + action);
298
      }  
299
    } else if (action.equals("delete")) {
300
      PrintWriter out = response.getWriter();
301
      if ( (username != null) &&  !username.equals("public") ) {
302
        handleDeleteAction(out, params, response, username, groupname);
303
      } else {  
304
        out.println("Permission denied for " + action);
305
      }  
306
    } else if (action.equals("validate")) {
307
      PrintWriter out = response.getWriter();
308
      handleValidateAction(out, params, response); 
309
    } else if (action.equals("getabstract")) {
310
      PrintWriter out = response.getWriter();
311
      try{
312
        handleViewAbstractAction(out, params, response);
313
      }
314
      catch(Exception e)
315
      {
316
        out.println("error viewing abstract: " + e.getMessage());
317
      }
318
    } else if (action.equals("getdatadoc")) {
319
      response.setContentType("application/zip");
320
      ServletOutputStream out = response.getOutputStream();
321
      handleGetDataDocumentAction(out, params, response);  
322
    } else if (action.equals("getdoctypes")) {
323
      PrintWriter out = response.getWriter();
324
      handleGetDoctypesAction(out, params, response);  
325
    } else if (action.equals("getdataguide")) {
326
      PrintWriter out = response.getWriter();
327
      handleGetDataGuideAction(out, params, response);  
328
    } else if (action.equals("login") || action.equals("logout")) {
329
    } else {
330
      PrintWriter out = response.getWriter();
331
      out.println("Error: action not registered.  Please report this error.");
332
    }
333
    util.closeConnections();
334
    // Close the stream to the client
335
    //out.close();
336
  }
337
  
338
  /**
339
   * decodes the mouse click information coming from the client.
340
   * This function may be overwritten to provide specific functionality
341
   * for different applications.
342
   * @param params the parameters from the CGI
343
   * @return action the action to be performed or "error" if an error was
344
   * generated
345
   */
346
  protected String decodeMouseAction(Hashtable params)
347
  {
348
    // Determine what type of request the user made
349
    // if the action parameter is set, use it as a default
350
    // but if the ypos param is set, calculate the action needed
351
    String action=null;
352
    long ypos = 0;
353
    try {
354
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
355
      //out.println("<P>YPOS IS " + ypos);
356
      if (ypos <= 13) {
357
        action = "getdocument";
358
      } else if (ypos > 13 && ypos <= 27) {
359
        action = "validate";
360
      } else if (ypos > 27) {
361
        action = "transform";
362
      }
363
      return action;
364
    } catch (Exception npe) {
365
      //
366
      // MBJ -- NOTE that this should be handled more gracefully with
367
      //        the new exception infrastructure -- this "error" return
368
      //        value is inappropriate
369
      //out.println("<P>Caught exception looking for Y value.");
370
      return "error";
371
    }  
372
  }
373

    
374
  /** 
375
   * Handle the login request. Create a new session object.
376
   * Do user authentication through the session.
377
   */
378
  private void handleLoginAction(PrintWriter out, Hashtable params, 
379
               HttpServletRequest request, HttpServletResponse response) {
380

    
381
    AuthSession sess = null;
382
    String un = ((String[])params.get("username"))[0];
383
    String pw = ((String[])params.get("password"))[0];
384
    String action = ((String[])params.get("action"))[0];
385
    String qformat = ((String[])params.get("qformat"))[0];
386
    
387
    try {
388
      sess = new AuthSession();
389
    } catch (Exception e) {
390
      out.println(e.getMessage());
391
      return;
392
    }
393
    
394
    boolean isValid = sess.authenticate(request, un, pw);
395

    
396
    // format and transform the output
397
    if (qformat.equals("html")) {
398
      Connection conn = null;
399
      try {
400
        conn = util.getConnection();
401
        DBTransform trans = new DBTransform(conn);
402
        response.setContentType("text/html");
403
        // user authentication successful
404
        if (isValid) {
405
        //  trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
406
        //                             "-//W3C//HTML//EN", out);
407
          response.sendRedirect(
408
                   response.encodeRedirectUrl(htmlpath + "/metacat.html"));
409

    
410
        // unsuccessful user authentication 
411
        } else {
412
        //  trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//nologin//EN",
413
        //                             "-//W3C//HTML//EN", out);
414
          response.sendRedirect(htmlpath + "/login.html");
415
        }
416
        util.returnConnection(conn); 
417
      } catch(Exception e) {
418
        util.returnConnection(conn); 
419
      } 
420
      
421
    // any output is returned  
422
    } else {
423
      response.setContentType("text/xml");
424
      out.println(sess.getMessage()); 
425
    }
426

    
427
//    if (action.equals("Login Client")) {
428
//      out.println(sess.getMessage());
429
//    } else {
430
//      try {
431
//        if (isValid) {
432
//          if (un.equals("public")) {
433
//            response.sendRedirect(
434
//                   response.encodeRedirectUrl(htmlpath + "/index.html"));
435
//          } else {
436
//            response.sendRedirect(
437
//                   response.encodeRedirectUrl(htmlpath + "/metacat.html"));
438
//          }
439
//        } else {
440
//          response.sendRedirect(htmlpath + "/login.html");
441
//        }
442
//      } catch ( java.io.IOException ioe) {
443
//        String message = "handleLoginAction() - " +
444
//                    "Error on redirect of HttpServletResponse: " + 
445
//                    ioe.getMessage();
446
//        out.println(message);
447
//      }                
448
//    }
449
  }    
450

    
451
  /** 
452
   * Handle the logout request. Close the connection.
453
   */
454
  private void handleLogoutAction(PrintWriter out, Hashtable params, 
455
               HttpServletRequest request, HttpServletResponse response) {
456

    
457
    String qformat = ((String[])params.get("qformat"))[0];
458

    
459
    // close the connection
460
    HttpSession sess = request.getSession(false);
461
    if (sess != null) { sess.invalidate();  }    
462

    
463
    // produce output
464
    StringBuffer output = new StringBuffer();
465
    output.append("<?xml version=\"1.0\"?>");
466
    output.append("<success>");
467
    output.append("User logout.");
468
    output.append("</success>");
469

    
470
    //format and transform the output
471
    if (qformat.equals("html")) {
472
      Connection conn = null;
473
      try {
474
        conn = util.getConnection();
475
        DBTransform trans = new DBTransform(conn);
476
        response.setContentType("text/html");
477
        //trans.transformXMLDocument(output, "-//NCEAS//logout//EN", 
478
        //                           "-//W3C//HTML//EN", out);
479
        response.sendRedirect(htmlpath + "/index.html"); 
480
        util.returnConnection(conn); 
481
      } catch(Exception e) {
482
        util.returnConnection(conn); 
483
      } 
484
    // any output is returned  
485
    } else {
486
      response.setContentType("text/xml");
487
      out.println(output.toString()); 
488
    }
489

    
490
  }
491

    
492
  
493
  /**      
494
   * Retreive the squery xml, execute it and display it
495
   *
496
   * @param out the output stream to the client
497
   * @param params the Hashtable of parameters that should be included
498
   * in the squery.
499
   * @param response the response object linked to the client
500
   * @param conn the database connection 
501
   */
502
  protected void handleSQuery(PrintWriter out, Hashtable params, 
503
                 HttpServletResponse response, String user, String group)
504
  { 
505
    String xmlquery = ((String[])params.get("query"))[0];
506
    String qformat = ((String[])params.get("qformat"))[0];
507
    String resultdoc = null;
508
    String[] returndoc = null;
509
    if(params.contains("returndoc"))
510
    {
511
      returndoc = (String[])params.get("returndoc");
512
    }
513
    
514
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
515
    //String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
516

    
517
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
518
    
519
    //format and transform the results                                        
520
    if(qformat.equals("html")) {
521
      transformResultset(resultdoc, response, out);
522
    } else if(qformat.equals("xml")) {
523
      response.setContentType("text/xml");
524
      out.println(resultdoc);
525
    } else {
526
      out.println("invalid qformat: " + qformat); 
527
    }
528
  }
529
  
530
   /**
531
    * Create the xml query, execute it and display the results.
532
    *
533
    * @param out the output stream to the client
534
    * @param params the Hashtable of parameters that should be included
535
    * in the squery.
536
    * @param response the response object linked to the client
537
    */ 
538
  protected void handleQuery(PrintWriter out, Hashtable params, 
539
                 HttpServletResponse response, String user, String group)
540
  {
541
    //create the query and run it
542
    String[] returndoc = null;
543
    if(params.containsKey("returndoc"))
544
    {
545
      returndoc = (String[])params.get("returndoc");
546
    }
547
    String xmlquery = DBQuery.createSQuery(params);
548
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
549
    String qformat = ((String[])params.get("qformat"))[0];
550
    String resultdoc = null;
551
    
552
    resultdoc = createResultDocument(doclist, transformQuery(params));
553

    
554
    //format and transform the results                                        
555
    if(qformat.equals("html")) {
556
      transformResultset(resultdoc, response, out);
557
    } else if(qformat.equals("xml")) {
558
      response.setContentType("text/xml");
559
      out.println(resultdoc);
560
    } else { 
561
      out.println("invalid qformat: " + qformat); 
562
    }
563
  }
564
  
565
  /**
566
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
567
   * so it can properly be placed in the <query> tag of the resultset.
568
   * This method is overwritable so that other applications can customize
569
   * the structure of what is in the <query> tag.
570
   * 
571
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
572
   */
573
  protected String transformQuery(Hashtable params)
574
  {
575
    //DBQuery.createSQuery is a re-calling of a previously called 
576
    //function but it is necessary
577
    //so that overriding methods have access to the params hashtable
578
    String xmlquery = DBQuery.createSQuery(params);
579
    //the <?xml version="1.0"?> tag is the first 22 characters of the
580
    xmlquery = xmlquery.trim();
581
    int index = xmlquery.indexOf("?>");
582
    return xmlquery.substring(index + 2, xmlquery.length());
583
  }
584
  
585
  /**
586
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
587
   * string as a param instead of a hashtable.
588
   * 
589
   * @param xmlquery a string representing a query.
590
   */
591
  protected String transformQuery(String xmlquery)
592
  {
593
    xmlquery = xmlquery.trim();
594
    int index = xmlquery.indexOf("?>");
595
    return xmlquery.substring(index + 2, xmlquery.length());
596
  }
597
  
598
  /**
599
   * Run the query and return a hashtable of results.
600
   *
601
   * @param xmlquery the query to run
602
   */
603
  private Hashtable runQuery(String xmlquery, String user, String group, 
604
                             String[] returndoc)
605
  {
606
    Hashtable doclist=null;
607
    Connection conn = null;
608
    try
609
    {
610
      conn = util.getConnection();
611
      DBQuery queryobj = new DBQuery(conn, saxparser);
612
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
613
                                       returndoc);
614
      util.returnConnection(conn);
615
      return doclist;
616
    } 
617
    catch (Exception e) 
618
    {
619
      util.returnConnection(conn); 
620
      util.debugMessage("Error in runQuery: " + e.getMessage());
621
      doclist = null;
622
      return doclist;
623
    }    
624
  }
625
  
626
  /**
627
   * Transorms an xml resultset document to html and sends it to the browser
628
   *
629
   * @param resultdoc the string representation of the document that needs
630
   * to be transformed.
631
   * @param response the HttpServletResponse object bound to the client.
632
   * @param out the output stream to the client
633
   */ 
634
  protected void transformResultset(String resultdoc, 
635
                                    HttpServletResponse response,
636
                                    PrintWriter out)
637
  {
638
    Connection conn = null;
639
    try {
640
      conn = util.getConnection();
641
      DBTransform trans = new DBTransform(conn);
642
      response.setContentType("text/html");
643
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
644
                                 "-//W3C//HTML//EN", out);
645
      util.returnConnection(conn); 
646
    }
647
    catch(Exception e)
648
    {
649
      util.returnConnection(conn); 
650
    } 
651
  }
652
  
653
  /**
654
   * Transforms a hashtable of documents to an xml or html result.
655
   * If there is a returndoc, then it only displays documents of
656
   * whatever type returndoc represents.  If a result is found in a document
657
   * that is not of type returndoc then this attempts to find a relation 
658
   * between this document and one that satifies the returndoc doctype.
659
   *
660
   * @param doclist- the hashtable to transform
661
   * @param xmlquery- the query that returned the dolist result
662
   * @param resultdoc- the document type to backtrack to.
663
   */
664
  protected String createResultDocument(Hashtable doclist, String xmlquery)
665
  {
666
    // Create a buffer to hold the xml result
667
    StringBuffer resultset = new StringBuffer();
668
 
669
    // Print the resulting root nodes 
670
    String docid = null;
671
    String document = null;
672
    resultset.append("<?xml version=\"1.0\"?>\n");
673
    resultset.append("<resultset>\n");
674
      
675
    resultset.append("  <query>" + xmlquery + "</query>");   
676

    
677
    if(doclist != null)
678
    {
679
      Enumeration doclistkeys = doclist.keys(); 
680
      while (doclistkeys.hasMoreElements()) 
681
      {
682
        docid = (String)doclistkeys.nextElement();
683
        document = (String)doclist.get(docid);
684
        resultset.append("  <document>" + document + "</document>");
685
      }
686
    }
687

    
688
    resultset.append("</resultset>");
689
    //System.out.println(resultset.toString());
690
    return resultset.toString();
691
  }
692
  
693
  /**
694
   * Handle the request to view the abstract of a document.
695
   * The abstractpath CGI parameter gives the xml path to the abstract
696
   * node.  
697
   */
698
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
699
               HttpServletResponse response) throws IOException, SQLException
700
  {
701
    String abstractpath = null;
702
    String docid = null;
703
    Connection conn = null;
704
    response.setContentType("text/html");
705
    try
706
    {
707
      docid = ((String[])params.get("docid"))[0];
708
      if(params.containsKey("abstractpath"))
709
      {
710
        //the CGI parameter abstractpath holds the path to the abstract
711
        //that should be displayed.
712
        abstractpath = ((String[])params.get("abstractpath"))[0];
713
      }
714
      else
715
      {
716
        out.println("error: no abstractpath parameter"); 
717
      }
718
      conn = util.getConnection();
719
    
720
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
721
    
722
      out.println("<html><head><title>Abstract</title></head>");
723
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
724
      for(int i=0; i<abstracts.length; i++)
725
      {
726
        out.println("<p>" + (String)abstracts[i] + "</p>");
727
      }
728
      out.println("</body></html>");
729
    }
730
    catch (IOException ioe)
731
    {
732
       util.debugMessage("error in handlegetabstract: " + ioe.getMessage());
733
    }
734
    catch(SQLException sqle)
735
    {
736
      util.debugMessage("error in handlegetabstract: " + sqle.getMessage()); 
737
    }
738
    catch(Exception e)
739
    {
740
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
741
    }
742
    
743
    util.returnConnection(conn);
744
  }
745

    
746
  /** 
747
   * Handle the database getrelateddocument request and return a XML document, 
748
   * possibly transformed from XML into HTML
749
   */
750
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params, 
751
               HttpServletResponse response) 
752
               throws ClassNotFoundException, IOException, SQLException 
753
  {
754
    String docid = null;
755
    Connection conn = null;
756
      
757
    if(params.containsKey("url"))
758
    {//the identifier for the related document is contained in the URL param
759
      try
760
      {
761
        DocumentImpl xmldoc=null;
762
        metacatURL murl = new metacatURL(((String[])params.get("url"))[0]);
763
        if(murl.getURLType().equals("metacat"))
764
        {//get the document from the database if it is the right type of url
765
          Hashtable murlParams = murl.getHashParams();
766
          if(murlParams.containsKey("docid"))
767
          {//the docid should be first
768
            docid = (String)murlParams.get("docid"); //get the docid value
769
            conn = util.getConnection();
770
            xmldoc = new DocumentImpl(conn, docid);
771
            String qformat = ((String[])params.get("qformat"))[0];
772
            if (qformat.equals("xml")) 
773
            { 
774
              // set content type and other response header fields first
775
              response.setContentType("text/xml");
776
              xmldoc.toXml(out);
777
              //out.println(xmldoc);
778
            } 
779
            else if (qformat.equals("html")) 
780
            {
781
              response.setContentType("text/html");
782
              // Look up the document type
783
              String sourcetype = xmldoc.getDoctype();
784
              // Transform the document to the new doctype
785
              DBTransform dbt = new DBTransform(conn);
786
              dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
787
                                 "-//W3C//HTML//EN", out);
788
            }
789

    
790
            util.returnConnection(conn);
791
          }
792
          else
793
          {
794
            //throw new Exception("handleGetDocument: bad URL");
795
            System.err.println("handleGetDocument: bad URL");
796
          }
797
        }
798
        else if(murl.getURLType().equals("http"))
799
        {//get the document from the internet
800
          Hashtable murlParams = murl.getHashParams();
801
          if(murlParams.containsKey("httpurl"))
802
          {//httpurl is the param name for an http url.
803
            URL urlconn = new URL((String)murlParams.get("httpurl"));  
804
            //create a new url obj.
805
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
806
            BufferedReader htmldoc = new BufferedReader(
807
                                   new InputStreamReader(urlconn.openStream()));
808
            //bind a data stream.
809
            try
810
            { //display the document
811
              String line=null;
812
              while((line = htmldoc.readLine()) != null)
813
              {
814
                out.println(line); 
815
              }
816
            }
817
            catch(Exception e)
818
            {
819
              util.debugMessage("error viewing html document"); 
820
            }
821
          }
822
        }
823
      }
824
      catch (McdbException e) {
825
        response.setContentType("text/xml");
826
        e.toXml(out);
827
      } catch   (Throwable t) {
828
        response.setContentType("text/html");
829
        out.println(t.getMessage());
830
      } finally {
831
        util.returnConnection(conn);
832
      }
833
    }
834
  }   
835
  
836
  /** 
837
   * Handle the database getdocument request and return a XML document, 
838
   * possibly transformed from XML into HTML
839
   */
840
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
841
               HttpServletResponse response) 
842
               throws ClassNotFoundException, IOException, SQLException {
843
    String docidstr = null;
844
    String docid = null;
845
    String doc = null;
846
    Connection conn = null;
847
    
848
    try {
849
      // Find the document id number
850
      docidstr = ((String[])params.get("docid"))[0]; 
851
      docid = docidstr;
852
      conn = util.getConnection();
853
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
854
      // Get the document indicated from the db
855
      //doc = docreader.readXMLDocument(docid);
856

    
857
      // Return the document in XML or HTML format
858
      String qformat=null;
859
      if(params.containsKey("qformat"))
860
      {
861
        qformat = ((String[])params.get("qformat"))[0];
862
      }
863
      else
864
      {
865
        qformat = "html";        
866
      }
867
      if (qformat.equals("xml")) { 
868
        // set content type and other response header fields first
869
        response.setContentType("text/xml");
870
        xmldoc.toXml(out);
871
        //out.println(xmldoc);
872
      } else if (qformat.equals("html")) {
873
        response.setContentType("text/html");
874
        // Look up the document type
875
        String sourcetype = xmldoc.getDoctype();
876
        // Transform the document to the new doctype
877
        DBTransform dbt = new DBTransform(conn);
878
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
879
                                 "-//W3C//HTML//EN", out);
880
      }
881
    } catch (McdbException e) {
882
      response.setContentType("text/xml");
883
      e.toXml(out);
884
    } catch (Throwable t) {
885
      response.setContentType("text/html");
886
      out.println(t.getMessage());
887
    } finally {
888
      util.returnConnection(conn);
889
    }    
890

    
891
  }
892

    
893
  /** 
894
   * Handle the database putdocument request and write an XML document 
895
   * to the database connection
896
   */
897
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
898
               HttpServletResponse response, String user, String group) {
899

    
900
    Connection conn = null;
901

    
902
    try {
903
      // Get the document indicated
904
      String[] doctext = (String[])params.get("doctext");
905
      StringReader xml = null;
906
      try {
907
        xml = new StringReader(doctext[0]);
908

    
909
        String[] action = (String[])params.get("action");
910
        String[] docid = (String[])params.get("docid");
911
        String newdocid = null;
912

    
913
        String doAction = null;
914
        if (action[0].equals("insert")) {
915
          doAction = "INSERT";
916
        } else if (action[0].equals("update")) {
917
          doAction = "UPDATE";
918
        }
919

    
920
        try {
921
            // get a connection from the pool
922
            conn = util.getConnection();
923

    
924
            // write the document to the database
925
            try {
926
                String accNumber = docid[0];
927
                if (accNumber.equals("")) {
928
                    accNumber = null;
929
                }
930
                newdocid = DocumentImpl.write(conn, xml, doAction, accNumber, 
931
                                              user, group);
932
                
933
            } catch (NullPointerException npe) {
934
              newdocid = DocumentImpl.write(conn,xml,doAction,null,user,group);
935
            }
936
//        } catch (Exception e) {
937
//          response.setContentType("text/html");
938
//          out.println(e.getMessage());
939
        } finally {
940
          util.returnConnection(conn);
941
        }    
942

    
943
        // set content type and other response header fields first
944
        response.setContentType("text/xml");
945
        out.println("<?xml version=\"1.0\"?>");
946
        out.println("<success>");
947
        out.println("<docid>" + newdocid + "</docid>"); 
948
        out.println("</success>");
949

    
950
      } catch (NullPointerException npe) {
951
        response.setContentType("text/xml");
952
        out.println("<?xml version=\"1.0\"?>");
953
        out.println("<error>");
954
        out.println(npe.getMessage()); 
955
        out.println("</error>");
956
      }
957
    } catch (Exception e) {
958
      response.setContentType("text/xml");
959
      out.println("<?xml version=\"1.0\"?>");
960
      out.println("<error>");
961
      out.println(e.getMessage()); 
962
      if (e instanceof SAXException) {
963
        Exception e2 = ((SAXException)e).getException();
964
        out.println("<error>");
965
        out.println(e2.getMessage()); 
966
        out.println("</error>");
967
      }
968
      //e.printStackTrace(out);
969
      out.println("</error>");
970
    }
971
  }
972

    
973
  /** 
974
   * Handle the database delete request and delete an XML document 
975
   * from the database connection
976
   */
977
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
978
               HttpServletResponse response, String user, String group) {
979

    
980
    String[] docid = (String[])params.get("docid");
981
    Connection conn = null;
982

    
983
    // delete the document from the database
984
    try {
985
      // get a connection from the pool
986
      conn = util.getConnection();
987
                                      // NOTE -- NEED TO TEST HERE
988
                                      // FOR EXISTENCE OF DOCID PARAM
989
                                      // BEFORE ACCESSING ARRAY
990
      try { 
991
        DocumentImpl.delete(conn, docid[0], user, group);
992
        response.setContentType("text/xml");
993
        out.println("<?xml version=\"1.0\"?>");
994
        out.println("<success>");
995
        out.println("Document deleted."); 
996
        out.println("</success>");
997
      } catch (AccessionNumberException ane) {
998
        response.setContentType("text/xml");
999
        out.println("<?xml version=\"1.0\"?>");
1000
        out.println("<error>");
1001
        out.println("Error deleting document!!!");
1002
        out.println(ane.getMessage()); 
1003
        out.println("</error>");
1004
      }
1005
    } catch (Exception e) {
1006
      response.setContentType("text/xml");
1007
      out.println("<?xml version=\"1.0\"?>");
1008
      out.println("<error>");
1009
      out.println(e.getMessage()); 
1010
      out.println("</error>");
1011
    } finally {
1012
      util.returnConnection(conn);
1013
    }  
1014
  }
1015
  
1016
  /** 
1017
   * Handle the validation request and return the results to the requestor
1018
   */
1019
  private void handleValidateAction(PrintWriter out, Hashtable params, 
1020
               HttpServletResponse response) {
1021

    
1022
    // Get the document indicated
1023
    String valtext = null;
1024
    
1025
    try {
1026
      valtext = ((String[])params.get("valtext"))[0];
1027
    } catch (Exception nullpe) {
1028

    
1029
      Connection conn = null;
1030
      String docid = null;
1031
      try {
1032
        // Find the document id number
1033
        docid = ((String[])params.get("docid"))[0]; 
1034

    
1035
        // get a connection from the pool
1036
        conn = util.getConnection();
1037

    
1038
        // Get the document indicated from the db
1039
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1040
        valtext = xmldoc.toString();
1041

    
1042
      } catch (NullPointerException npe) {
1043
        response.setContentType("text/xml");
1044
        out.println("<error>Error getting document ID: " + docid + "</error>");
1045
        if ( conn != null ) { util.returnConnection(conn); }
1046
        return;
1047
      } catch (Exception e) {
1048
        response.setContentType("text/html");
1049
        out.println(e.getMessage()); 
1050
      } finally {
1051
        util.returnConnection(conn);
1052
      }  
1053
    }
1054

    
1055
    Connection conn = null;
1056
    try {
1057
      // get a connection from the pool
1058
      conn = util.getConnection();
1059
      DBValidate valobj = new DBValidate(saxparser,conn);
1060
      boolean valid = valobj.validateString(valtext);
1061

    
1062
      // set content type and other response header fields first
1063
      response.setContentType("text/xml");
1064
      out.println(valobj.returnErrors());
1065

    
1066
    } catch (NullPointerException npe2) {
1067
      // set content type and other response header fields first
1068
      response.setContentType("text/xml");
1069
      out.println("<error>Error validating document.</error>"); 
1070
    } catch (Exception e) {
1071
      response.setContentType("text/html");
1072
      out.println(e.getMessage()); 
1073
    } finally {
1074
      util.returnConnection(conn);
1075
    }  
1076
  }
1077

    
1078
  /** 
1079
   * Handle the document request and return the results to the requestor
1080
   * If a docid is passed in through the params then that document
1081
   * will be retrieved form the DB and put in the zip file.
1082
   * In addition if 1 or more relations parameters are passed, those file
1083
   * will be zipped as well.  Currently this is only implemented for 
1084
   * metacat:// and http:// files.  Support should be added for srb:// files
1085
   * as well.
1086
   */
1087
  private void handleGetDataDocumentAction(ServletOutputStream out, 
1088
               Hashtable params, 
1089
               HttpServletResponse response) {
1090
  //find the related files, get them from their source and zip them into 
1091
  //a zip file.
1092
  try
1093
  {
1094
    Connection conn = util.getConnection();
1095
    String currentDocid = ((String[])params.get("docid"))[0];
1096
    ZipOutputStream zout = new ZipOutputStream(out);
1097
    byte[] bytestring = null;
1098
    ZipEntry zentry = null;
1099
    DocumentImpl xmldoc = null;
1100
    String[] reldocs = null;
1101
    
1102
    if(params.containsKey("relation"))
1103
    { //get the relations from the parameters.
1104
      reldocs = ((String[])params.get("relation"));
1105
    }
1106
    else
1107
    { //let the for loop know that there are no relations to zip
1108
      reldocs = new String[0];
1109
    }
1110

    
1111
    //write the base file to the zip file.
1112
    xmldoc = new DocumentImpl(conn, currentDocid);
1113
    bytestring = (xmldoc.toString()).getBytes();
1114
    zentry = new ZipEntry(currentDocid + ".xml");
1115
    //create a new zip entry and write the file to the stream
1116
    zentry.setSize(bytestring.length);
1117
    zout.putNextEntry(zentry);
1118
    zout.write(bytestring, 0, bytestring.length);
1119
    zout.closeEntry(); //get ready for the next entry. 
1120

    
1121
    //zip up the related documents
1122
    for(int i=0; i<reldocs.length; i++)
1123
    {
1124
      metacatURL murl = new metacatURL(((String)reldocs[i]));
1125
      if(murl.getURLType().equals("metacat"))
1126
      {
1127
        //get the document from the database
1128
        xmldoc = new DocumentImpl(conn, (String)murl.getHashParam("docid"));
1129
        bytestring = (xmldoc.toString()).getBytes();
1130
        zentry = new ZipEntry(murl.getHashParam("docid") + ".xml");
1131
        //create a new zip entry and write the file to the stream
1132
        zentry.setSize(bytestring.length);
1133
        zout.putNextEntry(zentry);
1134
        zout.write(bytestring, 0, bytestring.length);
1135
        zout.closeEntry(); //get ready for the next entry.
1136
      }
1137
      else if(murl.getURLType().equals("http"))
1138
      {
1139
        Hashtable murlParams = murl.getHashParams();
1140
        if(murlParams.containsKey("httpurl"))
1141
        {//httpurl is the param name for an http url.
1142
          URL urlconn = new URL((String)murlParams.get("httpurl"));  
1143
          //create a new url obj.
1144
          BufferedReader htmldoc = new BufferedReader(
1145
                                   new InputStreamReader(urlconn.openStream()));
1146
          //get the data from the web server
1147
          try
1148
          { //zip the document
1149
            String line=null;
1150
            zentry = new ZipEntry((String)murlParams.get("filename"));
1151
            //get just the filename from the URL.
1152
            zout.putNextEntry(zentry);
1153
            //make a new entry in the zip file stream
1154
            while((line = htmldoc.readLine()) != null)
1155
            {
1156
              bytestring = (line.toString()).getBytes();
1157
              zout.write(bytestring, 0, bytestring.length);
1158
              //write out the file line by line
1159
            }
1160
            zout.closeEntry(); //close the entry in the file
1161
          }
1162
          catch(Exception e)
1163
          {
1164
            util.debugMessage("error downloading html document"); 
1165
          }
1166
        }
1167
      }
1168
    }
1169
    zout.finish();  //terminate the zip file
1170
    zout.close();   //close the stream.
1171
    util.returnConnection(conn); //return the connection to the pool
1172
  }
1173
  catch(Exception e)
1174
  {
1175
    System.out.println("Error creating zip file: " + e.getMessage()); 
1176
    e.printStackTrace(System.out);
1177
  }
1178
           
1179
   /*
1180
   //////////old code using a shell script/////////////////////////////////
1181
   
1182
      boolean error_flag = false;
1183
      String error_message = "";
1184
      // Get the document indicated
1185
      String[] datadoc = (String[])params.get("datadoc");
1186
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1187
      // executescript = "test.bat";        // for testing only!!!
1188
      
1189
      // set content type and other response header fields first
1190
      response.setContentType("application/octet-stream");
1191
      if (defaultdatapath!=null) {
1192
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1193
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1194
        }
1195
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1196
        if (executescript!=null) {
1197
          String command = null;
1198
          File scriptfile = new File(executescript);
1199
          if (scriptfile.exists()) {
1200
            command=executescript+" "+datadoc[0]; // script includes path
1201
        } else {     // look in defaultdatapath
1202
            // on Win98 one MUST include the .bat extender
1203
            command = defaultdatapath+executescript+" "+datadoc[0];  
1204
        }
1205
      System.out.println(command);
1206
      try {
1207
      Process proc = Runtime.getRuntime().exec(command);
1208
      proc.waitFor();
1209
      }
1210
      catch (Exception eee) {
1211
        System.out.println("Error running process!");
1212
        error_flag = true;
1213
        error_message = "Error running process!";}
1214
      } // end executescript not null if
1215
      File datafile = new File(defaultdatapath+datadoc[0]);
1216
      try {
1217
      FileInputStream fw = new FileInputStream(datafile);
1218
      int x;
1219
      while ((x = fw.read())!=-1) {
1220
        out.write(x); }
1221
        fw.close();
1222
      } catch (Exception e) {
1223
        System.out.println("Error in returning file\n"+e.getMessage());
1224
        error_flag=true;
1225
        error_message = error_message+"\nError in returning file\n"+
1226
                        e.getMessage();
1227
      }
1228
    } // end defaultdatapath not null if
1229
    */
1230
  }
1231
  
1232
  /** 
1233
   * Handle the getdoctypes Action.
1234
   * Read all doctypes from db connection in XML format
1235
   */
1236
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1237
                                       HttpServletResponse response) {
1238

    
1239
    Connection conn = null;
1240
    
1241
    try {
1242

    
1243
        // get connection from the pool
1244
        conn = util.getConnection();
1245
        DBUtil dbutil = new DBUtil(conn);
1246
        String doctypes = dbutil.readDoctypes();
1247
        out.println(doctypes);
1248

    
1249
    } catch (Exception e) {
1250
      out.println("<?xml version=\"1.0\"?>");
1251
      out.println("<error>");
1252
      out.println(e.getMessage());
1253
      out.println("</error>");
1254
    } finally {
1255
      util.returnConnection(conn);
1256
    }  
1257
    
1258
  }
1259

    
1260
  /** 
1261
   * Handle the getdataguide Action.
1262
   * Read Data Guide for a given doctype from db connection in XML format
1263
   */
1264
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1265
                                        HttpServletResponse response) {
1266

    
1267
    Connection conn = null;
1268
    String doctype = null;
1269
    String[] doctypeArr = (String[])params.get("doctype");
1270

    
1271
    // get only the first doctype specified in the list of doctypes
1272
    // it could be done for all doctypes in that list
1273
    if (doctypeArr != null) {
1274
        doctype = ((String[])params.get("doctype"))[0]; 
1275
    }
1276

    
1277
    try {
1278

    
1279
        // get connection from the pool
1280
        conn = util.getConnection();
1281
        DBUtil dbutil = new DBUtil(conn);
1282
        String dataguide = dbutil.readDataGuide(doctype);
1283
        out.println(dataguide);
1284

    
1285
    } catch (Exception e) {
1286
      out.println("<?xml version=\"1.0\"?>");
1287
      out.println("<error>");
1288
      out.println(e.getMessage());
1289
      out.println("</error>");
1290
    } finally {
1291
      util.returnConnection(conn);
1292
    }  
1293
    
1294
  }
1295

    
1296
}
(23-23/33)