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: jones $'
10
 *     '$Date: 2001-05-22 15:24:53 -0700 (Tue, 22 May 2001) $'
11
 * '$Revision: 745 $'
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.File;
31
import java.io.PrintWriter;
32
import java.io.IOException;
33
import java.io.StringReader;
34
import java.io.FileInputStream;
35
import java.io.BufferedInputStream;
36
import java.util.Enumeration;
37
import java.util.Hashtable;
38
import java.util.ResourceBundle; 
39
import java.util.Random;
40
import java.util.PropertyResourceBundle;
41
import java.net.URL;
42
import java.net.MalformedURLException;
43
import java.sql.PreparedStatement;
44
import java.sql.ResultSet;
45
import java.sql.Connection;
46
import java.sql.SQLException;
47
import java.lang.reflect.*;
48
import java.net.*;
49
import java.util.zip.*;
50

    
51
import javax.servlet.ServletConfig;
52
import javax.servlet.ServletContext;
53
import javax.servlet.ServletException;
54
import javax.servlet.ServletInputStream;
55
import javax.servlet.http.HttpServlet;
56
import javax.servlet.http.HttpServletRequest;
57
import javax.servlet.http.HttpServletResponse;
58
import javax.servlet.http.HttpSession;
59
import javax.servlet.http.HttpUtils;
60
import javax.servlet.ServletOutputStream;
61

    
62
import oracle.xml.parser.v2.XSLStylesheet;
63
import oracle.xml.parser.v2.XSLException;
64
import oracle.xml.parser.v2.XMLDocumentFragment;
65
import oracle.xml.parser.v2.XSLProcessor;
66

    
67
import org.xml.sax.SAXException;
68

    
69
/**
70
 * A metadata catalog server implemented as a Java Servlet
71
 *
72
 * <p>Valid parameters are:<br>
73
 * action=query -- query the values of all elements and attributes
74
 *                     and return a result set of nodes<br>
75
 * action=squery -- structured query (see pathquery.dtd)<br>
76
 * action=read -- read any metadata/data file from Metacat and from Internet<br>
77
 * action=insert -- insert an XML document into the database store<br>
78
 * action=update -- update an XML document that is in the database store<br>
79
 * action=delete --  delete an XML document from the database store<br>
80
 * action=validate -- vallidate the xml contained in valtext<br>
81
 * doctype -- document type list returned by the query (publicID)<br>
82
 * qformat=xml -- display resultset from query in XML<br>
83
 * qformat=html -- display resultset from query in HTML<br>
84
 * qformat=zip -- zip resultset from query<br>
85
 * docid=34 -- display the document with the document ID number 34<br>
86
 * doctext -- XML text of the document to load into the database<br>
87
 * acltext -- XML access text for a document to load into the database<br>
88
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog<br>
89
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
90
 * valtext -- XML text to be validated<br>
91
 * abstractpath -- XPath in metadata document to read from<br>
92
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
93
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
94
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
95
 * action=getdataguide -- retrieve a Data Guide<br>
96
 * action=getprincipals -- retrieve a list of principals in XML<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
// MOVED IT TO doGet() & doPost()
145
//      try {
146
//        // Open a pool of db connections
147
//        connectionPool = util.getConnectionPool();
148
//      } catch (Exception e) {
149
//        System.err.println("Error creating pool of database connections");
150
//        System.err.println(e.getMessage());
151
//      }
152
    } catch ( ServletException ex ) {
153
      throw ex;
154
    }
155
  }
156

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

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

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

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

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

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

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

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

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

    
235
    // This block handles session management for the servlet
236
    // by looking up the current session information for all actions
237
    // other than "login" and "logout"
238
    String username = null;
239
    String password = null;
240
    String groupname = null;
241
    String sess_id = null;
242

    
243
    // handle login action
244
    if (action.equals("login")) {
245

    
246
      handleLoginAction(response.getWriter(), params, request, response);
247

    
248
    // handle logout action  
249
    } else if (action.equals("logout")) {
250

    
251
      handleLogoutAction(response.getWriter(), params, request, response);
252

    
253
    // aware of session expiration on every request  
254
    } else {   
255

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

    
275
    // Now that we know the session is valid, we can delegate the request
276
    // to a particular action handler
277
    if(action.equals("query")) {
278
      handleQuery(response.getWriter(), params, response, username, groupname); 
279
    } else if(action.equals("squery")) {
280
      if(params.containsKey("query")) {
281
        handleSQuery(response.getWriter(), params, response, username, groupname); 
282
      } else {
283
        PrintWriter out = response.getWriter();
284
        out.println("Illegal action squery without \"query\" parameter");
285
      }
286
    } else if (action.equals("read")) {
287
      handleReadAction(params, response, username, groupname);
288
    } else if (action.equals("insert") || action.equals("update")) {
289
      PrintWriter out = response.getWriter();
290
      if ( (username != null) &&  !username.equals("public") ) {
291
        handleInsertOrUpdateAction(out, params, response, username, groupname);
292
      } else {  
293
        out.println("Permission denied for " + action);
294
      }  
295
    } else if (action.equals("delete")) {
296
      PrintWriter out = response.getWriter();
297
      if ( (username != null) &&  !username.equals("public") ) {
298
        handleDeleteAction(out, params, response, username, groupname);
299
      } else {  
300
        out.println("Permission denied for " + action);
301
      }  
302
    } else if (action.equals("validate")) {
303
      PrintWriter out = response.getWriter();
304
      handleValidateAction(out, params, response); 
305
    } else if (action.equals("getdataport")) {
306
      PrintWriter out = response.getWriter();
307
      if ( (username != null) &&  !username.equals("public") ) {
308
      handleGetDataPortAction(out, params, response, username, groupname, 
309
                              sess_id);
310
      } else {
311
        out.println("You must be authenticated to perform the getdataport " +
312
                    "action!");
313
      }
314
    } else if (action.equals("getaccesscontrol")) {
315
      PrintWriter out = response.getWriter();
316
      handleGetAccessControlAction(out, params, response, username, groupname);
317
    } else if (action.equals("getprincipals")) {
318
      PrintWriter out = response.getWriter();
319
      handleGetPrincipalsAction(out, username, password);  
320
    } else if (action.equals("getdoctypes")) {
321
      PrintWriter out = response.getWriter();
322
      handleGetDoctypesAction(out, params, response);  
323
    } else if (action.equals("getdtdschema")) {
324
      PrintWriter out = response.getWriter();
325
      handleGetDTDSchemaAction(out, params, response);  
326
    } else if (action.equals("getdataguide")) {
327
      PrintWriter out = response.getWriter();
328
      handleGetDataGuideAction(out, params, response);  
329
    } else if (action.equals("login") || action.equals("logout")) {
330
    } else if (action.equals("protocoltest")) {
331
      String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
332
      try {
333
        testURL = ((String[])params.get("url"))[0];
334
      } catch (Throwable t) {
335
      }
336
      String phandler = System.getProperty("java.protocol.handler.pkgs");
337
      response.setContentType("text/html");
338
      PrintWriter out = response.getWriter();
339
      out.println("<body bgcolor=\"white\">");
340
      out.println("<p>Handler property: <code>" + phandler + "</code></p>");
341
      out.println("<p>Starting test for:<br>");
342
      out.println("    " + testURL + "</p>");
343
      try {
344
        URL u = new URL(testURL);
345
        out.println("<pre>");
346
        out.println("Protocol: " + u.getProtocol());
347
        out.println("    Host: " + u.getHost());
348
        out.println("    Port: " + u.getPort());
349
        out.println("    Path: " + u.getPath());
350
        out.println("     Ref: " + u.getRef());
351
        String pquery = u.getQuery();
352
        out.println("   Query: " + pquery);
353
        out.println("  Params: ");
354
        if (pquery != null) {
355
          Hashtable qparams = util.parseQuery(u.getQuery());
356
          for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
357
            String pname = (String)en.nextElement();
358
            String pvalue = (String)qparams.get(pname);
359
            out.println("    " + pname + ": " + pvalue);
360
          }
361
        }
362
        out.println("</pre>");
363
        out.println("</body>");
364
        out.close();
365
      } catch (MalformedURLException mue) {
366
        System.out.println("bad url from MetacatServlet.handleGetOrPost");
367
        out.println(mue.getMessage());
368
        mue.printStackTrace(out);
369
        out.close();
370
      }
371
    } else {
372
      PrintWriter out = response.getWriter();
373
      out.println("Error: action not registered.  Please report this error.");
374
    }
375
    
376
    util.closeConnections();
377
    // Close the stream to the client
378
    // out.close();
379
  }
380
  
381
  // LOGIN & LOGOUT SECTION
382
  /** 
383
   * Handle the login request. Create a new session object.
384
   * Do user authentication through the session.
385
   */
386
  private void handleLoginAction(PrintWriter out, Hashtable params, 
387
               HttpServletRequest request, HttpServletResponse response) {
388

    
389
    AuthSession sess = null;
390
    String un = ((String[])params.get("username"))[0];
391
    String pw = ((String[])params.get("password"))[0];
392
    String action = ((String[])params.get("action"))[0];
393
    String qformat = ((String[])params.get("qformat"))[0];
394
    
395
    try {
396
      sess = new AuthSession();
397
    } catch (Exception e) {
398
      System.out.println("error in MetacatServlet.handleLoginAction: " +
399
                          e.getMessage());
400
      out.println(e.getMessage());
401
      return;
402
    }
403
    
404
    boolean isValid = sess.authenticate(request, un, pw);
405

    
406
    // format and transform the output
407
    if (qformat.equals("html")) {
408
      Connection conn = null;
409
      try {
410
        conn = util.getConnection();
411
        DBTransform trans = new DBTransform(conn);
412
        response.setContentType("text/html");
413
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
414
                                   "-//W3C//HTML//EN", out);
415
        util.returnConnection(conn); 
416
      } catch(Exception e) {
417
        util.returnConnection(conn); 
418
      } 
419
      
420
    // any output is returned  
421
    } else {
422
      response.setContentType("text/xml");
423
      out.println(sess.getMessage()); 
424
    }
425
  }    
426

    
427
  /** 
428
   * Handle the logout request. Close the connection.
429
   */
430
  private void handleLogoutAction(PrintWriter out, Hashtable params, 
431
               HttpServletRequest request, HttpServletResponse response) {
432

    
433
    String qformat = ((String[])params.get("qformat"))[0];
434

    
435
    // close the connection
436
    HttpSession sess = request.getSession(false);
437
    if (sess != null) { sess.invalidate();  }    
438

    
439
    // produce output
440
    StringBuffer output = new StringBuffer();
441
    output.append("<?xml version=\"1.0\"?>");
442
    output.append("<logout>");
443
    output.append("User logged out");
444
    output.append("</logout>");
445

    
446
    //format and transform the output
447
    if (qformat.equals("html")) {
448
      Connection conn = null;
449
      try {
450
        conn = util.getConnection();
451
        DBTransform trans = new DBTransform(conn);
452
        response.setContentType("text/html");
453
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN", 
454
                                   "-//W3C//HTML//EN", out);
455
        util.returnConnection(conn); 
456
      } catch(Exception e) {
457
        util.returnConnection(conn); 
458
      } 
459
    // any output is returned  
460
    } else {
461
      response.setContentType("text/xml");
462
      out.println(output.toString()); 
463
    }
464
  }
465
  // END OF LOGIN & LOGOUT SECTION
466
  
467
  // SQUERY & QUERY SECTION
468
  /**      
469
   * Retreive the squery xml, execute it and display it
470
   *
471
   * @param out the output stream to the client
472
   * @param params the Hashtable of parameters that should be included
473
   * in the squery.
474
   * @param response the response object linked to the client
475
   * @param conn the database connection 
476
   */
477
  protected void handleSQuery(PrintWriter out, Hashtable params, 
478
                 HttpServletResponse response, String user, String group)
479
  { 
480
    String xmlquery = ((String[])params.get("query"))[0];
481
    String qformat = ((String[])params.get("qformat"))[0];
482
    String resultdoc = null;
483
    
484
    Hashtable doclist = runQuery(xmlquery, user, group);
485

    
486
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
487
    
488
    //format and transform the results                                        
489
    if(qformat.equals("html")) {
490
      transformResultset(resultdoc, response, out);
491
    } else if(qformat.equals("xml")) {
492
      response.setContentType("text/xml");
493
      out.println(resultdoc);
494
    } else {
495
      out.println("invalid qformat: " + qformat); 
496
    }
497
  }
498
  
499
   /**
500
    * Create the xml query, execute it and display the results.
501
    *
502
    * @param out the output stream to the client
503
    * @param params the Hashtable of parameters that should be included
504
    * in the squery.
505
    * @param response the response object linked to the client
506
    */ 
507
  protected void handleQuery(PrintWriter out, Hashtable params, 
508
                 HttpServletResponse response, String user, String group)
509
  {
510
    //create the query and run it
511
    String xmlquery = DBQuery.createSQuery(params);
512
    Hashtable doclist = runQuery(xmlquery, user, group);
513
    String qformat = ((String[])params.get("qformat"))[0];
514
    String resultdoc = null;
515
    
516
    resultdoc = createResultDocument(doclist, transformQuery(params));
517

    
518
    //format and transform the results                                        
519
    if(qformat.equals("html")) {
520
      transformResultset(resultdoc, response, out);
521
    } else if(qformat.equals("xml")) {
522
      response.setContentType("text/xml");
523
      out.println(resultdoc);
524
    } else { 
525
      out.println("invalid qformat: " + qformat); 
526
    }
527
  }
528
  
529
  /**
530
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
531
   * so it can properly be placed in the <query> tag of the resultset.
532
   * This method is overwritable so that other applications can customize
533
   * the structure of what is in the <query> tag.
534
   * 
535
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
536
   */
537
  protected String transformQuery(Hashtable params)
538
  {
539
    //DBQuery.createSQuery is a re-calling of a previously called 
540
    //function but it is necessary
541
    //so that overriding methods have access to the params hashtable
542
    String xmlquery = DBQuery.createSQuery(params);
543
    //the <?xml version="1.0"?> tag is the first 22 characters of the
544
    xmlquery = xmlquery.trim();
545
    int index = xmlquery.indexOf("?>");
546
    return xmlquery.substring(index + 2, xmlquery.length());
547
  }
548
  
549
  /**
550
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
551
   * string as a param instead of a hashtable.
552
   * 
553
   * @param xmlquery a string representing a query.
554
   */
555
  protected String transformQuery(String xmlquery)
556
  {
557
    xmlquery = xmlquery.trim();
558
    int index = xmlquery.indexOf("?>");
559
    return xmlquery.substring(index + 2, xmlquery.length());
560
  }
561
  
562
  /**
563
   * Run the query and return a hashtable of results.
564
   *
565
   * @param xmlquery the query to run
566
   */
567
  private Hashtable runQuery(String xmlquery, String user, String group)
568
  {
569
    Hashtable doclist=null;
570
    Connection conn = null;
571
    try
572
    {
573
      conn = util.getConnection();
574
      DBQuery queryobj = new DBQuery(conn, saxparser);
575
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group);
576
      util.returnConnection(conn);
577
      return doclist;
578
    } 
579
    catch (Exception e) 
580
    {
581
      util.returnConnection(conn); 
582
      util.debugMessage("Error in MetacatServlet.runQuery: " + e.getMessage());
583
      doclist = null;
584
      return doclist;
585
    }    
586
  }
587
  
588
  /**
589
   * Transorms an xml resultset document to html and sends it to the browser
590
   *
591
   * @param resultdoc the string representation of the document that needs
592
   * to be transformed.
593
   * @param response the HttpServletResponse object bound to the client.
594
   * @param out the output stream to the client
595
   */ 
596
  protected void transformResultset(String resultdoc, 
597
                                    HttpServletResponse response,
598
                                    PrintWriter out)
599
  {
600
    Connection conn = null;
601
    try {
602
      conn = util.getConnection();
603
      DBTransform trans = new DBTransform(conn);
604
      response.setContentType("text/html");
605
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
606
                                 "-//W3C//HTML//EN", out);
607
      util.returnConnection(conn); 
608
    }
609
    catch(Exception e)
610
    {
611
      util.returnConnection(conn); 
612
    } 
613
  }
614
  
615
  /**
616
   * Transforms a hashtable of documents to an xml or html result.
617
   *
618
   * @param doclist- the hashtable to transform
619
   * @param xmlquery- the query that returned the doclist result
620
   */
621
  protected String createResultDocument(Hashtable doclist, String xmlquery)
622
  {
623
    // Create a buffer to hold the xml result
624
    StringBuffer resultset = new StringBuffer();
625
 
626
    // Print the resulting root nodes 
627
    String docid = null;
628
    String document = null;
629
    resultset.append("<?xml version=\"1.0\"?>\n");
630
    resultset.append("<resultset>\n");
631
      
632
    resultset.append("  <query>" + xmlquery + "</query>");   
633

    
634
    if(doclist != null)
635
    {
636
      Enumeration doclistkeys = doclist.keys(); 
637
      while (doclistkeys.hasMoreElements()) 
638
      {
639
        docid = (String)doclistkeys.nextElement();
640
        document = (String)doclist.get(docid);
641
        resultset.append("  <document>" + document + "</document>");
642
      }
643
    }
644

    
645
    resultset.append("</resultset>");
646
    return resultset.toString();
647
  }
648
  // END OF SQUERY & QUERY SECTION
649
  
650
  // READ SECTION
651
  /** 
652
   * Handle the "read" request of metadata/data files from Metacat
653
   * or any files from Internet;
654
   * transformed metadata XML document into HTML presentation if requested;
655
   * zip files when more than one were requested.
656
   *
657
   * @param params the Hashtable of HTTP request parameters
658
   * @param response the HTTP response object linked to the client
659
   * @param user the username sent the request
660
   * @param group the user's groupname
661
   */
662
  private void handleReadAction(Hashtable params, HttpServletResponse response,
663
                                String user, String group) 
664
  {
665
    ServletOutputStream out = null;
666
    ZipOutputStream zout = null;
667
    
668
    try {
669
      String[] docs = new String[0];
670
      String docid = "";
671
      String qformat = "";
672
      String abstrpath = null;
673
      boolean zip = false;
674
      // read the params
675
      if (params.containsKey("docid")) {
676
        docs = (String[])params.get("docid");
677
      }
678
      if (params.containsKey("qformat")) {
679
        qformat = ((String[])params.get("qformat"))[0];
680
      }
681
      if (params.containsKey("abstractpath")) {
682
        abstrpath = ((String[])params.get("abstractpath"))[0];
683
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
684
          viewAbstract(response, abstrpath, docs[0]);
685
          return;
686
        }
687
      }
688
      if ( (docs.length > 1) || qformat.equals("zip") ) {
689
        zip = true;
690
        out = response.getOutputStream();
691
        response.setContentType("application/zip"); //MIME type
692
        zout = new ZipOutputStream(out);
693
      }
694
      // go through the list of docs to read
695
      for (int i=0; i < docs.length; i++ ) {
696
        try {
697

    
698
          URL murl = new URL(docs[i]);
699
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
700
          // case docid="http://.../?docid=aaa" 
701
          // or docid="metacat://.../?docid=bbb"
702
          if (murlQueryStr.containsKey("docid")) {
703
            // get only docid, eliminate the rest
704
            docid = (String)murlQueryStr.get("docid");
705
            if ( zip ) {
706
              addDocToZip(docid, zout);
707
            } else {
708
              readFromMetacat(response, docid, qformat, abstrpath,
709
                              user, group, zip, zout);
710
            }
711

    
712
          // case docid="http://.../filename"
713
          } else {
714
            docid = docs[i];
715
            if ( zip ) {
716
              addDocToZip(docid, zout);
717
            } else {
718
              readFromURLConnection(response, docid);
719
            }
720
          }
721

    
722
        // case docid="ccc"
723
        } catch (MalformedURLException mue) {
724
          docid = docs[i];
725
          if ( zip ) {
726
            addDocToZip(docid, zout);
727
          } else {
728
            readFromMetacat(response, docid, qformat, abstrpath,
729
                            user, group, zip, zout);
730
          }
731
        }
732
        
733
      } /* end for */
734
      
735
      if ( zip ) {
736
        zout.finish(); //terminate the zip file
737
        zout.close();  //close the zip stream
738
      }
739
      
740
    } catch (Exception e) {
741
      try {
742
        if ( out != null ) { out.close(); }
743
        if ( zout != null ) { zout.close(); }
744
        response.setContentType("text/xml"); //MIME type
745
        PrintWriter pw = response.getWriter();
746
        pw.println(e.getMessage());
747
      } catch (IOException ioe) {
748
        System.out.println("Problem with the servlet output " +
749
                           "in MetacatServlet.handleReadAction: " +
750
                           ioe.getMessage());
751
        ioe.printStackTrace(System.out);
752
        
753
      }
754

    
755
      System.out.println("Error in MetacatServlet.handleReadAction: " +
756
                         e.getMessage());
757
      e.printStackTrace(System.out);
758
    }
759
    
760
  }
761
  
762
  // read metadata or data from Metacat
763
  private void readFromMetacat(HttpServletResponse response, String docid,
764
                               String qformat, String abstrpath, String user,
765
                               String group, boolean zip, ZipOutputStream zout)
766
               throws ClassNotFoundException, IOException, SQLException, 
767
                      McdbException, Exception
768
  {
769
    Connection conn = null;
770
    try {
771
      conn = util.getConnection();
772
      DocumentImpl doc = new DocumentImpl(conn, docid);
773
      
774
      if ( doc.getRootNodeID() == 0 ) {
775
        // this is data file
776
        ServletOutputStream out = response.getOutputStream(); 
777
        String filepath = util.getOption("datafilepath");
778
        if(!filepath.endsWith("/")) {
779
          filepath += "/";
780
        }
781
        String filename = filepath + doc.getDocname();      //MIME type
782
        String contentType = getServletContext().getMimeType(filename);
783
        if (contentType == null) {
784
          if (filename.endsWith(".xml")) {
785
            contentType="text/xml";
786
          } else if (filename.endsWith(".css")) {
787
            contentType="text/css";
788
          } else if (filename.endsWith(".dtd")) {
789
            contentType="text/plain";
790
          } else if (filename.endsWith(".xsd")) {
791
            contentType="text/xml";
792
          } else if (filename.endsWith("/")) {
793
            contentType="text/html";
794
          } else {
795
            File f = new File(filename);
796
            if ( f.isDirectory() ) {
797
              contentType="text/html";
798
            } else {
799
              contentType="application/octet-stream";
800
            }
801
          }
802
        }
803
        response.setContentType(contentType);
804
        // if we decide to use "application/octet-stream" for all data returns
805
        // response.setContentType("application/octet-stream");
806
        FileInputStream fin = null;
807
        try {
808
          fin = new FileInputStream(filename);
809
          byte[] buf = new byte[4 * 1024]; // 4K buffer
810
          int b = fin.read(buf);
811
          while (b != -1) {
812
            out.write(buf, 0, b);
813
            b = fin.read(buf);
814
          }
815
        } finally {
816
          if (fin != null) fin.close();
817
        }
818

    
819
      } else {
820
        // this is metadata doc
821
        if ( qformat.equals("html") ) { 
822
          response.setContentType("text/html");  //MIME type
823
          PrintWriter out = response.getWriter();
824
    
825
          // Look up the document type
826
          String doctype = doc.getDoctype();
827
          // Transform the document to the new doctype
828
          DBTransform dbt = new DBTransform(conn);
829
          dbt.transformXMLDocument(doc.toString(),
830
                                   doctype,"-//W3C//HTML//EN",out);
831
        } else {
832
          // set content type first
833
          response.setContentType("text/xml");   //MIME type
834
          PrintWriter out = response.getWriter();
835
          doc.toXml(out);
836
        }
837
      
838
      }
839
    } finally {
840
      util.returnConnection(conn);
841
    }
842
    
843
  }
844
  
845
  // read data from URLConnection
846
  private void readFromURLConnection(HttpServletResponse response, String docid)
847
               throws IOException, MalformedURLException
848
  {
849
    ServletOutputStream out = response.getOutputStream(); 
850
    String contentType = getServletContext().getMimeType(docid); //MIME type
851
    if (contentType == null) {
852
      if (docid.endsWith(".xml")) {
853
        contentType="text/xml";
854
      } else if (docid.endsWith(".css")) {
855
        contentType="text/css";
856
      } else if (docid.endsWith(".dtd")) {
857
        contentType="text/plain";
858
      } else if (docid.endsWith(".xsd")) {
859
        contentType="text/xml";
860
      } else if (docid.endsWith("/")) {
861
        contentType="text/html";
862
      } else {
863
        File f = new File(docid);
864
        if ( f.isDirectory() ) {
865
          contentType="text/html";
866
        } else {
867
          contentType="application/octet-stream";
868
        }
869
      }
870
    }
871
    response.setContentType(contentType);
872
    // if we decide to use "application/octet-stream" for all data returns
873
    // response.setContentType("application/octet-stream");
874

    
875
    // this is http url
876
    URL url = new URL(docid);
877
    BufferedInputStream bis = null;
878
    try {
879
      bis = new BufferedInputStream(url.openStream());
880
      byte[] buf = new byte[4 * 1024]; // 4K buffer
881
      int b = bis.read(buf);
882
      while (b != -1) {
883
        out.write(buf, 0, b);
884
        b = bis.read(buf);
885
      }
886
    } finally {
887
      if (bis != null) bis.close();
888
    }
889
    
890
  }
891
  
892
  // read file/doc and write to ZipOutputStream
893
  private void addDocToZip(String docid, ZipOutputStream zout)
894
               throws ClassNotFoundException, IOException, SQLException, 
895
                      McdbException, Exception
896
  {
897
    byte[] bytestring = null;
898
    ZipEntry zentry = null;
899

    
900
    try {
901
      URL url = new URL(docid);
902

    
903
      // this http url; read from URLConnection; add to zip
904
      zentry = new ZipEntry(docid);
905
      zout.putNextEntry(zentry);
906
      BufferedInputStream bis = null;
907
      try {
908
        bis = new BufferedInputStream(url.openStream());
909
        byte[] buf = new byte[4 * 1024]; // 4K buffer
910
        int b = bis.read(buf);
911
        while(b != -1) {
912
          zout.write(buf, 0, b);
913
          b = bis.read(buf);
914
        }
915
      } finally {
916
        if (bis != null) bis.close();
917
      }
918
      zout.closeEntry();
919

    
920
    } catch (MalformedURLException mue) {
921
      
922
      // this is metacat doc (data file or metadata doc)
923
      Connection conn = null;
924
      try {
925
        conn = util.getConnection();
926
        DocumentImpl doc = new DocumentImpl(conn, docid);
927
      
928
        if ( doc.getRootNodeID() == 0 ) {
929
          // this is data file; add file to zip
930
          String filepath = util.getOption("datafilepath");
931
          if(!filepath.endsWith("/")) {
932
            filepath += "/";
933
          }
934
          String filename = filepath + doc.getDocname();
935
          zentry = new ZipEntry(filename);
936
          zout.putNextEntry(zentry);
937
          FileInputStream fin = null;
938
          try {
939
            fin = new FileInputStream(filename);
940
            byte[] buf = new byte[4 * 1024]; // 4K buffer
941
            int b = fin.read(buf);
942
            while (b != -1) {
943
              zout.write(buf, 0, b);
944
              b = fin.read(buf);
945
            }
946
          } finally {
947
            if (fin != null) fin.close();
948
          }
949
          zout.closeEntry();
950

    
951
        } else {
952
          // this is metadata doc; add doc to zip
953
          bytestring = doc.toString().getBytes();
954
          zentry = new ZipEntry(docid + ".xml");
955
          zentry.setSize(bytestring.length);
956
          zout.putNextEntry(zentry);
957
          zout.write(bytestring, 0, bytestring.length);
958
          zout.closeEntry();
959
        }
960
      } finally {
961
        util.returnConnection(conn);
962
      }
963
      
964
    }
965
      
966
  }
967
  
968
  // view abstract within document
969
  private void viewAbstract(HttpServletResponse response,
970
                            String abstractpath, String docid)
971
               throws ClassNotFoundException, IOException, SQLException,
972
                      McdbException, Exception
973
  {
974
    Connection conn = null;
975
    try {
976
      conn = util.getConnection();
977
    
978
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
979
    
980
      response.setContentType("text/html");  //MIME type
981
      PrintWriter out = response.getWriter();
982
      out.println("<html><head><title>Abstract</title></head>");
983
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
984
      for (int i=0; i<abstracts.length; i++) {
985
        out.println("<p>" + (String)abstracts[i] + "</p>");
986
      }
987
      out.println("</body></html>");
988

    
989
    } finally {
990
      util.returnConnection(conn);
991
    }
992
  }
993
  // END OF READ SECTION
994
    
995
  // INSERT/UPDATE SECTION
996
  /** 
997
   * Handle the database putdocument request and write an XML document 
998
   * to the database connection
999
   */
1000
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
1001
               HttpServletResponse response, String user, String group) {
1002

    
1003
    Connection conn = null;
1004

    
1005
    try {
1006
      // Get the document indicated
1007
      String[] doctext = (String[])params.get("doctext");
1008

    
1009
      String pub = null;
1010
      if (params.containsKey("public")) {
1011
        pub = ((String[])params.get("public"))[0];
1012
      }
1013

    
1014
      StringReader dtd = null;
1015
      if (params.containsKey("dtdtext")) {
1016
        String[] dtdtext = (String[])params.get("dtdtext");
1017
        try {
1018
          if ( !dtdtext[0].equals("") ) {
1019
            dtd = new StringReader(dtdtext[0]);
1020
          }
1021
        } catch (NullPointerException npe) {}
1022
      }
1023
      
1024
      StringReader xml = null;
1025
      boolean validate = false;
1026
      try {
1027
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... > 
1028
        // in order to decide whether to use validation parser
1029
        validate = validateXML(doctext[0]);
1030
        xml = new StringReader(doctext[0]);
1031

    
1032
        String[] action = (String[])params.get("action");
1033
        String[] docid = (String[])params.get("docid");
1034
        String newdocid = null;
1035

    
1036
        String doAction = null;
1037
        if (action[0].equals("insert")) {
1038
          doAction = "INSERT";
1039
        } else if (action[0].equals("update")) {
1040
          doAction = "UPDATE";
1041
        }
1042

    
1043
        try {
1044
          // get a connection from the pool
1045
          conn = util.getConnection();
1046

    
1047
          // write the document to the database
1048
          try {
1049
            String accNumber = docid[0];
1050
            if (accNumber.equals("")) {
1051
              accNumber = null;
1052
            }
1053
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1054
                                          accNumber, user, group, validate);
1055
          } catch (NullPointerException npe) {
1056
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1057
                                          null, user, group, validate);
1058
          }
1059
        } finally {
1060
          util.returnConnection(conn);
1061
        }    
1062

    
1063
        // set content type and other response header fields first
1064
        response.setContentType("text/xml");
1065
        out.println("<?xml version=\"1.0\"?>");
1066
        out.println("<success>");
1067
        out.println("<docid>" + newdocid + "</docid>"); 
1068
        out.println("</success>");
1069

    
1070
      } catch (NullPointerException npe) {
1071
        response.setContentType("text/xml");
1072
        out.println("<?xml version=\"1.0\"?>");
1073
        out.println("<error>");
1074
        out.println(npe.getMessage()); 
1075
        out.println("</error>");
1076
      }
1077
    } catch (Exception e) {
1078
      response.setContentType("text/xml");
1079
      out.println("<?xml version=\"1.0\"?>");
1080
      out.println("<error>");
1081
      out.println(e.getMessage()); 
1082
      if (e instanceof SAXException) {
1083
        Exception e2 = ((SAXException)e).getException();
1084
        out.println("<error>");
1085
        out.println(e2.getMessage()); 
1086
        out.println("</error>");
1087
      }
1088
      //e.printStackTrace(out);
1089
      out.println("</error>");
1090
    }
1091
  }
1092

    
1093
  /** 
1094
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > 
1095
   * in order to decide whether to use validation parser
1096
   */
1097
  private static boolean validateXML(String xmltext) throws IOException {
1098
    
1099
    StringReader xmlreader = new StringReader(xmltext);
1100
    StringBuffer cbuff = new StringBuffer();
1101
    java.util.Stack st = new java.util.Stack();
1102
    boolean validate = false;
1103
    int c;
1104
    int inx;
1105
    
1106
    // read from the stream until find the keywords
1107
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1108
      cbuff.append((char)c);
1109

    
1110
      // "<!DOCTYPE" keyword is found; put it in the stack
1111
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1112
        cbuff = new StringBuffer();
1113
        st.push("<!DOCTYPE");
1114
      }
1115
      // "PUBLIC" keyword is found; put it in the stack
1116
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1117
        cbuff = new StringBuffer();
1118
        st.push("PUBLIC");
1119
      }
1120
      // "SYSTEM" keyword is found; put it in the stack
1121
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1122
        cbuff = new StringBuffer();
1123
        st.push("SYSTEM");
1124
      }
1125
      // ">" character is found; put it in the stack
1126
      // ">" is found twice: fisrt from <?xml ...?> 
1127
      // and second from <!DOCTYPE ... >
1128
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1129
        cbuff = new StringBuffer();
1130
        st.push(">");
1131
      }
1132
    }
1133

    
1134
    // close the stream
1135
    xmlreader.close();
1136

    
1137
    // check the stack whether it contains the keywords:
1138
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1139
    if ( st.size() == 4 ) {
1140
      if ( ((String)st.pop()).equals(">") &&
1141
           ( ((String)st.peek()).equals("PUBLIC") |
1142
             ((String)st.pop()).equals("SYSTEM") ) &&
1143
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1144
        validate = true;
1145
      }
1146
    }
1147

    
1148
System.out.println("Validation is " + validate);
1149
    return validate;
1150
  }
1151
  // END OF INSERT/UPDATE SECTION
1152

    
1153
  // DELETE SECTION
1154
  /** 
1155
   * Handle the database delete request and delete an XML document 
1156
   * from the database connection
1157
   */
1158
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1159
               HttpServletResponse response, String user, String group) {
1160

    
1161
    String[] docid = (String[])params.get("docid");
1162
    Connection conn = null;
1163

    
1164
    // delete the document from the database
1165
    try {
1166
      // get a connection from the pool
1167
      conn = util.getConnection();
1168
                                      // NOTE -- NEED TO TEST HERE
1169
                                      // FOR EXISTENCE OF DOCID PARAM
1170
                                      // BEFORE ACCESSING ARRAY
1171
      try { 
1172
        DocumentImpl.delete(conn, docid[0], user, group);
1173
        response.setContentType("text/xml");
1174
        out.println("<?xml version=\"1.0\"?>");
1175
        out.println("<success>");
1176
        out.println("Document deleted."); 
1177
        out.println("</success>");
1178
      } catch (AccessionNumberException ane) {
1179
        response.setContentType("text/xml");
1180
        out.println("<?xml version=\"1.0\"?>");
1181
        out.println("<error>");
1182
        out.println("Error deleting document!!!");
1183
        out.println(ane.getMessage()); 
1184
        out.println("</error>");
1185
      }
1186
    } catch (Exception e) {
1187
      response.setContentType("text/xml");
1188
      out.println("<?xml version=\"1.0\"?>");
1189
      out.println("<error>");
1190
      out.println(e.getMessage()); 
1191
      out.println("</error>");
1192
    } finally {
1193
      util.returnConnection(conn);
1194
    }  
1195
  }
1196
  // END OF DELETE SECTION
1197
  
1198
  // VALIDATE SECTION
1199
  /** 
1200
   * Handle the validation request and return the results to the requestor
1201
   */
1202
  private void handleValidateAction(PrintWriter out, Hashtable params, 
1203
               HttpServletResponse response) {
1204

    
1205
    // Get the document indicated
1206
    String valtext = null;
1207
    
1208
    try {
1209
      valtext = ((String[])params.get("valtext"))[0];
1210
    } catch (Exception nullpe) {
1211

    
1212
      Connection conn = null;
1213
      String docid = null;
1214
      try {
1215
        // Find the document id number
1216
        docid = ((String[])params.get("docid"))[0]; 
1217

    
1218
        // get a connection from the pool
1219
        conn = util.getConnection();
1220

    
1221
        // Get the document indicated from the db
1222
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1223
        valtext = xmldoc.toString();
1224

    
1225
      } catch (NullPointerException npe) {
1226
        response.setContentType("text/xml");
1227
        out.println("<error>Error getting document ID: " + docid + "</error>");
1228
        if ( conn != null ) { util.returnConnection(conn); }
1229
        return;
1230
      } catch (Exception e) {
1231
        response.setContentType("text/html");
1232
        out.println(e.getMessage()); 
1233
      } finally {
1234
        util.returnConnection(conn);
1235
      }  
1236
    }
1237

    
1238
    Connection conn = null;
1239
    try {
1240
      // get a connection from the pool
1241
      conn = util.getConnection();
1242
      DBValidate valobj = new DBValidate(saxparser,conn);
1243
      boolean valid = valobj.validateString(valtext);
1244

    
1245
      // set content type and other response header fields first
1246
      response.setContentType("text/xml");
1247
      out.println(valobj.returnErrors());
1248

    
1249
    } catch (NullPointerException npe2) {
1250
      // set content type and other response header fields first
1251
      response.setContentType("text/xml");
1252
      out.println("<error>Error validating document.</error>"); 
1253
    } catch (Exception e) {
1254
      response.setContentType("text/html");
1255
      out.println(e.getMessage()); 
1256
    } finally {
1257
      util.returnConnection(conn);
1258
    }  
1259
  }
1260
  // END OF VALIDATE SECTION
1261
 
1262
  // OTHER ACTION HANDLERS
1263
  /**
1264
   * sends the port number that the data socket is running on.
1265
   * This is a parameter set in the metacat.properties file.
1266
   */
1267
  private void handleGetDataPortAction(PrintWriter out, Hashtable params, 
1268
                                       HttpServletResponse response, 
1269
                                       String username, String groupname,
1270
                                       String sess_id)
1271
  {
1272
    int port;
1273
    String filedir = null;
1274
    try
1275
    {
1276
      filedir = util.getOption("datafilepath");
1277
      
1278
      Random r = new Random();
1279
      port = r.nextInt(65000);  //pick a random port between 0-65000
1280
      //System.out.println("random port is: " + port);
1281
      while(!DataFileServer.portIsAvailable(port))
1282
      {
1283
        port = r.nextInt(65000);
1284
        //System.out.println("next port used: " + port);
1285
      }
1286
      DataFileServer dfs = new DataFileServer(port, username, sess_id);
1287
      dfs.start();
1288
      
1289
      //System.out.println("filedir: " + filedir);
1290
      //System.out.println("port: " + port);
1291
      response.setContentType("text/xml");
1292
      out.println("<?xml version=\"1.0\"?>");
1293
      out.println("<port>");
1294
      out.print(port);
1295
      out.print("</port>");
1296
      
1297
    }
1298
	  catch (Exception e) 
1299
    {
1300
      System.out.println("error in MetacatServlet.handleGetDataPortAction: " + 
1301
                          e.getMessage());
1302
    }
1303
  }
1304
  
1305
  /** 
1306
   * Handle "getaccesscontrol" action.
1307
   * Read Access Control List from db connection in XML format
1308
   */
1309
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params, 
1310
                                       HttpServletResponse response, 
1311
                                       String username, String groupname) {
1312

    
1313
    Connection conn = null;
1314
    String docid = ((String[])params.get("docid"))[0];
1315
    
1316
    try {
1317

    
1318
        // get connection from the pool
1319
        conn = util.getConnection();
1320
        AccessControlList aclobj = new AccessControlList(conn);
1321
        String acltext = aclobj.getACL(docid, username, groupname);
1322
        out.println(acltext);
1323

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

    
1335
  /** 
1336
   * Handle the "getprincipals" action.
1337
   * Read all principals from authentication scheme in XML format
1338
   */
1339
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1340
                                         String password) {
1341

    
1342
    Connection conn = null;
1343

    
1344
    try {
1345

    
1346
        // get connection from the pool
1347
        AuthSession auth = new AuthSession();
1348
        String principals = auth.getPrincipals(user, password);
1349
        out.println(principals);
1350

    
1351
    } catch (Exception e) {
1352
      out.println("<?xml version=\"1.0\"?>");
1353
      out.println("<error>");
1354
      out.println(e.getMessage());
1355
      out.println("</error>");
1356
    } finally {
1357
      util.returnConnection(conn);
1358
    }  
1359
    
1360
  }
1361

    
1362
  /** 
1363
   * Handle "getdoctypes" action.
1364
   * Read all doctypes from db connection in XML format
1365
   */
1366
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1367
                                       HttpServletResponse response) {
1368

    
1369
    Connection conn = null;
1370
    
1371
    try {
1372

    
1373
        // get connection from the pool
1374
        conn = util.getConnection();
1375
        DBUtil dbutil = new DBUtil(conn);
1376
        String doctypes = dbutil.readDoctypes();
1377
        out.println(doctypes);
1378

    
1379
    } catch (Exception e) {
1380
      out.println("<?xml version=\"1.0\"?>");
1381
      out.println("<error>");
1382
      out.println(e.getMessage());
1383
      out.println("</error>");
1384
    } finally {
1385
      util.returnConnection(conn);
1386
    }  
1387
    
1388
  }
1389

    
1390
  /** 
1391
   * Handle the "getdtdschema" action.
1392
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1393
   */
1394
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1395
                                        HttpServletResponse response) {
1396

    
1397
    Connection conn = null;
1398
    String doctype = null;
1399
    String[] doctypeArr = (String[])params.get("doctype");
1400

    
1401
    // get only the first doctype specified in the list of doctypes
1402
    // it could be done for all doctypes in that list
1403
    if (doctypeArr != null) {
1404
        doctype = ((String[])params.get("doctype"))[0]; 
1405
    }
1406

    
1407
    try {
1408

    
1409
        // get connection from the pool
1410
        conn = util.getConnection();
1411
        DBUtil dbutil = new DBUtil(conn);
1412
        String dtdschema = dbutil.readDTDSchema(doctype);
1413
        out.println(dtdschema);
1414

    
1415
    } catch (Exception e) {
1416
      out.println("<?xml version=\"1.0\"?>");
1417
      out.println("<error>");
1418
      out.println(e.getMessage());
1419
      out.println("</error>");
1420
    } finally {
1421
      util.returnConnection(conn);
1422
    }  
1423
    
1424
  }
1425

    
1426
  /** 
1427
   * Handle the "getdataguide" action.
1428
   * Read Data Guide for a given doctype from db connection in XML format
1429
   */
1430
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1431
                                        HttpServletResponse response) {
1432

    
1433
    Connection conn = null;
1434
    String doctype = null;
1435
    String[] doctypeArr = (String[])params.get("doctype");
1436

    
1437
    // get only the first doctype specified in the list of doctypes
1438
    // it could be done for all doctypes in that list
1439
    if (doctypeArr != null) {
1440
        doctype = ((String[])params.get("doctype"))[0]; 
1441
    }
1442

    
1443
    try {
1444

    
1445
        // get connection from the pool
1446
        conn = util.getConnection();
1447
        DBUtil dbutil = new DBUtil(conn);
1448
        String dataguide = dbutil.readDataGuide(doctype);
1449
        out.println(dataguide);
1450

    
1451
    } catch (Exception e) {
1452
      out.println("<?xml version=\"1.0\"?>");
1453
      out.println("<error>");
1454
      out.println(e.getMessage());
1455
      out.println("</error>");
1456
    } finally {
1457
      util.returnConnection(conn);
1458
    }  
1459
    
1460
  }
1461

    
1462
}
(32-32/43)