Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: bojilova $'
10
 *     '$Date: 2001-01-19 11:05:40 -0800 (Fri, 19 Jan 2001) $'
11
 * '$Revision: 680 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.io.PrintWriter;
31
import java.io.IOException;
32
import java.io.Reader;
33
import java.io.StringReader;
34
import java.io.BufferedReader;
35
import java.io.File;
36
import java.io.FileInputStream;
37
import java.io.FileOutputStream;
38
import java.io.InputStreamReader;
39
import java.io.DataInputStream;
40
import java.util.Enumeration;
41
import java.util.Hashtable;
42
import java.util.ResourceBundle; 
43
import java.util.Random;
44
import java.util.PropertyResourceBundle;
45
import java.net.URL;
46
import java.net.MalformedURLException;
47
import java.sql.PreparedStatement;
48
import java.sql.ResultSet;
49
import java.sql.Connection;
50
import java.sql.SQLException;
51
import java.lang.reflect.*;
52
import java.net.*;
53
import java.util.zip.*;
54

    
55
import javax.servlet.ServletConfig;
56
import javax.servlet.ServletContext;
57
import javax.servlet.ServletException;
58
import javax.servlet.ServletInputStream;
59
import javax.servlet.http.HttpServlet;
60
import javax.servlet.http.HttpServletRequest;
61
import javax.servlet.http.HttpServletResponse;
62
import javax.servlet.http.HttpSession;
63
import javax.servlet.http.HttpUtils;
64
import javax.servlet.ServletOutputStream;
65

    
66
import oracle.xml.parser.v2.XSLStylesheet;
67
import oracle.xml.parser.v2.XSLException;
68
import oracle.xml.parser.v2.XMLDocumentFragment;
69
import oracle.xml.parser.v2.XSLProcessor;
70

    
71
import org.xml.sax.SAXException;
72

    
73
/**
74
 * A metadata catalog server implemented as a Java Servlet
75
 *
76
 * <p>Valid parameters are:<br>
77
 * action=query -- query the values of all elements and attributes
78
 *                     and return a result set of nodes<br>
79
 * action=squery -- structured query (see pathquery.dtd)<br>
80
 * action=insert -- insert an XML document into the database store<br>
81
 * action=update -- update an XML document that is in the database store<br>
82
 * action=delete --  delete an XML document from the database store<br>
83
 * action=validate -- vallidate the xml contained in valtext<br>
84
 * action=read -- display an XML document in XML or HTML<br>
85
 * doctype -- document type list returned by the query (publicID)<br>
86
 * qformat=xml -- display resultset from query in XML<br>
87
 * qformat=html -- display resultset from query in HTML<br>
88
 * docid=34 -- display the document with the document ID number 34<br>
89
 * doctext -- XML text of the document to load into the database<br>
90
 * acltext -- XML access text for a document to load into the database<br>
91
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog<br>
92
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
93
 * valtext -- XML text to be validated<br>
94
 * action=getdatadoc -- retreive a stored datadocument<br>
95
 * action=getdoctypes -- retreive all doctypes (publicID)<br>
96
 * action=getdataguide -- retreive a Data Guide<br>
97
 * datadoc -- data document name (id)<br>
98
 * <p>
99
 * The particular combination of parameters that are valid for each 
100
 * particular action value is quite specific.  This documentation
101
 * will be reorganized to reflect this information.
102
 */
103
public class MetaCatServlet extends HttpServlet {
104

    
105
  private ServletConfig config = null;
106
  private ServletContext context = null;
107
  private Hashtable connectionPool = new Hashtable();
108
  private String resultStyleURL = null;
109
  private String xmlcatalogfile = null;
110
  private String saxparser = null;
111
  private String defaultdatapath = null; 
112
  private String servletpath = null; 
113
  private PropertyResourceBundle options = null;
114
  private MetaCatUtil util = null;
115

    
116
  // path to directory where data files 
117
  // that can be downloaded will be stored
118
  private String htmlpath = null; 
119
  // script to get data file and put it 
120
  // in defaultdocpath dir
121
  private String executescript  = null;  
122

    
123
  /**
124
   * Initialize the servlet by creating appropriate database connections
125
   */
126
  public void init( ServletConfig config ) throws ServletException {
127
    try {
128
      super.init( config );
129
      this.config = config;
130
      this.context = config.getServletContext(); 
131
      System.out.println("MetaCatServlet Initialize");
132

    
133
      util = new MetaCatUtil();
134

    
135
      // Get the configuration file information
136
      resultStyleURL = util.getOption("resultStyleURL");
137
      xmlcatalogfile = util.getOption("xmlcatalogfile");
138
      saxparser = util.getOption("saxparser");
139
      defaultdatapath = util.getOption("defaultdatapath");
140
      executescript = util.getOption("executescript"); 
141
      servletpath = util.getOption("servletpath");
142
      htmlpath = util.getOption("htmlpath");
143

    
144
//      try {
145
//        // Open a pool of db connections
146
//        connectionPool = util.getConnectionPool();
147
//      } catch (Exception e) {
148
//        System.err.println("Error creating pool of database connections");
149
//        System.err.println(e.getMessage());
150
//      }
151
    } catch ( ServletException ex ) {
152
      throw ex;
153
    }
154
  }
155

    
156
  /**
157
   * Close all db connections from the pool
158
   */
159
  public void destroy() {
160
    
161
    if (util != null) {
162
        util.closeConnections();
163
    }
164
  }
165

    
166
  /** Handle "GET" method requests from HTTP clients */
167
  public void doGet (HttpServletRequest request, HttpServletResponse response)
168
    throws ServletException, IOException {
169

    
170
    // Process the data and send back the response
171
    handleGetOrPost(request, response);
172
  }
173

    
174
  /** Handle "POST" method requests from HTTP clients */
175
  public void doPost( HttpServletRequest request, HttpServletResponse response)
176
    throws ServletException, IOException {
177

    
178
    // Process the data and send back the response
179
    handleGetOrPost(request, response);
180
  }
181

    
182
  /**
183
   * Control servlet response depending on the action parameter specified
184
   */
185
  private void handleGetOrPost(HttpServletRequest request, 
186
    HttpServletResponse response) 
187
    throws ServletException, IOException 
188
 {
189

    
190
    if ( util == null ) {
191
        util = new MetaCatUtil(); 
192
    }
193
    if ( connectionPool.isEmpty() ) {
194
      try {
195
        // Open a pool of db connections
196
        connectionPool = util.getConnectionPool();
197
      } catch (Exception e) {
198
        System.err.println("Error creating pool of database connections in " +
199
                            " MetaCatServlet.handleGetOrPost");
200
        System.err.println(e.getMessage());
201
      }
202
    }    
203
    // Get a handle to the output stream back to the client
204
    //PrintWriter pwout = response.getWriter();
205
    //response.setContentType("text/html");
206
  
207
    String name = null;
208
    String[] value = null;
209
    String[] docid = new String[3];
210
    Hashtable params = new Hashtable();
211
    Enumeration paramlist = request.getParameterNames();
212
    while (paramlist.hasMoreElements()) {
213
      name = (String)paramlist.nextElement();
214
      value = request.getParameterValues(name);
215

    
216
      // Decode the docid and mouse click information
217
      if (name.endsWith(".y")) {
218
        docid[0] = name.substring(0,name.length()-2);
219
        //out.println("docid => " + docid[0]);
220
        params.put("docid", docid);
221
        name = "ypos";
222
      }
223
      if (name.endsWith(".x")) {
224
        name = "xpos";
225
      } 
226

    
227
      //pwout.println(name + " => " + value[0]);
228
      params.put(name,value); 
229
    }  
230
    
231
    //if the user clicked on the input images, decode which image
232
    //was clicked then set the action.
233
    String action = ((String[])params.get("action"))[0];  
234
    util.debugMessage("Line 213: Action is: " + action);
235

    
236
    //MBJELIMINATE String action = decodeMouseAction(params);
237
    //if(action.equals("error"))
238
    //{
239
      //util.debugMessage("Line 218: Action is: " + action);
240
      //action = ((String[])params.get("action"))[0];  
241
    //}
242
    
243
    // This block handles session management for the servlet
244
    // by looking up the current session information for all actions
245
    // other than "login" and "logout"
246
    String username = null;
247
    String groupname = null;
248
    String sess_id = null;
249

    
250
    // handle login action
251
    if (action.equals("login")) {
252

    
253
      handleLoginAction(response.getWriter(), params, request, response);
254

    
255
    // handle logout action  
256
    } else if (action.equals("logout")) {
257

    
258
      handleLogoutAction(response.getWriter(), params, request, response);
259

    
260
    // aware of session expiration on every request  
261
    } else {   
262

    
263
      HttpSession sess = request.getSession(true);
264
      if (sess.isNew()) { 
265
        // session expired or has not been stored b/w user requests
266
        username = "public";
267
        sess.setAttribute("username", username);
268
      } else {
269
        username = (String)sess.getAttribute("username");
270
        groupname = (String)sess.getAttribute("groupname");
271
        try
272
        {
273
          sess_id = (String)sess.getId();
274
        }
275
        catch(IllegalStateException ise)
276
        {
277
          System.out.println("error in handleGetOrPost: this shouldn't " +
278
                             "happen: the session should be valid: " + 
279
                             ise.getMessage());
280
        }
281
      }  
282
    }    
283

    
284
    // Now that we know the session is valid, we can delegate the request
285
    // to a particular action handler
286
    if(action.equals("query"))
287
    {
288
      handleQuery(response.getWriter(), params, response, username, groupname); 
289
    } 
290
    else if(action.equals("squery"))
291
    {
292
      if(params.containsKey("query"))
293
      {
294
        handleSQuery(response.getWriter(), params, response, username, groupname); 
295
      }
296
      else
297
      {
298
        PrintWriter out = response.getWriter();
299
        out.println("Illegal action squery without \"query\" parameter");
300
      }
301
    }
302
    else if (action.equals("read")) {
303
      //PrintWriter out = response.getWriter();
304
      try {
305
        handleReadAction(/*out,*/ params, response, username);
306
      } catch (ClassNotFoundException e) {
307
        System.out.println("Error in MetacatServlet.handlGetOrPost: " + 
308
                            e.getMessage());
309
      } catch (SQLException se) {
310
        System.out.println("Error in MetaCatServlet.handleGetOrPost: " + 
311
                            se.getMessage());
312
      }
313
    } 
314
/*
315
    else if (action.equals("getrelateddocument")) {
316
      PrintWriter out = response.getWriter();
317
      try {
318
        handleGetRelatedDocumentAction(out, params, response);
319
      } catch (ClassNotFoundException e) {
320
        out.println(e.getMessage());
321
      } catch (SQLException se) {
322
        out.println(se.getMessage());
323
      }
324
    }
325
*/
326
    else if (action.equals("insert") || action.equals("update")) {
327
      PrintWriter out = response.getWriter();
328
      if ( (username != null) &&  !username.equals("public") ) {
329
        handleInsertOrUpdateAction(out, params, response, username, groupname);
330
      } else {  
331
        out.println("Permission denied for " + action);
332
      }  
333
    } else if (action.equals("delete")) {
334
      PrintWriter out = response.getWriter();
335
      if ( (username != null) &&  !username.equals("public") ) {
336
        handleDeleteAction(out, params, response, username, groupname);
337
      } else {  
338
        out.println("Permission denied for " + action);
339
      }  
340
    } else if (action.equals("validate")) {
341
      PrintWriter out = response.getWriter();
342
      handleValidateAction(out, params, response); 
343
    } else if (action.equals("getabstract")) {
344
      PrintWriter out = response.getWriter();
345
      try{
346
        handleViewAbstractAction(out, params, response);
347
      }
348
      catch(Exception e)
349
      {
350
        out.println("error viewing abstract from " + 
351
                    "MetacatServlet.handleGetorPost: " + e.getMessage());
352
      }
353
    } else if (action.equals("getdatadoc")) {
354
      response.setContentType("application/zip");
355
      ServletOutputStream out = response.getOutputStream();
356
      handleGetDataDocumentAction(out, params, response);  
357
    } else if (action.equals("getdoctypes")) {
358
      PrintWriter out = response.getWriter();
359
      handleGetDoctypesAction(out, params, response);  
360
    } else if (action.equals("getdataport")) {
361
      PrintWriter out = response.getWriter();
362
      if ( (username != null) &&  !username.equals("public") ) {
363
      handleGetDataPortAction(out, params, response, username, groupname, 
364
                              sess_id);
365
      } else {
366
        out.println("You must be authenticated to perform the getdataport " +
367
                    "action!");
368
      }
369
    } else if (action.equals("getdataguide")) {
370
      PrintWriter out = response.getWriter();
371
      handleGetDataGuideAction(out, params, response);  
372
    } else if (action.equals("login") || action.equals("logout")) {
373
    } else if (action.equals("protocoltest")) {
374
      String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
375
      try {
376
        testURL = ((String[])params.get("url"))[0];
377
      } catch (Throwable t) {
378
      }
379
      String phandler = System.getProperty("java.protocol.handler.pkgs");
380
      response.setContentType("text/html");
381
      PrintWriter out = response.getWriter();
382
      out.println("<body bgcolor=\"white\">");
383
      out.println("<p>Handler property: <code>" + phandler + "</code></p>");
384
      out.println("<p>Starting test for:<br>");
385
      out.println("    " + testURL + "</p>");
386
      try {
387
        URL u = new URL(testURL);
388
        out.println("<pre>");
389
        out.println("Protocol: " + u.getProtocol());
390
        out.println("    Host: " + u.getHost());
391
        out.println("    Port: " + u.getPort());
392
        out.println("    Path: " + u.getPath());
393
        out.println("     Ref: " + u.getRef());
394
        String pquery = u.getQuery();
395
        out.println("   Query: " + pquery);
396
        out.println("  Params: ");
397
        if (pquery != null) {
398
          Hashtable qparams = util.parseQuery(u.getQuery());
399
          for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
400
            String pname = (String)en.nextElement();
401
            String pvalue = (String)qparams.get(pname);
402
            out.println("    " + pname + ": " + pvalue);
403
          }
404
        }
405
        out.println("</pre>");
406
        out.println("</body>");
407
        out.close();
408
      } catch (MalformedURLException mue) {
409
        System.out.println("bad url from MetacatServlet.handleGetOrPost");
410
        out.println(mue.getMessage());
411
        mue.printStackTrace(out);
412
        out.close();
413
      }
414
    } else {
415
      PrintWriter out = response.getWriter();
416
      out.println("Error: action not registered.  Please report this error.");
417
    }
418
    util.closeConnections();
419
    // Close the stream to the client
420
    //out.close();
421
  }
422
  
423
  /**
424
   * decodes the mouse click information coming from the client.
425
   * This function may be overwritten to provide specific functionality
426
   * for different applications.
427
   * @param params the parameters from the CGI
428
   * @return action the action to be performed or "error" if an error was
429
   * generated
430
   */
431
  protected String decodeMouseAction(Hashtable params)
432
  {
433
    // Determine what type of request the user made
434
    // if the action parameter is set, use it as a default
435
    // but if the ypos param is set, calculate the action needed
436
    String action=null;
437
    long ypos = 0;
438
    try {
439
      ypos = (new Long(((String[])params.get("ypos"))[0]).longValue());
440
      //out.println("<P>YPOS IS " + ypos);
441
      if (ypos <= 13) {
442
        action = "read";
443
      } else if (ypos > 13 && ypos <= 27) {
444
        action = "validate";
445
      } else if (ypos > 27) {
446
        action = "transform";
447
      }
448
      return action;
449
    } catch (Exception npe) {
450
      //
451
      // MBJ -- NOTE that this should be handled more gracefully with
452
      //        the new exception infrastructure -- this "error" return
453
      //        value is inappropriate
454
      //out.println("<P>Caught exception looking for Y value.");
455
      return "error";
456
    }  
457
  }
458
  
459
  /**
460
   * sends the port number that the data socket is running on.  This is a 
461
   * parameter set in the metacat.properties file.
462
   */
463
  private void handleGetDataPortAction(PrintWriter out, Hashtable params, 
464
                                       HttpServletResponse response, 
465
                                       String username, String groupname,
466
                                       String sess_id)
467
  {
468
    int port;
469
    String filedir = null;
470
    try
471
    {
472
      filedir = util.getOption("datafilepath");
473
      
474
      Random r = new Random();
475
      port = r.nextInt(65000);  //pick a random port between 0-65000
476
      //System.out.println("random port is: " + port);
477
      while(!DataFileServer.portIsAvailable(port))
478
      {
479
        port = r.nextInt(65000);
480
        //System.out.println("next port used: " + port);
481
      }
482
      DataFileServer dfs = new DataFileServer(port, username, sess_id);
483
      dfs.start();
484
      
485
      //System.out.println("filedir: " + filedir);
486
      //System.out.println("port: " + port);
487
      response.setContentType("text/xml");
488
      out.println("<?xml version=\"1.0\"?>");
489
      out.println("<port>");
490
      out.print(port);
491
      out.print("</port>");
492
      
493
    }
494
	  catch (Exception e) 
495
    {
496
      System.out.println("error in MetacatServlet.handleGetDataPortAction: " + 
497
                          e.getMessage());
498
    }
499
  }
500

    
501
  /** 
502
   * Handle the login request. Create a new session object.
503
   * Do user authentication through the session.
504
   */
505
  private void handleLoginAction(PrintWriter out, Hashtable params, 
506
               HttpServletRequest request, HttpServletResponse response) {
507

    
508
    AuthSession sess = null;
509
    String un = ((String[])params.get("username"))[0];
510
    String pw = ((String[])params.get("password"))[0];
511
    String action = ((String[])params.get("action"))[0];
512
    String qformat = ((String[])params.get("qformat"))[0];
513
    
514
    try {
515
      sess = new AuthSession();
516
    } catch (Exception e) {
517
      System.out.println("error in MetacatServlet.handleLoginAction: " +
518
                          e.getMessage());
519
      out.println(e.getMessage());
520
      return;
521
    }
522
    
523
    boolean isValid = sess.authenticate(request, un, pw);
524

    
525
    // format and transform the output
526
    if (qformat.equals("html")) {
527
      Connection conn = null;
528
      try {
529
        conn = util.getConnection();
530
        DBTransform trans = new DBTransform(conn);
531
        response.setContentType("text/html");
532
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
533
                                   "-//W3C//HTML//EN", out);
534
        util.returnConnection(conn); 
535
      } catch(Exception e) {
536
        util.returnConnection(conn); 
537
      } 
538
      
539
    // any output is returned  
540
    } else {
541
      response.setContentType("text/xml");
542
      out.println(sess.getMessage()); 
543
    }
544
        
545
/* WITHOUT XSLT transformation
546
    // redirects response to html page
547
    if (qformat.equals("html")) {
548
      // user authentication successful
549
      if (isValid) {
550
        response.sendRedirect(
551
                 response.encodeRedirectUrl(htmlpath + "/metacat.html"));
552
      // unsuccessful user authentication 
553
      } else {
554
        response.sendRedirect(htmlpath + "/login.html");
555
      }
556
    // any output is returned  
557
    } else {
558
      response.setContentType("text/xml");
559
      out.println(sess.getMessage()); 
560
    }
561
*/        
562

    
563
  }    
564

    
565
  /** 
566
   * Handle the logout request. Close the connection.
567
   */
568
  private void handleLogoutAction(PrintWriter out, Hashtable params, 
569
               HttpServletRequest request, HttpServletResponse response) {
570

    
571
    String qformat = ((String[])params.get("qformat"))[0];
572

    
573
    // close the connection
574
    HttpSession sess = request.getSession(false);
575
    if (sess != null) { sess.invalidate();  }    
576

    
577
    // produce output
578
    StringBuffer output = new StringBuffer();
579
    output.append("<?xml version=\"1.0\"?>");
580
    output.append("<logout>");
581
    output.append("User logged out");
582
    output.append("</logout>");
583

    
584
    //format and transform the output
585
    if (qformat.equals("html")) {
586
      Connection conn = null;
587
      try {
588
        conn = util.getConnection();
589
        DBTransform trans = new DBTransform(conn);
590
        response.setContentType("text/html");
591
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN", 
592
                                   "-//W3C//HTML//EN", out);
593
        util.returnConnection(conn); 
594
      } catch(Exception e) {
595
        util.returnConnection(conn); 
596
      } 
597
    // any output is returned  
598
    } else {
599
      response.setContentType("text/xml");
600
      out.println(output.toString()); 
601
    }
602

    
603
/* WITHOUT XSLT transformation
604
    // redirects response to html page
605
    if (qformat.equals("html")) {
606
        response.sendRedirect(htmlpath + "/index.html"); 
607
      } catch(Exception e) {
608
        util.returnConnection(conn); 
609
      } 
610
    // any output is returned  
611
    } else {
612
      response.setContentType("text/xml");
613
      out.println(output.toString()); 
614
    }
615
*/
616
  }
617

    
618
  
619
  /**      
620
   * Retreive the squery xml, execute it and display it
621
   *
622
   * @param out the output stream to the client
623
   * @param params the Hashtable of parameters that should be included
624
   * in the squery.
625
   * @param response the response object linked to the client
626
   * @param conn the database connection 
627
   */
628
  protected void handleSQuery(PrintWriter out, Hashtable params, 
629
                 HttpServletResponse response, String user, String group)
630
  { 
631
    String xmlquery = ((String[])params.get("query"))[0];
632
    String qformat = ((String[])params.get("qformat"))[0];
633
    String resultdoc = null;
634
    String[] returndoc = null;
635
    if(params.contains("returndoc"))
636
    {
637
      returndoc = (String[])params.get("returndoc");
638
    }
639
    
640
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
641
    //String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
642

    
643
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
644
    
645
    //format and transform the results                                        
646
    if(qformat.equals("html")) {
647
      transformResultset(resultdoc, response, out);
648
    } else if(qformat.equals("xml")) {
649
      response.setContentType("text/xml");
650
      out.println(resultdoc);
651
    } else {
652
      out.println("invalid qformat: " + qformat); 
653
    }
654
  }
655
  
656
   /**
657
    * Create the xml query, execute it and display the results.
658
    *
659
    * @param out the output stream to the client
660
    * @param params the Hashtable of parameters that should be included
661
    * in the squery.
662
    * @param response the response object linked to the client
663
    */ 
664
  protected void handleQuery(PrintWriter out, Hashtable params, 
665
                 HttpServletResponse response, String user, String group)
666
  {
667
    //create the query and run it
668
    String[] returndoc = null;
669
    if(params.containsKey("returndoc"))
670
    {
671
      returndoc = (String[])params.get("returndoc");
672
    }
673
    String xmlquery = DBQuery.createSQuery(params);
674
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
675
    String qformat = ((String[])params.get("qformat"))[0];
676
    String resultdoc = null;
677
    
678
    resultdoc = createResultDocument(doclist, transformQuery(params));
679

    
680
    //format and transform the results                                        
681
    if(qformat.equals("html")) {
682
      transformResultset(resultdoc, response, out);
683
    } else if(qformat.equals("xml")) {
684
      response.setContentType("text/xml");
685
      out.println(resultdoc);
686
    } else { 
687
      out.println("invalid qformat: " + qformat); 
688
    }
689
  }
690
  
691
  /**
692
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
693
   * so it can properly be placed in the <query> tag of the resultset.
694
   * This method is overwritable so that other applications can customize
695
   * the structure of what is in the <query> tag.
696
   * 
697
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
698
   */
699
  protected String transformQuery(Hashtable params)
700
  {
701
    //DBQuery.createSQuery is a re-calling of a previously called 
702
    //function but it is necessary
703
    //so that overriding methods have access to the params hashtable
704
    String xmlquery = DBQuery.createSQuery(params);
705
    //the <?xml version="1.0"?> tag is the first 22 characters of the
706
    xmlquery = xmlquery.trim();
707
    int index = xmlquery.indexOf("?>");
708
    return xmlquery.substring(index + 2, xmlquery.length());
709
  }
710
  
711
  /**
712
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
713
   * string as a param instead of a hashtable.
714
   * 
715
   * @param xmlquery a string representing a query.
716
   */
717
  protected String transformQuery(String xmlquery)
718
  {
719
    xmlquery = xmlquery.trim();
720
    int index = xmlquery.indexOf("?>");
721
    return xmlquery.substring(index + 2, xmlquery.length());
722
  }
723
  
724
  /**
725
   * Run the query and return a hashtable of results.
726
   *
727
   * @param xmlquery the query to run
728
   */
729
  private Hashtable runQuery(String xmlquery, String user, String group, 
730
                             String[] returndoc)
731
  {
732
    Hashtable doclist=null;
733
    Connection conn = null;
734
    try
735
    {
736
      conn = util.getConnection();
737
      DBQuery queryobj = new DBQuery(conn, saxparser);
738
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
739
                                       returndoc);
740
      util.returnConnection(conn);
741
      return doclist;
742
    } 
743
    catch (Exception e) 
744
    {
745
      util.returnConnection(conn); 
746
      util.debugMessage("Error in MetacatServlet.runQuery: " + e.getMessage());
747
      doclist = null;
748
      return doclist;
749
    }    
750
  }
751
  
752
  /**
753
   * Transorms an xml resultset document to html and sends it to the browser
754
   *
755
   * @param resultdoc the string representation of the document that needs
756
   * to be transformed.
757
   * @param response the HttpServletResponse object bound to the client.
758
   * @param out the output stream to the client
759
   */ 
760
  protected void transformResultset(String resultdoc, 
761
                                    HttpServletResponse response,
762
                                    PrintWriter out)
763
  {
764
    Connection conn = null;
765
    try {
766
      conn = util.getConnection();
767
      DBTransform trans = new DBTransform(conn);
768
      response.setContentType("text/html");
769
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
770
                                 "-//W3C//HTML//EN", out);
771
      util.returnConnection(conn); 
772
    }
773
    catch(Exception e)
774
    {
775
      util.returnConnection(conn); 
776
    } 
777
  }
778
  
779
  /**
780
   * Transforms a hashtable of documents to an xml or html result.
781
   * If there is a returndoc, then it only displays documents of
782
   * whatever type returndoc represents.  If a result is found in a document
783
   * that is not of type returndoc then this attempts to find a relation 
784
   * between this document and one that satifies the returndoc doctype.
785
   *
786
   * @param doclist- the hashtable to transform
787
   * @param xmlquery- the query that returned the dolist result
788
   * @param resultdoc- the document type to backtrack to.
789
   */
790
  protected String createResultDocument(Hashtable doclist, String xmlquery)
791
  {
792
    // Create a buffer to hold the xml result
793
    StringBuffer resultset = new StringBuffer();
794
 
795
    // Print the resulting root nodes 
796
    String docid = null;
797
    String document = null;
798
    resultset.append("<?xml version=\"1.0\"?>\n");
799
    resultset.append("<resultset>\n");
800
      
801
    resultset.append("  <query>" + xmlquery + "</query>");   
802

    
803
    if(doclist != null)
804
    {
805
      Enumeration doclistkeys = doclist.keys(); 
806
      while (doclistkeys.hasMoreElements()) 
807
      {
808
        docid = (String)doclistkeys.nextElement();
809
        document = (String)doclist.get(docid);
810
        resultset.append("  <document>" + document + "</document>");
811
      }
812
    }
813

    
814
    resultset.append("</resultset>");
815
    //System.out.println(resultset.toString());
816
    return resultset.toString();
817
  }
818
  
819
  /**
820
   * Handle the request to view the abstract of a document.
821
   * The abstractpath CGI parameter gives the xml path to the abstract
822
   * node.  
823
   */
824
  private void handleViewAbstractAction(PrintWriter out, Hashtable params,
825
               HttpServletResponse response) throws IOException, SQLException
826
  {
827
    String abstractpath = null;
828
    String docid = null;
829
    Connection conn = null;
830
    response.setContentType("text/html");
831
    try
832
    {
833
      docid = ((String[])params.get("docid"))[0];
834
      if(params.containsKey("abstractpath"))
835
      {
836
        //the CGI parameter abstractpath holds the path to the abstract
837
        //that should be displayed.
838
        abstractpath = ((String[])params.get("abstractpath"))[0];
839
      }
840
      else
841
      {
842
        out.println("error: no abstractpath parameter"); 
843
      }
844
      conn = util.getConnection();
845
    
846
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
847
    
848
      out.println("<html><head><title>Abstract</title></head>");
849
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
850
      for(int i=0; i<abstracts.length; i++)
851
      {
852
        out.println("<p>" + (String)abstracts[i] + "</p>");
853
      }
854
      out.println("</body></html>");
855
    }
856
    catch (IOException ioe)
857
    {
858
       util.debugMessage("error in MetacatServlet.handlegetabstract: " + 
859
                          ioe.getMessage());
860
       System.out.println("IO error in MetacatServlet.handlegetabstract: " + 
861
                          ioe.getMessage());
862
    }
863
    catch(SQLException sqle)
864
    {
865
      util.debugMessage("sql error in MetacatServLet.handlegetabstract: " + 
866
                         sqle.getMessage());
867
      System.out.println("sql error in MetacatServLet.handlegetabstract: " + 
868
                         sqle.getMessage());
869
    }
870
    catch(Exception e)
871
    {
872
      util.debugMessage("error in handlegetabstract: " + e.getMessage());
873
      System.out.println("error in MetacatServlEt.handlegetabstract: " + 
874
                         e.getMessage());
875
    }
876
    
877
    util.returnConnection(conn);
878
  }
879

    
880
  /** 
881
   * Handle the database getrelateddocument request and return a XML document, 
882
   * possibly transformed from XML into HTML
883
   */
884
  private void handleGetRelatedDocumentAction(PrintWriter out, Hashtable params,
885
               HttpServletResponse response, URL murl) 
886
               throws ClassNotFoundException, IOException, SQLException 
887
  {
888
    String docid = null;
889
    Connection conn = null;
890
      
891
    //if(params.containsKey("url"))
892
    //{//the identifier for the related document is contained in the URL param
893
      try
894
      {
895
        DocumentImpl xmldoc=null;
896
        //MetacatURL murl = new MetacatURL(((String[])params.get("url"))[0]);
897
        if(murl.getProtocol().equals("metacat"))
898
        {//get the document from the database if it is the right type of url
899
          //Hashtable murlParams = murl.getHashParams();
900
          Hashtable murlParams = util.parseQuery(murl.getQuery());
901
          if(murlParams.containsKey("docid"))
902
          {//the docid should be first
903
            docid = (String)murlParams.get("docid"); //get the docid value
904
            conn = util.getConnection();
905
            xmldoc = new DocumentImpl(conn, docid);
906
            String qformat = ((String[])params.get("qformat"))[0];
907
            if (qformat.equals("xml")) 
908
            { 
909
              // set content type and other response header fields first
910
              response.setContentType("text/xml");
911
              xmldoc.toXml(out);
912
              //out.println(xmldoc);
913
            } 
914
            else if (qformat.equals("html")) 
915
            {
916
              response.setContentType("text/html");
917
              // Look up the document type
918
              String sourcetype = xmldoc.getDoctype();
919
              // Transform the document to the new doctype
920
              DBTransform dbt = new DBTransform(conn);
921
              dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
922
                                 "-//W3C//HTML//EN", out);
923
            }
924

    
925
            util.returnConnection(conn);
926
          }
927
          else
928
          {
929
            //throw new Exception("handleGetDocument: bad URL");
930
            System.err.println("handleGetDocument: bad URL");
931
          }
932
        }
933
        else if(murl.getProtocol().equals("http"))
934
        {//get the document from the internet
935
          //Hashtable murlParams = murl.getHashParams();
936
          Hashtable murlParams = util.parseQuery(murl.getQuery());
937
          if(murlParams.containsKey("httpurl"))
938
          {//httpurl is the param name for an http url.
939
            URL urlconn = new URL((String)murlParams.get("httpurl"));  
940
            //create a new url obj.
941
            //DataInputStream htmldoc = new DataInputStream(urlconn.openStream());
942
            BufferedReader htmldoc = new BufferedReader(
943
                                   new InputStreamReader(urlconn.openStream()));
944
            //bind a data stream.
945
            try
946
            { //display the document
947
              String line=null;
948
              while((line = htmldoc.readLine()) != null)
949
              {
950
                out.println(line); 
951
              }
952
            }
953
            catch(Exception e)
954
            {
955
              System.out.println("error viewing html document from " +
956
                            "MetacatServlet.handleGetRelatedDocumentAction: " +
957
                            e.getMessage()); 
958
            }
959
          }
960
        }
961
      }
962
      catch (McdbException e) {
963
        response.setContentType("text/xml");
964
        e.toXml(out);
965
      } catch   (Throwable t) {
966
        response.setContentType("text/html");
967
        out.println(t.getMessage());
968
      } finally {
969
        util.returnConnection(conn);
970
      }
971
    //} // end if
972
  }   
973
  
974
  /** 
975
   * Handle the database read request and return an XML document, 
976
   * possibly transformed from XML into HTML
977
   */
978
  private void handleReadAction(/*PrintWriter out,*/ Hashtable params, 
979
               HttpServletResponse response, String username) 
980
               throws ClassNotFoundException, IOException, SQLException 
981
  {
982
     PrintWriter out;
983
    try {
984
      //MetacatURL murl = new MetacatURL(((String[])params.get("docid"))[0]);
985
      if(params.containsKey(new String("qformat")) && 
986
         ((String[])params.get("qformat"))[0].equals("bin"))
987
      {
988
        handleGetData(params, response, username);
989
      }
990
      else
991
      {
992
        out = response.getWriter();
993
        URL murl = new URL(((String[])params.get("docid"))[0]);
994
        handleGetRelatedDocumentAction(out, params, response, murl);
995
      }
996
    } catch (MalformedURLException mue) {
997
      out = response.getWriter();
998
      handleGetDocumentAction(out, params, response);
999
    }
1000
  }
1001
  
1002
  /**
1003
   * Handle the read of a data file.
1004
   */
1005
  private void handleGetData(Hashtable params, 
1006
                             HttpServletResponse response, String username)
1007
  {
1008
    String docid = null;
1009
    try
1010
    {
1011
      URL murl = new URL(((String[])params.get("docid"))[0]);
1012
      Hashtable murlParams = util.parseQuery(murl.getQuery());
1013
      if(murlParams.containsKey("docid"))
1014
      {
1015
        docid = (String)murlParams.get("docid");
1016
      }
1017
    }
1018
    catch(MalformedURLException mue)
1019
    {
1020
      docid = ((String[])params.get("docid"))[0];
1021
    }
1022
    
1023
    File f = null;
1024
    FileInputStream fin = null;
1025
    Connection conn;
1026
    
1027
    try
1028
    {
1029
      StringBuffer sql = new StringBuffer();
1030
      sql.append("select docname from xml_documents where docid like '");
1031
      sql.append(docid).append("'");
1032
      conn = util.openDBConnection();
1033
      
1034
      AccessControlList aclobj = new AccessControlList(conn);
1035
      boolean hasPermission = aclobj.hasPermission("READ",username,docid);
1036
      
1037
      if(!hasPermission)
1038
      {
1039
        response.setContentType("text/html");
1040
        PrintWriter out = response.getWriter();
1041
        out.println("Error: you do not have permission to view this document");
1042
        return;
1043
      }
1044
      response.setContentType("application/octet-stream");
1045
      ServletOutputStream sosout = response.getOutputStream(); 
1046
      PreparedStatement pstmt = conn.prepareStatement(sql.toString());
1047
      pstmt.execute();
1048
      ResultSet rs = pstmt.getResultSet();
1049
      boolean tablehasrows = rs.next();
1050
      while(tablehasrows)
1051
      {
1052
        //get the file stream from the file then send it to the output stream
1053
        String filepath = util.getOption("datafilepath");
1054
        if(!filepath.endsWith("/"))
1055
        {
1056
          filepath += "/";
1057
        }
1058
        f = new File(filepath + rs.getString(1)); 
1059
        fin = new FileInputStream(f);
1060
        
1061
        int b = fin.read();
1062
        while(b != -1)
1063
        {
1064
          sosout.write(b);
1065
          b = fin.read();
1066
        }
1067
        tablehasrows = rs.next();
1068
      }
1069
      
1070
      fin.close();
1071
      pstmt.close();
1072
      conn.close();
1073
    }
1074
    catch(Exception e)
1075
    {
1076
      System.out.println("error in MetacatServlet.handleGetData: " + 
1077
                          e.getMessage());
1078
      e.printStackTrace(System.out);
1079
    }
1080
  }
1081

    
1082
  /** 
1083
   * Handle the database read request and return an XML document, 
1084
   * possibly transformed from XML into HTML
1085
   */
1086
  private void handleGetDocumentAction(PrintWriter out, Hashtable params, 
1087
               HttpServletResponse response) 
1088
               throws ClassNotFoundException, IOException, SQLException {
1089
    String docidstr = null;
1090
    String docid = null;
1091
    String doc = null;
1092
    Connection conn = null;
1093
    
1094
    try {
1095
      // Find the document id number
1096
      docidstr = ((String[])params.get("docid"))[0]; 
1097
      docid = docidstr;
1098
      
1099
      conn = util.getConnection();
1100
      DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1101
      // Get the document indicated from the db
1102
      //doc = docreader.readXMLDocument(docid);
1103

    
1104
      // Return the document in XML or HTML format
1105
      String qformat=null;
1106
      if(params.containsKey("qformat"))
1107
      {
1108
        qformat = ((String[])params.get("qformat"))[0];
1109
      }
1110
      else
1111
      {
1112
        qformat = "html";        
1113
      }
1114
      if (qformat.equals("xml")) { 
1115
        // set content type and other response header fields first
1116
        response.setContentType("text/xml");
1117
        xmldoc.toXml(out);
1118
        //out.println(xmldoc);
1119
      } else if (qformat.equals("html")) {
1120
        response.setContentType("text/html");
1121
        // Look up the document type
1122
        String sourcetype = xmldoc.getDoctype();
1123
        // Transform the document to the new doctype
1124
        DBTransform dbt = new DBTransform(conn);
1125
        dbt.transformXMLDocument(xmldoc.toString(), sourcetype, 
1126
                                 "-//W3C//HTML//EN", out);
1127
      }
1128
    } catch (McdbException e) {
1129
      response.setContentType("text/xml");
1130
      e.toXml(out);
1131
    } catch (Throwable t) {
1132
      response.setContentType("text/html");
1133
      out.println(t.getMessage());
1134
    } finally {
1135
      util.returnConnection(conn);
1136
    }    
1137

    
1138
  }
1139

    
1140
  /** 
1141
   * Handle the database putdocument request and write an XML document 
1142
   * to the database connection
1143
   */
1144
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
1145
               HttpServletResponse response, String user, String group) {
1146

    
1147
    Connection conn = null;
1148

    
1149
    try {
1150
      // Get the document indicated
1151
      String[] doctext = (String[])params.get("doctext");
1152

    
1153
      String pub = null;
1154
      if (params.containsKey("public")) {
1155
        pub = ((String[])params.get("public"))[0];
1156
      }
1157

    
1158
      StringReader dtd = null;
1159
      if (params.containsKey("dtdtext")) {
1160
        String[] dtdtext = (String[])params.get("dtdtext");
1161
        try {
1162
          if ( !dtdtext[0].equals("") ) {
1163
            dtd = new StringReader(dtdtext[0]);
1164
          }
1165
        } catch (NullPointerException npe) {}
1166
      }
1167
      
1168
      StringReader xml = null;
1169
      try {
1170
        xml = new StringReader(doctext[0]);
1171

    
1172
        String[] action = (String[])params.get("action");
1173
        String[] docid = (String[])params.get("docid");
1174
        String newdocid = null;
1175

    
1176
        String doAction = null;
1177
        if (action[0].equals("insert")) {
1178
          doAction = "INSERT";
1179
        } else if (action[0].equals("update")) {
1180
          doAction = "UPDATE";
1181
        }
1182

    
1183
        try {
1184
          // get a connection from the pool
1185
          conn = util.getConnection();
1186

    
1187
          // write the document to the database
1188
          try {
1189
            String accNumber = docid[0];
1190
            if (accNumber.equals("")) {
1191
              accNumber = null;
1192
            }
1193
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1194
                                          accNumber, user, group);
1195
          } catch (NullPointerException npe) {
1196
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1197
                                          null, user, group);
1198
          }
1199
        } finally {
1200
          util.returnConnection(conn);
1201
        }    
1202

    
1203
        // set content type and other response header fields first
1204
        response.setContentType("text/xml");
1205
        out.println("<?xml version=\"1.0\"?>");
1206
        out.println("<success>");
1207
        out.println("<docid>" + newdocid + "</docid>"); 
1208
        out.println("</success>");
1209

    
1210
      } catch (NullPointerException npe) {
1211
        response.setContentType("text/xml");
1212
        out.println("<?xml version=\"1.0\"?>");
1213
        out.println("<error>");
1214
        out.println(npe.getMessage()); 
1215
        out.println("</error>");
1216
      }
1217
    } catch (Exception e) {
1218
      response.setContentType("text/xml");
1219
      out.println("<?xml version=\"1.0\"?>");
1220
      out.println("<error>");
1221
      out.println(e.getMessage()); 
1222
      if (e instanceof SAXException) {
1223
        Exception e2 = ((SAXException)e).getException();
1224
        out.println("<error>");
1225
        out.println(e2.getMessage()); 
1226
        out.println("</error>");
1227
      }
1228
      //e.printStackTrace(out);
1229
      out.println("</error>");
1230
    }
1231
  }
1232

    
1233
  /** 
1234
   * Handle the database delete request and delete an XML document 
1235
   * from the database connection
1236
   */
1237
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1238
               HttpServletResponse response, String user, String group) {
1239

    
1240
    String[] docid = (String[])params.get("docid");
1241
    Connection conn = null;
1242

    
1243
    // delete the document from the database
1244
    try {
1245
      // get a connection from the pool
1246
      conn = util.getConnection();
1247
                                      // NOTE -- NEED TO TEST HERE
1248
                                      // FOR EXISTENCE OF DOCID PARAM
1249
                                      // BEFORE ACCESSING ARRAY
1250
      try { 
1251
        DocumentImpl.delete(conn, docid[0], user, group);
1252
        response.setContentType("text/xml");
1253
        out.println("<?xml version=\"1.0\"?>");
1254
        out.println("<success>");
1255
        out.println("Document deleted."); 
1256
        out.println("</success>");
1257
      } catch (AccessionNumberException ane) {
1258
        response.setContentType("text/xml");
1259
        out.println("<?xml version=\"1.0\"?>");
1260
        out.println("<error>");
1261
        out.println("Error deleting document!!!");
1262
        out.println(ane.getMessage()); 
1263
        out.println("</error>");
1264
      }
1265
    } catch (Exception e) {
1266
      response.setContentType("text/xml");
1267
      out.println("<?xml version=\"1.0\"?>");
1268
      out.println("<error>");
1269
      out.println(e.getMessage()); 
1270
      out.println("</error>");
1271
    } finally {
1272
      util.returnConnection(conn);
1273
    }  
1274
  }
1275
  
1276
  /** 
1277
   * Handle the validation request and return the results to the requestor
1278
   */
1279
  private void handleValidateAction(PrintWriter out, Hashtable params, 
1280
               HttpServletResponse response) {
1281

    
1282
    // Get the document indicated
1283
    String valtext = null;
1284
    
1285
    try {
1286
      valtext = ((String[])params.get("valtext"))[0];
1287
    } catch (Exception nullpe) {
1288

    
1289
      Connection conn = null;
1290
      String docid = null;
1291
      try {
1292
        // Find the document id number
1293
        docid = ((String[])params.get("docid"))[0]; 
1294

    
1295
        // get a connection from the pool
1296
        conn = util.getConnection();
1297

    
1298
        // Get the document indicated from the db
1299
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1300
        valtext = xmldoc.toString();
1301

    
1302
      } catch (NullPointerException npe) {
1303
        response.setContentType("text/xml");
1304
        out.println("<error>Error getting document ID: " + docid + "</error>");
1305
        if ( conn != null ) { util.returnConnection(conn); }
1306
        return;
1307
      } catch (Exception e) {
1308
        response.setContentType("text/html");
1309
        out.println(e.getMessage()); 
1310
      } finally {
1311
        util.returnConnection(conn);
1312
      }  
1313
    }
1314

    
1315
    Connection conn = null;
1316
    try {
1317
      // get a connection from the pool
1318
      conn = util.getConnection();
1319
      DBValidate valobj = new DBValidate(saxparser,conn);
1320
      boolean valid = valobj.validateString(valtext);
1321

    
1322
      // set content type and other response header fields first
1323
      response.setContentType("text/xml");
1324
      out.println(valobj.returnErrors());
1325

    
1326
    } catch (NullPointerException npe2) {
1327
      // set content type and other response header fields first
1328
      response.setContentType("text/xml");
1329
      out.println("<error>Error validating document.</error>"); 
1330
    } catch (Exception e) {
1331
      response.setContentType("text/html");
1332
      out.println(e.getMessage()); 
1333
    } finally {
1334
      util.returnConnection(conn);
1335
    }  
1336
  }
1337

    
1338
  /** 
1339
   * Handle the document request and return the results to the requestor
1340
   * If a docid is passed in through the params then that document
1341
   * will be retrieved form the DB and put in the zip file.
1342
   * In addition if 1 or more relations parameters are passed, those file
1343
   * will be zipped as well.  Currently this is only implemented for 
1344
   * metacat:// and http:// files.  Support should be added for srb:// files
1345
   * as well.
1346
   */
1347
  private void handleGetDataDocumentAction(ServletOutputStream out, 
1348
               Hashtable params, 
1349
               HttpServletResponse response) {
1350
  //find the related files, get them from their source and zip them into 
1351
  //a zip file.
1352
  try
1353
  {
1354
    Connection conn = util.getConnection();
1355
    String currentDocid = ((String[])params.get("docid"))[0];
1356
    ZipOutputStream zout = new ZipOutputStream(out);
1357
    byte[] bytestring = null;
1358
    ZipEntry zentry = null;
1359
    DocumentImpl xmldoc = null;
1360
    String[] reldocs = null;
1361
    
1362
    if(params.containsKey("relation"))
1363
    { //get the relations from the parameters.
1364
      reldocs = ((String[])params.get("relation"));
1365
    }
1366
    else
1367
    { //let the for loop know that there are no relations to zip
1368
      reldocs = new String[0];
1369
    }
1370

    
1371
    //write the base file to the zip file.
1372
    xmldoc = new DocumentImpl(conn, currentDocid);
1373
    bytestring = (xmldoc.toString()).getBytes();
1374
    zentry = new ZipEntry(currentDocid + ".xml");
1375
    //create a new zip entry and write the file to the stream
1376
    zentry.setSize(bytestring.length);
1377
    zout.putNextEntry(zentry);
1378
    zout.write(bytestring, 0, bytestring.length);
1379
    zout.closeEntry(); //get ready for the next entry. 
1380

    
1381
    //zip up the related documents
1382
    for(int i=0; i<reldocs.length; i++)
1383
    {
1384
      //MetacatURL murl = new MetacatURL(((String)reldocs[i]));
1385
      URL murl = new URL(((String)reldocs[i]));
1386
      Hashtable qparams = util.parseQuery(murl.getQuery());
1387
      if(murl.getProtocol().equals("metacat"))
1388
      {
1389
        //get the document from the database
1390
        //xmldoc = new DocumentImpl(conn, (String)murl.getHashParam("docid"));
1391
        xmldoc = new DocumentImpl(conn, (String)qparams.get("docid"));
1392
        bytestring = (xmldoc.toString()).getBytes();
1393
        zentry = new ZipEntry(qparams.get("docid") + ".xml");
1394
        //create a new zip entry and write the file to the stream
1395
        zentry.setSize(bytestring.length);
1396
        zout.putNextEntry(zentry);
1397
        zout.write(bytestring, 0, bytestring.length);
1398
        zout.closeEntry(); //get ready for the next entry.
1399
      }
1400
      else if(murl.getProtocol().equals("http"))
1401
      {
1402
        //Hashtable murlParams = murl.getHashParams();
1403
        if(qparams.containsKey("httpurl"))
1404
        {//httpurl is the param name for an http url.
1405
          URL urlconn = new URL((String)qparams.get("httpurl"));  
1406
          //create a new url obj.
1407
          BufferedReader htmldoc = new BufferedReader(
1408
                                   new InputStreamReader(urlconn.openStream()));
1409
          //get the data from the web server
1410
          try
1411
          { //zip the document
1412
            String line=null;
1413
            zentry = new ZipEntry((String)qparams.get("filename"));
1414
            //get just the filename from the URL.
1415
            zout.putNextEntry(zentry);
1416
            //make a new entry in the zip file stream
1417
            while((line = htmldoc.readLine()) != null)
1418
            {
1419
              bytestring = (line.toString()).getBytes();
1420
              zout.write(bytestring, 0, bytestring.length);
1421
              //write out the file line by line
1422
            }
1423
            zout.closeEntry(); //close the entry in the file
1424
          }
1425
          catch(Exception e)
1426
          {
1427
            System.out.println("error downloading html document "+ 
1428
                               "in metacatServlet.handleGetDataDocumentAction"); 
1429
          }
1430
        }
1431
      }
1432
    }
1433
    zout.finish();  //terminate the zip file
1434
    zout.close();   //close the stream.
1435
    util.returnConnection(conn); //return the connection to the pool
1436
  }
1437
  catch(Exception e)
1438
  {
1439
    System.out.println("Error creating zip file from " +
1440
                       "MetacatServlet.handleGetDataDocumentAction: " + 
1441
                        e.getMessage()); 
1442
    e.printStackTrace(System.out);
1443
  }
1444
           
1445
   /*
1446
   //////////old code using a shell script/////////////////////////////////
1447
   
1448
      boolean error_flag = false;
1449
      String error_message = "";
1450
      // Get the document indicated
1451
      String[] datadoc = (String[])params.get("datadoc");
1452
      // defaultdatapath = "C:\\Temp\\";    // for testing only!!!
1453
      // executescript = "test.bat";        // for testing only!!!
1454
      
1455
      // set content type and other response header fields first
1456
      response.setContentType("application/octet-stream");
1457
      if (defaultdatapath!=null) {
1458
        if(!defaultdatapath.endsWith(System.getProperty("file.separator"))) {
1459
          defaultdatapath=defaultdatapath+System.getProperty("file.separator");
1460
        }
1461
        System.out.println("Path= "+defaultdatapath+datadoc[0]);
1462
        if (executescript!=null) {
1463
          String command = null;
1464
          File scriptfile = new File(executescript);
1465
          if (scriptfile.exists()) {
1466
            command=executescript+" "+datadoc[0]; // script includes path
1467
        } else {     // look in defaultdatapath
1468
            // on Win98 one MUST include the .bat extender
1469
            command = defaultdatapath+executescript+" "+datadoc[0];  
1470
        }
1471
      System.out.println(command);
1472
      try {
1473
      Process proc = Runtime.getRuntime().exec(command);
1474
      proc.waitFor();
1475
      }
1476
      catch (Exception eee) {
1477
        System.out.println("Error running process!");
1478
        error_flag = true;
1479
        error_message = "Error running process!";}
1480
      } // end executescript not null if
1481
      File datafile = new File(defaultdatapath+datadoc[0]);
1482
      try {
1483
      FileInputStream fw = new FileInputStream(datafile);
1484
      int x;
1485
      while ((x = fw.read())!=-1) {
1486
        out.write(x); }
1487
        fw.close();
1488
      } catch (Exception e) {
1489
        System.out.println("Error in returning file\n"+e.getMessage());
1490
        error_flag=true;
1491
        error_message = error_message+"\nError in returning file\n"+
1492
                        e.getMessage();
1493
      }
1494
    } // end defaultdatapath not null if
1495
    */
1496
  }
1497
  
1498
  /** 
1499
   * Handle the getdoctypes Action.
1500
   * Read all doctypes from db connection in XML format
1501
   */
1502
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1503
                                       HttpServletResponse response) {
1504

    
1505
    Connection conn = null;
1506
    
1507
    try {
1508

    
1509
        // get connection from the pool
1510
        conn = util.getConnection();
1511
        DBUtil dbutil = new DBUtil(conn);
1512
        String doctypes = dbutil.readDoctypes();
1513
        out.println(doctypes);
1514

    
1515
    } catch (Exception e) {
1516
      out.println("<?xml version=\"1.0\"?>");
1517
      out.println("<error>");
1518
      out.println(e.getMessage());
1519
      out.println("</error>");
1520
    } finally {
1521
      util.returnConnection(conn);
1522
    }  
1523
    
1524
  }
1525

    
1526
  /** 
1527
   * Handle the getdataguide Action.
1528
   * Read Data Guide for a given doctype from db connection in XML format
1529
   */
1530
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1531
                                        HttpServletResponse response) {
1532

    
1533
    Connection conn = null;
1534
    String doctype = null;
1535
    String[] doctypeArr = (String[])params.get("doctype");
1536

    
1537
    // get only the first doctype specified in the list of doctypes
1538
    // it could be done for all doctypes in that list
1539
    if (doctypeArr != null) {
1540
        doctype = ((String[])params.get("doctype"))[0]; 
1541
    }
1542

    
1543
    try {
1544

    
1545
        // get connection from the pool
1546
        conn = util.getConnection();
1547
        DBUtil dbutil = new DBUtil(conn);
1548
        String dataguide = dbutil.readDataGuide(doctype);
1549
        out.println(dataguide);
1550

    
1551
    } catch (Exception e) {
1552
      out.println("<?xml version=\"1.0\"?>");
1553
      out.println("<error>");
1554
      out.println(e.getMessage());
1555
      out.println("</error>");
1556
    } finally {
1557
      util.returnConnection(conn);
1558
    }  
1559
    
1560
  }
1561

    
1562
}
(32-32/43)