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-09-26 15:06:52 -0700 (Tue, 26 Sep 2000) $'
11
 * '$Revision: 465 $'
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 = decodeMouseAction(params);
216
    if(action.equals("error"))
217
    {
218
      action = ((String[])params.get("action"))[0];  
219
    }
220
    
221
    // This block handles session management for the servlet
222
    // by looking up the current session information for all actions
223
    // other than "Login" and "Logout"
224
    // handle login action
225
    String username = null;
226
    String groupname = null;
227
    if (action.equals("Login") || action.equals("Login Client")) {
228
      handleLoginAction(response.getWriter(), params, request, response);
229
    // handle logout action  
230
    } else if (action.equals("Logout") || action.equals("Logout Client")) {
231
      HttpSession sess = request.getSession(false);
232
      if (sess != null) { sess.invalidate();  }    
233
      if (action.equals("Logout Client")) {
234
        PrintWriter out = response.getWriter();
235
        out.println("<?xml version=\"1.0\"?>");
236
        out.println("<success>");
237
        out.println("User logout.");
238
        out.println("</success>");
239
        return;
240
      }    
241

    
242
      response.sendRedirect(htmlpath + "/index.html"); 
243

    
244
    // aware of session expiration on every request  
245
    } else {   
246
      HttpSession sess = request.getSession(true);
247
      if (sess.isNew()) { 
248
        // session expired or has not been stored b/w user requests
249
        // redirect to default page for query only access
250
        //  response.sendRedirect(htmlpath + "/sexpire.html");
251
        username = "public";
252
      } else {
253
        username = (String)sess.getAttribute("username");
254
        groupname = (String)sess.getAttribute("groupname");
255
      }  
256
    }    
257

    
258
    // Now that we know the session is valid, we can delegate the request
259
    // to a particular action handler
260
    if(action.equals("query"))
261
    {
262
      handleQuery(response.getWriter(), params, response, username, groupname); 
263
    } 
264
    else if(action.equals("squery"))
265
    {
266
      if(params.containsKey("query"))
267
      {
268
        handleSQuery(response.getWriter(), params, response, username, groupname); 
269
      }
270
      else
271
      {
272
        PrintWriter out = response.getWriter();
273
        out.println("Illegal action squery without \"query\" parameter");
274
      }
275
    }
276
    else if (action.equals("getdocument")) {
277
      PrintWriter out = response.getWriter();
278
      try {
279
        handleGetDocumentAction(out, params, response);
280
      } catch (ClassNotFoundException e) {
281
        out.println(e.getMessage());
282
      } catch (SQLException se) {
283
        out.println(se.getMessage());
284
      }
285
    } 
286
    else if (action.equals("getrelateddocument")) {
287
      PrintWriter out = response.getWriter();
288
      try {
289
        handleGetRelatedDocumentAction(out, params, response);
290
      } catch (ClassNotFoundException e) {
291
        out.println(e.getMessage());
292
      } catch (SQLException se) {
293
        out.println(se.getMessage());
294
      }
295
    }
296
    else if (action.equals("insert") || action.equals("update")) {
297
      PrintWriter out = response.getWriter();
298
      if ( !username.equals("public") && (username != null) ) {
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.equals("public") && (username != null) ) {
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("Login Client")) {
333
    } else {
334
      PrintWriter out = response.getWriter();
335
      out.println("Error: action not registered.  Please report this error.");
336
    }
337
    util.closeConnections();
338
    // Close the stream to the client
339
    //out.close();
340
  }
341
  
342
  /**
343
   * decodes the mouse click information coming from the client.
344
   * This function may be overwritten to provide specific functionality
345
   * for different applications.
346
   * @param params the parameters from the CGI
347
   * @return action the action to be performed or "error" if an error was
348
   * generated
349
   */
350
  protected String decodeMouseAction(Hashtable params)
351
  {
352
    // Determine what type of request the user made
353
    // if the action parameter is set, use it as a default
354
    // but if the ypos param is set, calculate the action needed
355
    String action=null;
356
    long ypos = 0;
357
    try {
358
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
359
      //out.println("<P>YPOS IS " + ypos);
360
      if (ypos <= 13) {
361
        action = "getdocument";
362
      } else if (ypos > 13 && ypos <= 27) {
363
        action = "validate";
364
      } else if (ypos > 27) {
365
        action = "transform";
366
      }
367
      return action;
368
    } catch (Exception npe) {
369
      //
370
      // MBJ -- NOTE that this should be handled more gracefully with
371
      //        the new exception infrastructure -- this "error" return
372
      //        value is inappropriate
373
      //out.println("<P>Caught exception looking for Y value.");
374
      return "error";
375
    }  
376
  }
377

    
378
  /** 
379
   * Handle the Login request. Create a new session object.
380
   * Make a user authentication through SRB RMI Connection.
381
   */
382
  private void handleLoginAction(PrintWriter out, Hashtable params, 
383
               HttpServletRequest request, HttpServletResponse response) {
384

    
385
    MetaCatSession sess = null;
386
    String un = ((String[])params.get("username"))[0];
387
    String pw = ((String[])params.get("password"))[0];
388
    String action = ((String[])params.get("action"))[0];
389
    
390
    try {
391
        sess = new MetaCatSession(request, un, pw);
392
    } catch (Exception e) {
393
      out.println(e.getMessage());
394
    }
395
    
396
    String output = null;
397
    output = sess.userLogin(response, un, pw, action, htmlpath);
398
    out.println(output);
399

    
400
  }    
401
  
402
  /**      
403
   * Retreive the squery xml, execute it and display it
404
   *
405
   * @param out the output stream to the client
406
   * @param params the Hashtable of parameters that should be included
407
   * in the squery.
408
   * @param response the response object linked to the client
409
   * @param conn the database connection 
410
   */
411
  protected void handleSQuery(PrintWriter out, Hashtable params, 
412
                 HttpServletResponse response, String user, String group)
413
  { 
414
    String xmlquery = ((String[])params.get("query"))[0];
415
    String qformat = ((String[])params.get("qformat"))[0];
416
    String resultdoc = null;
417
    String[] returndoc = null;
418
    if(params.contains("returndoc"))
419
    {
420
      returndoc = (String[])params.get("returndoc");
421
    }
422
    
423
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
424
    //String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
425

    
426
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
427
    
428
    //format and transform the results                                        
429
    if(qformat.equals("html")) {
430
      transformResultset(resultdoc, response, out);
431
    } else if(qformat.equals("xml")) {
432
      response.setContentType("text/xml");
433
      out.println(resultdoc);
434
    } else {
435
      out.println("invalid qformat: " + qformat); 
436
    }
437
  }
438
  
439
   /**
440
    * Create the xml query, execute it and display the results.
441
    *
442
    * @param out the output stream to the client
443
    * @param params the Hashtable of parameters that should be included
444
    * in the squery.
445
    * @param response the response object linked to the client
446
    */ 
447
  protected void handleQuery(PrintWriter out, Hashtable params, 
448
                 HttpServletResponse response, String user, String group)
449
  {
450
    //create the query and run it
451
    String[] returndoc = null;
452
    if(params.containsKey("returndoc"))
453
    {
454
      returndoc = (String[])params.get("returndoc");
455
    }
456
    String xmlquery = DBQuery.createSQuery(params);
457
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
458
    String qformat = ((String[])params.get("qformat"))[0];
459
    String resultdoc = null;
460
    
461
    resultdoc = createResultDocument(doclist, transformQuery(params));
462

    
463
    //format and transform the results                                        
464
    if(qformat.equals("html")) {
465
      transformResultset(resultdoc, response, out);
466
    } else if(qformat.equals("xml")) {
467
      response.setContentType("text/xml");
468
      out.println(resultdoc);
469
    } else { 
470
      out.println("invalid qformat: " + qformat); 
471
    }
472
  }
473
  
474
  /**
475
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
476
   * so it can properly be placed in the <query> tag of the resultset.
477
   * This method is overwritable so that other applications can customize
478
   * the structure of what is in the <query> tag.
479
   * 
480
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
481
   */
482
  protected String transformQuery(Hashtable params)
483
  {
484
    //DBQuery.createSQuery is a re-calling of a previously called 
485
    //function but it is necessary
486
    //so that overriding methods have access to the params hashtable
487
    String xmlquery = DBQuery.createSQuery(params);
488
    //the <?xml version="1.0"?> tag is the first 22 characters of the
489
    xmlquery = xmlquery.trim();
490
    int index = xmlquery.indexOf("?>");
491
    return xmlquery.substring(index + 2, xmlquery.length());
492
  }
493
  
494
  /**
495
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
496
   * string as a param instead of a hashtable.
497
   * 
498
   * @param xmlquery a string representing a query.
499
   */
500
  protected String transformQuery(String xmlquery)
501
  {
502
    xmlquery = xmlquery.trim();
503
    int index = xmlquery.indexOf("?>");
504
    return xmlquery.substring(index + 2, xmlquery.length());
505
  }
506
  
507
  /**
508
   * Run the query and return a hashtable of results.
509
   *
510
   * @param xmlquery the query to run
511
   */
512
  private Hashtable runQuery(String xmlquery, String user, String group, 
513
                             String[] returndoc)
514
  {
515
    Hashtable doclist=null;
516
    Connection conn = null;
517
    try
518
    {
519
      conn = util.getConnection();
520
      DBQuery queryobj = new DBQuery(conn, saxparser);
521
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
522
                                       returndoc);
523
      util.returnConnection(conn);
524
      return doclist;
525
    } 
526
    catch (Exception e) 
527
    {
528
      util.returnConnection(conn); 
529
      util.debugMessage("Error in runQuery: " + e.getMessage());
530
      doclist = null;
531
      return doclist;
532
    }    
533
  }
534
  
535
  /**
536
   * Transorms an xml resultset document to html and sends it to the browser
537
   *
538
   * @param resultdoc the string representation of the document that needs
539
   * to be transformed.
540
   * @param response the HttpServletResponse object bound to the client.
541
   * @param out the output stream to the client
542
   */ 
543
  protected void transformResultset(String resultdoc, 
544
                                    HttpServletResponse response,
545
                                    PrintWriter out)
546
  {
547
    Connection conn = null;
548
    try {
549
      conn = util.getConnection();
550
      DBTransform trans = new DBTransform(conn);
551
      response.setContentType("text/html");
552
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
553
                                 "-//W3C//HTML//EN", out);
554
      util.returnConnection(conn); 
555
    }
556
    catch(Exception e)
557
    {
558
      util.returnConnection(conn); 
559
    } 
560
  }
561
  
562
  /**
563
   * Transforms a hashtable of documents to an xml or html result.
564
   * If there is a returndoc, then it only displays documents of
565
   * whatever type returndoc represents.  If a result is found in a document
566
   * that is not of type returndoc then this attempts to find a relation 
567
   * between this document and one that satifies the returndoc doctype.
568
   *
569
   * @param doclist- the hashtable to transform
570
   * @param xmlquery- the query that returned the dolist result
571
   * @param resultdoc- the document type to backtrack to.
572
   */
573
  protected String createResultDocument(Hashtable doclist, String xmlquery)
574
  {
575
    // Create a buffer to hold the xml result
576
    StringBuffer resultset = new StringBuffer();
577
 
578
    // Print the resulting root nodes 
579
    String docid = null;
580
    String document = null;
581
    resultset.append("<?xml version=\"1.0\"?>\n");
582
    resultset.append("<resultset>\n");
583
      
584
    resultset.append("  <query>" + xmlquery + "</query>");   
585
      
586
    Enumeration doclistkeys = doclist.keys(); 
587
    while (doclistkeys.hasMoreElements()) 
588
    {
589
      docid = (String)doclistkeys.nextElement();
590
      document = (String)doclist.get(docid);
591
      resultset.append("  <document>" + document + "</document>");
592
    } 
593
    resultset.append("</resultset>");
594
    //System.out.println(resultset.toString());
595
    return resultset.toString();
596
  }
597
  
598
  /**
599
   * Handle the request to view the abstract of a document.
600
   * The abstractpath CGI parameter gives the xml path to the abstract
601
   * node.  
602
   */
603
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
604
               HttpServletResponse response) throws IOException, SQLException
605
  {
606
    String abstractpath = null;
607
    String docid = null;
608
    Connection conn = null;
609
    response.setContentType("text/html");
610
    try
611
    {
612
      docid = ((String[])params.get("docid"))[0];
613
      if(params.containsKey("abstractpath"))
614
      {
615
        //the CGI parameter abstractpath holds the path to the abstract
616
        //that should be displayed.
617
        abstractpath = ((String[])params.get("abstractpath"))[0];
618
      }
619
      else
620
      {
621
        out.println("error: no abstractpath parameter"); 
622
      }
623
      conn = util.getConnection();
624
    
625
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
626
    
627
      out.println("<html><head><title>Abstract</title></head>");
628
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
629
      for(int i=0; i<abstracts.length; i++)
630
      {
631
        out.println("<p>" + (String)abstracts[i] + "</p>");
632
      }
633
      out.println("</body></html>");
634
    }
635
    catch (IOException ioe)
636
    {
637
       util.debugMessage("error in handlegetabstract: " + ioe.getMessage());
638
    }
639
    catch(SQLException sqle)
640
    {
641
      util.debugMessage("error in handlegetabstract: " + sqle.getMessage()); 
642
    }
643
    catch(Exception e)
644
    {
645
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
646
    }
647
    
648
    util.returnConnection(conn);
649
  }
650

    
651
  /** 
652
   * Handle the database getrelateddocument request and return a XML document, 
653
   * possibly transformed from XML into HTML
654
   */
655
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params, 
656
               HttpServletResponse response) 
657
               throws ClassNotFoundException, IOException, SQLException 
658
  {
659
    String docid = null;
660
    Connection conn = null;
661
      
662
    if(params.containsKey("url"))
663
    {//the identifier for the related document is contained in the URL param
664
      try
665
      {
666
        DocumentImpl xmldoc=null;
667
        metacatURL murl = new metacatURL(((String[])params.get("url"))[0]);
668
        if(murl.getURLType().equals("metacat"))
669
        {//get the document from the database if it is the right type of url
670
          String[] murlParams = murl.getParam(0);
671
          if(murlParams[0].equals("docid"))
672
          {//the docid should be first
673
            //murl.printParams();
674
            docid = murlParams[1]; //get the docid value
675
            conn = util.getConnection();
676
            xmldoc = new DocumentImpl(conn, docid);
677
            
678
            //**************************************************
679
            //the style sheet handling code needs to be put here. 
680
            out.println(xmldoc.toString());
681
            //**************************************************
682
          }
683
          else
684
          {
685
            //throw new Exception("handleGetDocument: bad URL");
686
            System.err.println("handleGetDocument: bad URL");
687
          }
688
        }
689
        else if(murl.getURLType().equals("http"))
690
        {//get the document from the internet
691
          String[] murlParams = murl.getParam(0);
692
          if(murlParams[0].equals("httpurl"))
693
          {//httpurl is the param name for an http url.
694
            URL urlconn = new URL(murlParams[1]);  //create a new url obj.
695
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
696
            BufferedReader htmldoc = new BufferedReader(
697
                                   new InputStreamReader(urlconn.openStream()));
698
            //bind a data stream.
699
            try
700
            { //display the document
701
              String line=null;
702
              while((line = htmldoc.readLine()) != null)
703
              {
704
                out.println(line); 
705
              }
706
            }
707
            catch(Exception e)
708
            {
709
              util.debugMessage("error viewing html document"); 
710
            }
711
          }
712
        }
713
      }
714
      catch (McdbException e) {
715
        response.setContentType("text/xml");
716
        e.toXml(out);
717
      } catch   (Throwable t) {
718
        response.setContentType("text/html");
719
        out.println(t.getMessage());
720
      } finally {
721
        util.returnConnection(conn);
722
      }
723
    }
724
  }   
725
  
726
  /** 
727
   * Handle the database getdocument request and return a XML document, 
728
   * possibly transformed from XML into HTML
729
   */
730
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
731
               HttpServletResponse response) 
732
               throws ClassNotFoundException, IOException, SQLException {
733
    String docidstr = null;
734
    String docid = null;
735
    String doc = null;
736
    Connection conn = null;
737
    
738
    try {
739
      // Find the document id number
740
      docidstr = ((String[])params.get("docid"))[0]; 
741
      docid = docidstr;
742
      conn = util.getConnection();
743
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
744
      // Get the document indicated from the db
745
      //doc = docreader.readXMLDocument(docid);
746

    
747
      // Return the document in XML or HTML format
748
      String qformat=null;
749
      if(params.containsKey("qformat"))
750
      {
751
        qformat = ((String[])params.get("qformat"))[0];
752
      }
753
      else
754
      {
755
        qformat = "html";        
756
      }
757
      if (qformat.equals("xml")) { 
758
        // set content type and other response header fields first
759
        response.setContentType("text/xml");
760
        xmldoc.toXml(out);
761
        //out.println(xmldoc);
762
      } else if (qformat.equals("html")) {
763
        response.setContentType("text/html");
764
        // Look up the document type
765
        String sourcetype = xmldoc.getDoctype();
766
        // Transform the document to the new doctype
767
        DBTransform dbt = new DBTransform(conn);
768
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
769
                                 "-//W3C//HTML//EN", out);
770
      }
771
    } catch (McdbException e) {
772
      response.setContentType("text/xml");
773
      e.toXml(out);
774
    } catch (Throwable t) {
775
      response.setContentType("text/html");
776
      out.println(t.getMessage());
777
    } finally {
778
      util.returnConnection(conn);
779
    }    
780

    
781
  }
782

    
783
  /** 
784
   * Handle the database putdocument request and write an XML document 
785
   * to the database connection
786
   */
787
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
788
               HttpServletResponse response, String user, String group) {
789

    
790
    Connection conn = null;
791

    
792
    try {
793
      // Get the document indicated
794
      String[] doctext = (String[])params.get("doctext");
795
      StringReader xml = null;
796
      try {
797
        xml = new StringReader(doctext[0]);
798

    
799
        String[] action = (String[])params.get("action");
800
        String[] docid = (String[])params.get("docid");
801
        String newdocid = null;
802

    
803
        String doAction = null;
804
        if (action[0].equals("insert")) {
805
          doAction = "INSERT";
806
        } else if (action[0].equals("update")) {
807
          doAction = "UPDATE";
808
        }
809

    
810
        try {
811
            // get a connection from the pool
812
            conn = util.getConnection();
813

    
814
            // write the document to the database
815
            try {
816
                String accNumber = docid[0];
817
                if (accNumber.equals("")) {
818
                    accNumber = null;
819
                }
820
                newdocid = DocumentImpl.write(conn, xml, doAction, accNumber, 
821
                                              user, group);
822
                DocumentImpl xmldoc = new DocumentImpl(conn, newdocid);
823
                
824
               //if this is a package file then write the package info to 
825
               //the xml_relation table. relationHandler checks to see
826
               //if it is a package file so you don't have to do it here.
827
               relationHandler rth = new relationHandler(xmldoc);
828
                
829
            } catch (NullPointerException npe) {
830
              newdocid = DocumentImpl.write(conn,xml,doAction,null,user,group);
831
            }
832
//        } catch (Exception e) {
833
//          response.setContentType("text/html");
834
//          out.println(e.getMessage());
835
        } finally {
836
          util.returnConnection(conn);
837
        }    
838

    
839
        // set content type and other response header fields first
840
        response.setContentType("text/xml");
841
        out.println("<?xml version=\"1.0\"?>");
842
        out.println("<success>");
843
        out.println("<docid>" + newdocid + "</docid>"); 
844
        out.println("</success>");
845

    
846
      } catch (NullPointerException npe) {
847
        response.setContentType("text/xml");
848
        out.println("<?xml version=\"1.0\"?>");
849
        out.println("<error>");
850
        out.println(npe.getMessage()); 
851
        out.println("</error>");
852
      }
853
    } catch (Exception e) {
854
      response.setContentType("text/xml");
855
      out.println("<?xml version=\"1.0\"?>");
856
      out.println("<error>");
857
      out.println(e.getMessage()); 
858
      if (e instanceof SAXException) {
859
        Exception e2 = ((SAXException)e).getException();
860
        out.println("<error>");
861
        out.println(e2.getMessage()); 
862
        out.println("</error>");
863
      }
864
      //e.printStackTrace(out);
865
      out.println("</error>");
866
    }
867
  }
868

    
869
  /** 
870
   * Handle the database delete request and delete an XML document 
871
   * from the database connection
872
   */
873
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
874
               HttpServletResponse response, String user, String group) {
875

    
876
    String[] docid = (String[])params.get("docid");
877
    Connection conn = null;
878

    
879
    // delete the document from the database
880
    try {
881
      // get a connection from the pool
882
      conn = util.getConnection();
883
                                      // NOTE -- NEED TO TEST HERE
884
                                      // FOR EXISTENCE OF DOCID PARAM
885
                                      // BEFORE ACCESSING ARRAY
886
      try { 
887
        DocumentImpl.delete(conn, docid[0], user, group);
888
        response.setContentType("text/xml");
889
        out.println("<?xml version=\"1.0\"?>");
890
        out.println("<success>");
891
        out.println("Document deleted."); 
892
        out.println("</success>");
893
      } catch (AccessionNumberException ane) {
894
        response.setContentType("text/xml");
895
        out.println("<?xml version=\"1.0\"?>");
896
        out.println("<error>");
897
        out.println("Error deleting document!!!");
898
        out.println(ane.getMessage()); 
899
        out.println("</error>");
900
      }
901
    } catch (Exception e) {
902
      response.setContentType("text/xml");
903
      out.println("<?xml version=\"1.0\"?>");
904
      out.println("<error>");
905
      out.println(e.getMessage()); 
906
      out.println("</error>");
907
    } finally {
908
      util.returnConnection(conn);
909
    }  
910
  }
911
  
912
  /** 
913
   * Handle the validation request and return the results to the requestor
914
   */
915
  private void handleValidateAction(PrintWriter out, Hashtable params, 
916
               HttpServletResponse response) {
917

    
918
    // Get the document indicated
919
    String valtext = null;
920
    
921
    try {
922
      valtext = ((String[])params.get("valtext"))[0];
923
    } catch (Exception nullpe) {
924

    
925
      Connection conn = null;
926
      String docid = null;
927
      try {
928
        // Find the document id number
929
        docid = ((String[])params.get("docid"))[0]; 
930

    
931
        // get a connection from the pool
932
        conn = util.getConnection();
933

    
934
        // Get the document indicated from the db
935
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
936
        valtext = xmldoc.toString();
937

    
938
      } catch (NullPointerException npe) {
939
        response.setContentType("text/xml");
940
        out.println("<error>Error getting document ID: " + docid + "</error>");
941
        if ( conn != null ) { util.returnConnection(conn); }
942
        return;
943
      } catch (Exception e) {
944
        response.setContentType("text/html");
945
        out.println(e.getMessage()); 
946
      } finally {
947
        util.returnConnection(conn);
948
      }  
949
    }
950

    
951
    Connection conn = null;
952
    try {
953
      // get a connection from the pool
954
      conn = util.getConnection();
955
      DBValidate valobj = new DBValidate(saxparser,conn);
956
      boolean valid = valobj.validateString(valtext);
957

    
958
      // set content type and other response header fields first
959
      response.setContentType("text/xml");
960
      out.println(valobj.returnErrors());
961

    
962
    } catch (NullPointerException npe2) {
963
      // set content type and other response header fields first
964
      response.setContentType("text/xml");
965
      out.println("<error>Error validating document.</error>"); 
966
    } catch (Exception e) {
967
      response.setContentType("text/html");
968
      out.println(e.getMessage()); 
969
    } finally {
970
      util.returnConnection(conn);
971
    }  
972
  }
973

    
974
  /** 
975
   * Handle the document request and return the results to the requestor
976
   * If a docid is passed in through the params then that document
977
   * will be retrieved form the DB and put in the zip file.
978
   * In addition if 1 or more relations parameters are passed, those file
979
   * will be zipped as well.  Currently this is only implemented for 
980
   * metacat:// and http:// files.  Support should be added for srb:// files
981
   * as well.
982
   */
983
  private void handleGetDataDocumentAction(ServletOutputStream out, 
984
               Hashtable params, 
985
               HttpServletResponse response) {
986
  //find the related files, get them from their source and zip them into 
987
  //a zip file.
988
  try
989
  {
990
    Connection conn = util.getConnection();
991
    String currentDocid = ((String[])params.get("docid"))[0];
992
    ZipOutputStream zout = new ZipOutputStream(out);
993
    byte[] bytestring = null;
994
    ZipEntry zentry = null;
995
    DocumentImpl xmldoc = null;
996
    String[] reldocs = null;
997
    
998
    if(params.containsKey("relation"))
999
    { //get the relations from the parameters.
1000
      reldocs = ((String[])params.get("relation"));
1001
    }
1002
    else
1003
    { //let the for loop know that there are no relations to zip
1004
      reldocs = new String[0];
1005
    }
1006

    
1007
    //write the base file to the zip file.
1008
    xmldoc = new DocumentImpl(conn, currentDocid);
1009
    bytestring = (xmldoc.toString()).getBytes();
1010
    zentry = new ZipEntry(currentDocid + ".xml");
1011
    //create a new zip entry and write the file to the stream
1012
    zentry.setSize(bytestring.length);
1013
    zout.putNextEntry(zentry);
1014
    zout.write(bytestring, 0, bytestring.length);
1015
    zout.closeEntry(); //get ready for the next entry. 
1016

    
1017
    //zip up the related documents
1018
    for(int i=0; i<reldocs.length; i++)
1019
    {
1020
      metacatURL murl = new metacatURL(((String)reldocs[i]));
1021
      if(murl.getURLType().equals("metacat"))
1022
      {
1023
        //get the document from the database
1024
        xmldoc = new DocumentImpl(conn, (murl.getParam(0))[1]);
1025
        bytestring = (xmldoc.toString()).getBytes();
1026
        zentry = new ZipEntry((murl.getParam(0))[1] + ".xml");
1027
        //create a new zip entry and write the file to the stream
1028
        zentry.setSize(bytestring.length);
1029
        zout.putNextEntry(zentry);
1030
        zout.write(bytestring, 0, bytestring.length);
1031
        zout.closeEntry(); //get ready for the next entry.
1032
      }
1033
      else if(murl.getURLType().equals("http"))
1034
      {
1035
        String[] murlParams = murl.getParam(0);
1036
        if(murlParams[0].equals("httpurl"))
1037
        {//httpurl is the param name for an http url.
1038
          URL urlconn = new URL(murlParams[1]);  //create a new url obj.
1039
          BufferedReader htmldoc = new BufferedReader(
1040
                                   new InputStreamReader(urlconn.openStream()));
1041
          //get the data from the web server
1042
          try
1043
          { //zip the document
1044
            String line=null;
1045
            zentry = new ZipEntry((murl.getParam(1))[1]);
1046
            //get just the filename from the URL.
1047
            zout.putNextEntry(zentry);
1048
            //make a new entry in the zip file stream
1049
            while((line = htmldoc.readLine()) != null)
1050
            {
1051
              bytestring = (line.toString()).getBytes();
1052
              zout.write(bytestring, 0, bytestring.length);
1053
              //write out the file line by line
1054
            }
1055
            zout.closeEntry(); //close the entry in the file
1056
          }
1057
          catch(Exception e)
1058
          {
1059
            util.debugMessage("error downloading html document"); 
1060
          }
1061
        }
1062
      }
1063
    }
1064
    zout.finish();  //terminate the zip file
1065
    zout.close();   //close the stream.
1066
    util.returnConnection(conn); //return the connection to the pool
1067
  }
1068
  catch(Exception e)
1069
  {
1070
    System.out.println("Error creating zip file: " + e.getMessage()); 
1071
    e.printStackTrace(System.out);
1072
  }
1073
           
1074
   /*
1075
   //////////old code using a shell script/////////////////////////////////
1076
   
1077
      boolean error_flag = false;
1078
      String error_message = "";
1079
      // Get the document indicated
1080
      String[] datadoc = (String[])params.get("datadoc");
1081
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1082
      // executescript = "test.bat";        // for testing only!!!
1083
      
1084
      // set content type and other response header fields first
1085
      response.setContentType("application/octet-stream");
1086
      if (defaultdatapath!=null) {
1087
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1088
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1089
        }
1090
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1091
        if (executescript!=null) {
1092
          String command = null;
1093
          File scriptfile = new File(executescript);
1094
          if (scriptfile.exists()) {
1095
            command=executescript+" "+datadoc[0]; // script includes path
1096
        } else {     // look in defaultdatapath
1097
            // on Win98 one MUST include the .bat extender
1098
            command = defaultdatapath+executescript+" "+datadoc[0];  
1099
        }
1100
      System.out.println(command);
1101
      try {
1102
      Process proc = Runtime.getRuntime().exec(command);
1103
      proc.waitFor();
1104
      }
1105
      catch (Exception eee) {
1106
        System.out.println("Error running process!");
1107
        error_flag = true;
1108
        error_message = "Error running process!";}
1109
      } // end executescript not null if
1110
      File datafile = new File(defaultdatapath+datadoc[0]);
1111
      try {
1112
      FileInputStream fw = new FileInputStream(datafile);
1113
      int x;
1114
      while ((x = fw.read())!=-1) {
1115
        out.write(x); }
1116
        fw.close();
1117
      } catch (Exception e) {
1118
        System.out.println("Error in returning file\n"+e.getMessage());
1119
        error_flag=true;
1120
        error_message = error_message+"\nError in returning file\n"+
1121
                        e.getMessage();
1122
      }
1123
    } // end defaultdatapath not null if
1124
    */
1125
  }
1126
  
1127
  /** 
1128
   * Handle the getdoctypes Action.
1129
   * Read all doctypes from db connection in XML format
1130
   */
1131
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1132
                                       HttpServletResponse response) {
1133

    
1134
    Connection conn = null;
1135
    
1136
    try {
1137

    
1138
        // get connection from the pool
1139
        conn = util.getConnection();
1140
        DBUtil dbutil = new DBUtil(conn);
1141
        String doctypes = dbutil.readDoctypes();
1142
        out.println(doctypes);
1143

    
1144
    } catch (Exception e) {
1145
      out.println("<?xml version=\"1.0\"?>");
1146
      out.println("<error>");
1147
      out.println(e.getMessage());
1148
      out.println("</error>");
1149
    } finally {
1150
      util.returnConnection(conn);
1151
    }  
1152
    
1153
  }
1154

    
1155
  /** 
1156
   * Handle the getdataguide Action.
1157
   * Read Data Guide for a given doctype from db connection in XML format
1158
   */
1159
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1160
                                        HttpServletResponse response) {
1161

    
1162
    Connection conn = null;
1163
    String doctype = null;
1164
    String[] doctypeArr = (String[])params.get("doctype");
1165

    
1166
    // get only the first doctype specified in the list of doctypes
1167
    // it could be done for all doctypes in that list
1168
    if (doctypeArr != null) {
1169
        doctype = ((String[])params.get("doctype"))[0]; 
1170
    }
1171

    
1172
    try {
1173

    
1174
        // get connection from the pool
1175
        conn = util.getConnection();
1176
        DBUtil dbutil = new DBUtil(conn);
1177
        String dataguide = dbutil.readDataGuide(doctype);
1178
        out.println(dataguide);
1179

    
1180
    } catch (Exception e) {
1181
      out.println("<?xml version=\"1.0\"?>");
1182
      out.println("<error>");
1183
      out.println(e.getMessage());
1184
      out.println("</error>");
1185
    } finally {
1186
      util.returnConnection(conn);
1187
    }  
1188
    
1189
  }
1190

    
1191
}
(19-19/28)