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: 2001-01-18 15:15:21 -0800 (Thu, 18 Jan 2001) $'
11
 * '$Revision: 675 $'
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
      StringReader acl = null;
1154
      if(params.containsKey("acltext"))
1155
      {
1156
        String[] acltext = (String[])params.get("acltext");
1157
        try {
1158
          if ( !acltext[0].equals("") ) {
1159
            acl = new StringReader(acltext[0]);
1160
          }
1161
        } catch (NullPointerException npe) {}
1162
      }
1163
      StringReader dtd = null;
1164
      if(params.containsKey("dtdtext"))
1165
      {
1166
        String[] dtdtext = (String[])params.get("dtdtext");
1167
        try {
1168
          if ( !dtdtext[0].equals("") ) {
1169
            dtd = new StringReader(dtdtext[0]);
1170
          }
1171
        } catch (NullPointerException npe) {}
1172
      }
1173
      
1174
      StringReader xml = null;
1175
      try {
1176
        xml = new StringReader(doctext[0]);
1177

    
1178
        String[] action = (String[])params.get("action");
1179
        String[] docid = (String[])params.get("docid");
1180
        String newdocid = null;
1181

    
1182
        String doAction = null;
1183
        if (action[0].equals("insert")) {
1184
          doAction = "INSERT";
1185
        } else if (action[0].equals("update")) {
1186
          doAction = "UPDATE";
1187
        }
1188

    
1189
        try {
1190
            // get a connection from the pool
1191
            conn = util.getConnection();
1192

    
1193
            // write the document to the database
1194
            try {
1195
                String accNumber = docid[0];
1196
                if (accNumber.equals("")) {
1197
                    accNumber = null;
1198
                }
1199
                newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1200
                                              accNumber, user, group);
1201
                
1202
            } catch (NullPointerException npe) {
1203
              newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1204
                                            null, user, group);
1205
            }
1206
//        } catch (Exception e) {
1207
//          response.setContentType("text/html");
1208
//          out.println(e.getMessage());
1209
        } finally {
1210
          util.returnConnection(conn);
1211
        }    
1212

    
1213
        // set content type and other response header fields first
1214
        response.setContentType("text/xml");
1215
        out.println("<?xml version=\"1.0\"?>");
1216
        out.println("<success>");
1217
        out.println("<docid>" + newdocid + "</docid>"); 
1218
        out.println("</success>");
1219

    
1220
      } catch (NullPointerException npe) {
1221
        response.setContentType("text/xml");
1222
        out.println("<?xml version=\"1.0\"?>");
1223
        out.println("<error>");
1224
        out.println(npe.getMessage()); 
1225
        out.println("</error>");
1226
      }
1227
    } catch (Exception e) {
1228
      response.setContentType("text/xml");
1229
      out.println("<?xml version=\"1.0\"?>");
1230
      out.println("<error>");
1231
      out.println(e.getMessage()); 
1232
      if (e instanceof SAXException) {
1233
        Exception e2 = ((SAXException)e).getException();
1234
        out.println("<error>");
1235
        out.println(e2.getMessage()); 
1236
        out.println("</error>");
1237
      }
1238
      //e.printStackTrace(out);
1239
      out.println("</error>");
1240
    }
1241
  }
1242

    
1243
  /** 
1244
   * Handle the database delete request and delete an XML document 
1245
   * from the database connection
1246
   */
1247
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1248
               HttpServletResponse response, String user, String group) {
1249

    
1250
    String[] docid = (String[])params.get("docid");
1251
    Connection conn = null;
1252

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

    
1292
    // Get the document indicated
1293
    String valtext = null;
1294
    
1295
    try {
1296
      valtext = ((String[])params.get("valtext"))[0];
1297
    } catch (Exception nullpe) {
1298

    
1299
      Connection conn = null;
1300
      String docid = null;
1301
      try {
1302
        // Find the document id number
1303
        docid = ((String[])params.get("docid"))[0]; 
1304

    
1305
        // get a connection from the pool
1306
        conn = util.getConnection();
1307

    
1308
        // Get the document indicated from the db
1309
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1310
        valtext = xmldoc.toString();
1311

    
1312
      } catch (NullPointerException npe) {
1313
        response.setContentType("text/xml");
1314
        out.println("<error>Error getting document ID: " + docid + "</error>");
1315
        if ( conn != null ) { util.returnConnection(conn); }
1316
        return;
1317
      } catch (Exception e) {
1318
        response.setContentType("text/html");
1319
        out.println(e.getMessage()); 
1320
      } finally {
1321
        util.returnConnection(conn);
1322
      }  
1323
    }
1324

    
1325
    Connection conn = null;
1326
    try {
1327
      // get a connection from the pool
1328
      conn = util.getConnection();
1329
      DBValidate valobj = new DBValidate(saxparser,conn);
1330
      boolean valid = valobj.validateString(valtext);
1331

    
1332
      // set content type and other response header fields first
1333
      response.setContentType("text/xml");
1334
      out.println(valobj.returnErrors());
1335

    
1336
    } catch (NullPointerException npe2) {
1337
      // set content type and other response header fields first
1338
      response.setContentType("text/xml");
1339
      out.println("<error>Error validating document.</error>"); 
1340
    } catch (Exception e) {
1341
      response.setContentType("text/html");
1342
      out.println(e.getMessage()); 
1343
    } finally {
1344
      util.returnConnection(conn);
1345
    }  
1346
  }
1347

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

    
1381
    //write the base file to the zip file.
1382
    xmldoc = new DocumentImpl(conn, currentDocid);
1383
    bytestring = (xmldoc.toString()).getBytes();
1384
    zentry = new ZipEntry(currentDocid + ".xml");
1385
    //create a new zip entry and write the file to the stream
1386
    zentry.setSize(bytestring.length);
1387
    zout.putNextEntry(zentry);
1388
    zout.write(bytestring, 0, bytestring.length);
1389
    zout.closeEntry(); //get ready for the next entry. 
1390

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

    
1515
    Connection conn = null;
1516
    
1517
    try {
1518

    
1519
        // get connection from the pool
1520
        conn = util.getConnection();
1521
        DBUtil dbutil = new DBUtil(conn);
1522
        String doctypes = dbutil.readDoctypes();
1523
        out.println(doctypes);
1524

    
1525
    } catch (Exception e) {
1526
      out.println("<?xml version=\"1.0\"?>");
1527
      out.println("<error>");
1528
      out.println(e.getMessage());
1529
      out.println("</error>");
1530
    } finally {
1531
      util.returnConnection(conn);
1532
    }  
1533
    
1534
  }
1535

    
1536
  /** 
1537
   * Handle the getdataguide Action.
1538
   * Read Data Guide for a given doctype from db connection in XML format
1539
   */
1540
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1541
                                        HttpServletResponse response) {
1542

    
1543
    Connection conn = null;
1544
    String doctype = null;
1545
    String[] doctypeArr = (String[])params.get("doctype");
1546

    
1547
    // get only the first doctype specified in the list of doctypes
1548
    // it could be done for all doctypes in that list
1549
    if (doctypeArr != null) {
1550
        doctype = ((String[])params.get("doctype"))[0]; 
1551
    }
1552

    
1553
    try {
1554

    
1555
        // get connection from the pool
1556
        conn = util.getConnection();
1557
        DBUtil dbutil = new DBUtil(conn);
1558
        String dataguide = dbutil.readDataGuide(doctype);
1559
        out.println(dataguide);
1560

    
1561
    } catch (Exception e) {
1562
      out.println("<?xml version=\"1.0\"?>");
1563
      out.println("<error>");
1564
      out.println(e.getMessage());
1565
      out.println("</error>");
1566
    } finally {
1567
      util.returnConnection(conn);
1568
    }  
1569
    
1570
  }
1571

    
1572
}
(32-32/43)