Project

General

Profile

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

    
14
package edu.ucsb.nceas.metacat;
15

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

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

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

    
56
import org.xml.sax.SAXException;
57

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

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

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

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

    
117
      util = new MetaCatUtil();
118

    
119
      // Get the configuration file information
120
      resultStyleURL = util.getOption("resultStyleURL");
121
      xmlcatalogfile = util.getOption("xmlcatalogfile");
122
      saxparser = util.getOption("saxparser");
123
      defaultdatapath = util.getOption("defaultdatapath");
124
      executescript = util.getOption("executescript"); 
125
      servletpath = util.getOption("servletpath");
126
      htmlpath = util.getOption("htmlpath");
127
/*
128
      try {
129
        // Open a pool of db connections
130
        connectionPool = util.getConnectionPool();
131
      } catch (Exception e) {
132
        System.err.println("Error creating pool of database connections");
133
        System.err.println(e.getMessage());
134
      }
135
*/
136
    } catch ( ServletException ex ) {
137
      throw ex;
138
    }
139
  }
140

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
478
  }    
479

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

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

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

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

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

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

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

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

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

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

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

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

    
832
            util.returnConnection(conn);
833
          }
834
          else
835
          {
836
            //throw new Exception("handleGetDocument: bad URL");
837
            System.err.println("handleGetDocument: bad URL");
838
          }
839
        }
840
        else if(murl.getProtocol().equals("http"))
841
        {//get the document from the internet
842
          //Hashtable murlParams = murl.getHashParams();
843
          Hashtable murlParams = util.parseQuery(murl.getQuery());
844
          if(murlParams.containsKey("httpurl"))
845
          {//httpurl is the param name for an http url.
846
            URL urlconn = new URL((String)murlParams.get("httpurl"));  
847
            //create a new url obj.
848
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
849
            BufferedReader htmldoc = new BufferedReader(
850
                                   new InputStreamReader(urlconn.openStream()));
851
            //bind a data stream.
852
            try
853
            { //display the document
854
              String line=null;
855
              while((line = htmldoc.readLine()) != null)
856
              {
857
                out.println(line); 
858
              }
859
            }
860
            catch(Exception e)
861
            {
862
              util.debugMessage("error viewing html document"); 
863
            }
864
          }
865
        }
866
      }
867
      catch (McdbException e) {
868
        response.setContentType("text/xml");
869
        e.toXml(out);
870
      } catch   (Throwable t) {
871
        response.setContentType("text/html");
872
        out.println(t.getMessage());
873
      } finally {
874
        util.returnConnection(conn);
875
      }
876
    //} // end if
877
  }   
878
  
879
  /** 
880
   * Handle the database read request and return an XML document, 
881
   * possibly transformed from XML into HTML
882
   */
883
  private void handleReadAction(PrintWriter out, Hashtable params, 
884
               HttpServletResponse response) 
885
               throws ClassNotFoundException, IOException, SQLException 
886
  {
887
//    out.println(((String[])params.get("docid"))[0]);
888
    try {
889
      //MetacatURL murl = new MetacatURL(((String[])params.get("docid"))[0]);
890
      URL murl = new URL(((String[])params.get("docid"))[0]);
891
      handleGetRelatedDocumentAction(out, params, response, murl);
892
    } catch (MalformedURLException mue) {
893
      handleGetDocumentAction(out, params, response);
894
    }
895
  }
896

    
897
  /** 
898
   * Handle the database read request and return an XML document, 
899
   * possibly transformed from XML into HTML
900
   */
901
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
902
               HttpServletResponse response) 
903
               throws ClassNotFoundException, IOException, SQLException {
904
    String docidstr = null;
905
    String docid = null;
906
    String doc = null;
907
    Connection conn = null;
908
    
909
    try {
910
      // Find the document id number
911
      docidstr = ((String[])params.get("docid"))[0]; 
912
      docid = docidstr;
913
      conn = util.getConnection();
914
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
915
      // Get the document indicated from the db
916
      //doc = docreader.readXMLDocument(docid);
917

    
918
      // Return the document in XML or HTML format
919
      String qformat=null;
920
      if(params.containsKey("qformat"))
921
      {
922
        qformat = ((String[])params.get("qformat"))[0];
923
      }
924
      else
925
      {
926
        qformat = "html";        
927
      }
928
      if (qformat.equals("xml")) { 
929
        // set content type and other response header fields first
930
        response.setContentType("text/xml");
931
        xmldoc.toXml(out);
932
        //out.println(xmldoc);
933
      } else if (qformat.equals("html")) {
934
        response.setContentType("text/html");
935
        // Look up the document type
936
        String sourcetype = xmldoc.getDoctype();
937
        // Transform the document to the new doctype
938
        DBTransform dbt = new DBTransform(conn);
939
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
940
                                 "-//W3C//HTML//EN", out);
941
      }
942
    } catch (McdbException e) {
943
      response.setContentType("text/xml");
944
      e.toXml(out);
945
    } catch (Throwable t) {
946
      response.setContentType("text/html");
947
      out.println(t.getMessage());
948
    } finally {
949
      util.returnConnection(conn);
950
    }    
951

    
952
  }
953

    
954
  /** 
955
   * Handle the database putdocument request and write an XML document 
956
   * to the database connection
957
   */
958
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
959
               HttpServletResponse response, String user, String group) {
960

    
961
    Connection conn = null;
962

    
963
    try {
964
      // Get the document indicated
965
      String[] doctext = (String[])params.get("doctext");
966
      String[] acltext = null;
967

    
968
      StringReader acl = null;
969
      if(params.contains("acl"))
970
      {
971
        acltext = (String[])params.get("acl");
972
        try {
973
          acl = new StringReader(acltext[0]);
974
        } catch (NullPointerException npe) {}
975
      }
976
      
977
      StringReader xml = null;
978
      try {
979
        xml = new StringReader(doctext[0]);
980

    
981
        String[] action = (String[])params.get("action");
982
        String[] docid = (String[])params.get("docid");
983
        String newdocid = null;
984

    
985
        String doAction = null;
986
        if (action[0].equals("insert")) {
987
          doAction = "INSERT";
988
        } else if (action[0].equals("update")) {
989
          doAction = "UPDATE";
990
        }
991

    
992
        try {
993
            // get a connection from the pool
994
            conn = util.getConnection();
995

    
996
            // write the document to the database
997
            try {
998
                String accNumber = docid[0];
999
                if (accNumber.equals("")) {
1000
                    accNumber = null;
1001
                }
1002
                newdocid = DocumentImpl.write(conn, xml, acl, doAction,
1003
                                              accNumber, user, group);
1004
                
1005
            } catch (NullPointerException npe) {
1006
              newdocid = DocumentImpl.write(conn, xml, acl, doAction,
1007
                                            null, user, group);
1008
            }
1009
//        } catch (Exception e) {
1010
//          response.setContentType("text/html");
1011
//          out.println(e.getMessage());
1012
        } finally {
1013
          util.returnConnection(conn);
1014
        }    
1015

    
1016
        // set content type and other response header fields first
1017
        response.setContentType("text/xml");
1018
        out.println("<?xml version=\"1.0\"?>");
1019
        out.println("<success>");
1020
        out.println("<docid>" + newdocid + "</docid>"); 
1021
        out.println("</success>");
1022

    
1023
      } catch (NullPointerException npe) {
1024
        response.setContentType("text/xml");
1025
        out.println("<?xml version=\"1.0\"?>");
1026
        out.println("<error>");
1027
        out.println(npe.getMessage()); 
1028
        out.println("</error>");
1029
      }
1030
    } catch (Exception e) {
1031
      response.setContentType("text/xml");
1032
      out.println("<?xml version=\"1.0\"?>");
1033
      out.println("<error>");
1034
      out.println(e.getMessage()); 
1035
      if (e instanceof SAXException) {
1036
        Exception e2 = ((SAXException)e).getException();
1037
        out.println("<error>");
1038
        out.println(e2.getMessage()); 
1039
        out.println("</error>");
1040
      }
1041
      //e.printStackTrace(out);
1042
      out.println("</error>");
1043
    }
1044
  }
1045

    
1046
  /** 
1047
   * Handle the database delete request and delete an XML document 
1048
   * from the database connection
1049
   */
1050
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1051
               HttpServletResponse response, String user, String group) {
1052

    
1053
    String[] docid = (String[])params.get("docid");
1054
    Connection conn = null;
1055

    
1056
    // delete the document from the database
1057
    try {
1058
      // get a connection from the pool
1059
      conn = util.getConnection();
1060
                                      // NOTE -- NEED TO TEST HERE
1061
                                      // FOR EXISTENCE OF DOCID PARAM
1062
                                      // BEFORE ACCESSING ARRAY
1063
      try { 
1064
        DocumentImpl.delete(conn, docid[0], user, group);
1065
        response.setContentType("text/xml");
1066
        out.println("<?xml version=\"1.0\"?>");
1067
        out.println("<success>");
1068
        out.println("Document deleted."); 
1069
        out.println("</success>");
1070
      } catch (AccessionNumberException ane) {
1071
        response.setContentType("text/xml");
1072
        out.println("<?xml version=\"1.0\"?>");
1073
        out.println("<error>");
1074
        out.println("Error deleting document!!!");
1075
        out.println(ane.getMessage()); 
1076
        out.println("</error>");
1077
      }
1078
    } catch (Exception e) {
1079
      response.setContentType("text/xml");
1080
      out.println("<?xml version=\"1.0\"?>");
1081
      out.println("<error>");
1082
      out.println(e.getMessage()); 
1083
      out.println("</error>");
1084
    } finally {
1085
      util.returnConnection(conn);
1086
    }  
1087
  }
1088
  
1089
  /** 
1090
   * Handle the validation request and return the results to the requestor
1091
   */
1092
  private void handleValidateAction(PrintWriter out, Hashtable params, 
1093
               HttpServletResponse response) {
1094

    
1095
    // Get the document indicated
1096
    String valtext = null;
1097
    
1098
    try {
1099
      valtext = ((String[])params.get("valtext"))[0];
1100
    } catch (Exception nullpe) {
1101

    
1102
      Connection conn = null;
1103
      String docid = null;
1104
      try {
1105
        // Find the document id number
1106
        docid = ((String[])params.get("docid"))[0]; 
1107

    
1108
        // get a connection from the pool
1109
        conn = util.getConnection();
1110

    
1111
        // Get the document indicated from the db
1112
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1113
        valtext = xmldoc.toString();
1114

    
1115
      } catch (NullPointerException npe) {
1116
        response.setContentType("text/xml");
1117
        out.println("<error>Error getting document ID: " + docid + "</error>");
1118
        if ( conn != null ) { util.returnConnection(conn); }
1119
        return;
1120
      } catch (Exception e) {
1121
        response.setContentType("text/html");
1122
        out.println(e.getMessage()); 
1123
      } finally {
1124
        util.returnConnection(conn);
1125
      }  
1126
    }
1127

    
1128
    Connection conn = null;
1129
    try {
1130
      // get a connection from the pool
1131
      conn = util.getConnection();
1132
      DBValidate valobj = new DBValidate(saxparser,conn);
1133
      boolean valid = valobj.validateString(valtext);
1134

    
1135
      // set content type and other response header fields first
1136
      response.setContentType("text/xml");
1137
      out.println(valobj.returnErrors());
1138

    
1139
    } catch (NullPointerException npe2) {
1140
      // set content type and other response header fields first
1141
      response.setContentType("text/xml");
1142
      out.println("<error>Error validating document.</error>"); 
1143
    } catch (Exception e) {
1144
      response.setContentType("text/html");
1145
      out.println(e.getMessage()); 
1146
    } finally {
1147
      util.returnConnection(conn);
1148
    }  
1149
  }
1150

    
1151
  /** 
1152
   * Handle the document request and return the results to the requestor
1153
   * If a docid is passed in through the params then that document
1154
   * will be retrieved form the DB and put in the zip file.
1155
   * In addition if 1 or more relations parameters are passed, those file
1156
   * will be zipped as well.  Currently this is only implemented for 
1157
   * metacat:// and http:// files.  Support should be added for srb:// files
1158
   * as well.
1159
   */
1160
  private void handleGetDataDocumentAction(ServletOutputStream out, 
1161
               Hashtable params, 
1162
               HttpServletResponse response) {
1163
  //find the related files, get them from their source and zip them into 
1164
  //a zip file.
1165
  try
1166
  {
1167
    Connection conn = util.getConnection();
1168
    String currentDocid = ((String[])params.get("docid"))[0];
1169
    ZipOutputStream zout = new ZipOutputStream(out);
1170
    byte[] bytestring = null;
1171
    ZipEntry zentry = null;
1172
    DocumentImpl xmldoc = null;
1173
    String[] reldocs = null;
1174
    
1175
    if(params.containsKey("relation"))
1176
    { //get the relations from the parameters.
1177
      reldocs = ((String[])params.get("relation"));
1178
    }
1179
    else
1180
    { //let the for loop know that there are no relations to zip
1181
      reldocs = new String[0];
1182
    }
1183

    
1184
    //write the base file to the zip file.
1185
    xmldoc = new DocumentImpl(conn, currentDocid);
1186
    bytestring = (xmldoc.toString()).getBytes();
1187
    zentry = new ZipEntry(currentDocid + ".xml");
1188
    //create a new zip entry and write the file to the stream
1189
    zentry.setSize(bytestring.length);
1190
    zout.putNextEntry(zentry);
1191
    zout.write(bytestring, 0, bytestring.length);
1192
    zout.closeEntry(); //get ready for the next entry. 
1193

    
1194
    //zip up the related documents
1195
    for(int i=0; i<reldocs.length; i++)
1196
    {
1197
      //MetacatURL murl = new MetacatURL(((String)reldocs[i]));
1198
      URL murl = new URL(((String)reldocs[i]));
1199
      Hashtable qparams = util.parseQuery(murl.getQuery());
1200
      if(murl.getProtocol().equals("metacat"))
1201
      {
1202
        //get the document from the database
1203
        //xmldoc = new DocumentImpl(conn, (String)murl.getHashParam("docid"));
1204
        xmldoc = new DocumentImpl(conn, (String)qparams.get("docid"));
1205
        bytestring = (xmldoc.toString()).getBytes();
1206
        zentry = new ZipEntry(qparams.get("docid") + ".xml");
1207
        //create a new zip entry and write the file to the stream
1208
        zentry.setSize(bytestring.length);
1209
        zout.putNextEntry(zentry);
1210
        zout.write(bytestring, 0, bytestring.length);
1211
        zout.closeEntry(); //get ready for the next entry.
1212
      }
1213
      else if(murl.getProtocol().equals("http"))
1214
      {
1215
        //Hashtable murlParams = murl.getHashParams();
1216
        if(qparams.containsKey("httpurl"))
1217
        {//httpurl is the param name for an http url.
1218
          URL urlconn = new URL((String)qparams.get("httpurl"));  
1219
          //create a new url obj.
1220
          BufferedReader htmldoc = new BufferedReader(
1221
                                   new InputStreamReader(urlconn.openStream()));
1222
          //get the data from the web server
1223
          try
1224
          { //zip the document
1225
            String line=null;
1226
            zentry = new ZipEntry((String)qparams.get("filename"));
1227
            //get just the filename from the URL.
1228
            zout.putNextEntry(zentry);
1229
            //make a new entry in the zip file stream
1230
            while((line = htmldoc.readLine()) != null)
1231
            {
1232
              bytestring = (line.toString()).getBytes();
1233
              zout.write(bytestring, 0, bytestring.length);
1234
              //write out the file line by line
1235
            }
1236
            zout.closeEntry(); //close the entry in the file
1237
          }
1238
          catch(Exception e)
1239
          {
1240
            util.debugMessage("error downloading html document"); 
1241
          }
1242
        }
1243
      }
1244
    }
1245
    zout.finish();  //terminate the zip file
1246
    zout.close();   //close the stream.
1247
    util.returnConnection(conn); //return the connection to the pool
1248
  }
1249
  catch(Exception e)
1250
  {
1251
    System.out.println("Error creating zip file: " + e.getMessage()); 
1252
    e.printStackTrace(System.out);
1253
  }
1254
           
1255
   /*
1256
   //////////old code using a shell script/////////////////////////////////
1257
   
1258
      boolean error_flag = false;
1259
      String error_message = "";
1260
      // Get the document indicated
1261
      String[] datadoc = (String[])params.get("datadoc");
1262
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1263
      // executescript = "test.bat";        // for testing only!!!
1264
      
1265
      // set content type and other response header fields first
1266
      response.setContentType("application/octet-stream");
1267
      if (defaultdatapath!=null) {
1268
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1269
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1270
        }
1271
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1272
        if (executescript!=null) {
1273
          String command = null;
1274
          File scriptfile = new File(executescript);
1275
          if (scriptfile.exists()) {
1276
            command=executescript+" "+datadoc[0]; // script includes path
1277
        } else {     // look in defaultdatapath
1278
            // on Win98 one MUST include the .bat extender
1279
            command = defaultdatapath+executescript+" "+datadoc[0];  
1280
        }
1281
      System.out.println(command);
1282
      try {
1283
      Process proc = Runtime.getRuntime().exec(command);
1284
      proc.waitFor();
1285
      }
1286
      catch (Exception eee) {
1287
        System.out.println("Error running process!");
1288
        error_flag = true;
1289
        error_message = "Error running process!";}
1290
      } // end executescript not null if
1291
      File datafile = new File(defaultdatapath+datadoc[0]);
1292
      try {
1293
      FileInputStream fw = new FileInputStream(datafile);
1294
      int x;
1295
      while ((x = fw.read())!=-1) {
1296
        out.write(x); }
1297
        fw.close();
1298
      } catch (Exception e) {
1299
        System.out.println("Error in returning file\n"+e.getMessage());
1300
        error_flag=true;
1301
        error_message = error_message+"\nError in returning file\n"+
1302
                        e.getMessage();
1303
      }
1304
    } // end defaultdatapath not null if
1305
    */
1306
  }
1307
  
1308
  /** 
1309
   * Handle the getdoctypes Action.
1310
   * Read all doctypes from db connection in XML format
1311
   */
1312
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1313
                                       HttpServletResponse response) {
1314

    
1315
    Connection conn = null;
1316
    
1317
    try {
1318

    
1319
        // get connection from the pool
1320
        conn = util.getConnection();
1321
        DBUtil dbutil = new DBUtil(conn);
1322
        String doctypes = dbutil.readDoctypes();
1323
        out.println(doctypes);
1324

    
1325
    } catch (Exception e) {
1326
      out.println("<?xml version=\"1.0\"?>");
1327
      out.println("<error>");
1328
      out.println(e.getMessage());
1329
      out.println("</error>");
1330
    } finally {
1331
      util.returnConnection(conn);
1332
    }  
1333
    
1334
  }
1335

    
1336
  /** 
1337
   * Handle the getdataguide Action.
1338
   * Read Data Guide for a given doctype from db connection in XML format
1339
   */
1340
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1341
                                        HttpServletResponse response) {
1342

    
1343
    Connection conn = null;
1344
    String doctype = null;
1345
    String[] doctypeArr = (String[])params.get("doctype");
1346

    
1347
    // get only the first doctype specified in the list of doctypes
1348
    // it could be done for all doctypes in that list
1349
    if (doctypeArr != null) {
1350
        doctype = ((String[])params.get("doctype"))[0]; 
1351
    }
1352

    
1353
    try {
1354

    
1355
        // get connection from the pool
1356
        conn = util.getConnection();
1357
        DBUtil dbutil = new DBUtil(conn);
1358
        String dataguide = dbutil.readDataGuide(doctype);
1359
        out.println(dataguide);
1360

    
1361
    } catch (Exception e) {
1362
      out.println("<?xml version=\"1.0\"?>");
1363
      out.println("<error>");
1364
      out.println(e.getMessage());
1365
      out.println("</error>");
1366
    } finally {
1367
      util.returnConnection(conn);
1368
    }  
1369
    
1370
  }
1371

    
1372
}
(27-27/38)