Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: bojilova $'
10
 *     '$Date: 2001-05-02 14:52:06 -0700 (Wed, 02 May 2001) $'
11
 * '$Revision: 733 $'
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
    String[] returndoc = null;
484
    if(params.contains("returndoc"))
485
    {
486
      returndoc = (String[])params.get("returndoc");
487
    }
488
    
489
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
490
    //String resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
491

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

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

    
652
    if(doclist != null)
653
    {
654
      Enumeration doclistkeys = doclist.keys(); 
655
      while (doclistkeys.hasMoreElements()) 
656
      {
657
        docid = (String)doclistkeys.nextElement();
658
        document = (String)doclist.get(docid);
659
        resultset.append("  <document>" + document + "</document>");
660
      }
661
    }
662

    
663
    resultset.append("</resultset>");
664
    //System.out.println(resultset.toString());
665
    return resultset.toString();
666
  }
667
  // END OF SQUERY & QUERY SECTION
668
  
669
  // READ SECTION
670
  /** 
671
   * Handle the "read" request of metadata/data files from Metacat
672
   * or any files from Internet;
673
   * transformed metadata XML document into HTML presentation if requested;
674
   * zip files when more than one were requested.
675
   *
676
   * @param params the Hashtable of HTTP request parameters
677
   * @param response the HTTP response object linked to the client
678
   * @param user the username sent the request
679
   * @param group the user's groupname
680
   */
681
  private void handleReadAction(Hashtable params, HttpServletResponse response,
682
                                String user, String group) 
683
  {
684
    ServletOutputStream out = null;
685
    ZipOutputStream zout = null;
686
    
687
    try {
688
      String[] docs = new String[0];
689
      String docid = "";
690
      String qformat = "";
691
      String abstrpath = null;
692
      boolean zip = false;
693
      // read the params
694
      if (params.containsKey("docid")) {
695
        docs = (String[])params.get("docid");
696
      }
697
      if (params.containsKey("qformat")) {
698
        qformat = ((String[])params.get("qformat"))[0];
699
      }
700
      if (params.containsKey("abstractpath")) {
701
        abstrpath = ((String[])params.get("abstractpath"))[0];
702
        viewAbstract(response, abstrpath, docs[0]);
703
      }
704
      if ( (docs.length > 1) || qformat.equals("zip") ) {
705
        zip = true;
706
        out = response.getOutputStream();
707
        response.setContentType("application/zip"); //MIME type
708
        zout = new ZipOutputStream(out);
709
      }
710
      // go through the list of docs to read
711
      for (int i=0; i < docs.length; i++ ) {
712
        try {
713

    
714
          URL murl = new URL(docs[i]);
715
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
716
          // case docid="http://.../?docid=aaa" 
717
          // or docid="metacat://.../?docid=bbb"
718
          if (murlQueryStr.containsKey("docid")) {
719
            // get only docid, eliminate the rest
720
            docid = (String)murlQueryStr.get("docid");
721
            if ( zip ) {
722
              addDocToZip(docid, zout);
723
            } else {
724
              readFromMetacat(response, docid, qformat, abstrpath,
725
                              user, group, zip, zout);
726
            }
727

    
728
          // case docid="http://.../filename"
729
          } else {
730
            docid = docs[i];
731
            if ( zip ) {
732
              addDocToZip(docid, zout);
733
            } else {
734
              readFromURLConnection(response, docid);
735
            }
736
          }
737

    
738
        // case docid="ccc"
739
        } catch (MalformedURLException mue) {
740
          docid = docs[i];
741
          if ( zip ) {
742
            addDocToZip(docid, zout);
743
          } else {
744
            readFromMetacat(response, docid, qformat, abstrpath,
745
                            user, group, zip, zout);
746
          }
747
        }
748
        
749
      } /* end for */
750
      
751
      if ( zip ) {
752
        zout.finish(); //terminate the zip file
753
        zout.close();  //close the zip stream
754
      }
755
      
756
    } catch (Exception e) {
757
      try {
758
        if ( out != null ) { out.close(); }
759
        if ( zout != null ) { zout.close(); }
760
        response.setContentType("text/xml"); //MIME type
761
        PrintWriter pw = response.getWriter();
762
        pw.println(e.getMessage());
763
      } catch (IOException ioe) {
764
        System.out.println("Problem with the servlet output " +
765
                           "in MetacatServlet.handleReadAction: " +
766
                           ioe.getMessage());
767
        ioe.printStackTrace(System.out);
768
        
769
      }
770

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

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

    
891
    // this is http url
892
    URL url = new URL(docid);
893
    BufferedInputStream bis = null;
894
    try {
895
      bis = new BufferedInputStream(url.openStream());
896
      byte[] buf = new byte[4 * 1024]; // 4K buffer
897
      int b = bis.read(buf);
898
      while (b != -1) {
899
        out.write(buf, 0, b);
900
        b = bis.read(buf);
901
      }
902
    } finally {
903
      if (bis != null) bis.close();
904
    }
905
    
906
  }
907
  
908
  // read file/doc and write to ZipOutputStream
909
  private void addDocToZip(String docid, ZipOutputStream zout)
910
               throws ClassNotFoundException, IOException, SQLException, 
911
                      McdbException, Exception
912
  {
913
    byte[] bytestring = null;
914
    ZipEntry zentry = null;
915

    
916
    try {
917
      URL url = new URL(docid);
918

    
919
      // this http url; read from URLConnection; add to zip
920
      zentry = new ZipEntry(docid);
921
      zout.putNextEntry(zentry);
922
      BufferedInputStream bis = null;
923
      try {
924
        bis = new BufferedInputStream(url.openStream());
925
        byte[] buf = new byte[4 * 1024]; // 4K buffer
926
        int b = bis.read(buf);
927
        while(b != -1) {
928
          zout.write(buf, 0, b);
929
          b = bis.read(buf);
930
        }
931
      } finally {
932
        if (bis != null) bis.close();
933
      }
934
      zout.closeEntry();
935

    
936
    } catch (MalformedURLException mue) {
937
      
938
      // this is metacat doc (data file or metadata doc)
939
      Connection conn = null;
940
      try {
941
        conn = util.getConnection();
942
        DocumentImpl doc = new DocumentImpl(conn, docid);
943
      
944
        if ( doc.getRootNodeID() == 0 ) {
945
          // this is data file; add file to zip
946
          String filepath = util.getOption("datafilepath");
947
          if(!filepath.endsWith("/")) {
948
            filepath += "/";
949
          }
950
          String filename = filepath + doc.getDocname();
951
          zentry = new ZipEntry(filename);
952
          zout.putNextEntry(zentry);
953
          FileInputStream fin = null;
954
          try {
955
            fin = new FileInputStream(filename);
956
            byte[] buf = new byte[4 * 1024]; // 4K buffer
957
            int b = fin.read(buf);
958
            while (b != -1) {
959
              zout.write(buf, 0, b);
960
              b = fin.read(buf);
961
            }
962
          } finally {
963
            if (fin != null) fin.close();
964
          }
965
          zout.closeEntry();
966

    
967
        } else {
968
          // this is metadata doc; add doc to zip
969
          bytestring = doc.toString().getBytes();
970
          zentry = new ZipEntry(docid + ".xml");
971
          zentry.setSize(bytestring.length);
972
          zout.putNextEntry(zentry);
973
          zout.write(bytestring, 0, bytestring.length);
974
          zout.closeEntry();
975
        }
976
      } finally {
977
        util.returnConnection(conn);
978
      }
979
      
980
    }
981
      
982
  }
983
  
984
  // view abstract within document
985
  private void viewAbstract(HttpServletResponse response,
986
                            String abstractpath, String docid)
987
               throws ClassNotFoundException, IOException, SQLException,
988
                      McdbException, Exception
989
  {
990
    Connection conn = null;
991
    try {
992
      conn = util.getConnection();
993
      DocumentImpl doc = new DocumentImpl(conn, docid);
994
    
995
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
996
    
997
      response.setContentType("text/html");  //MIME type
998
      PrintWriter out = response.getWriter();
999
      out.println("<html><head><title>Abstract</title></head>");
1000
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
1001
      for (int i=0; i<abstracts.length; i++) {
1002
        out.println("<p>" + (String)abstracts[i] + "</p>");
1003
      }
1004
      out.println("</body></html>");
1005

    
1006
    } finally {
1007
      util.returnConnection(conn);
1008
    }
1009
  }
1010
  // END OF READ SECTION
1011
    
1012
  // INSERT/UPDATE SECTION
1013
  /** 
1014
   * Handle the database putdocument request and write an XML document 
1015
   * to the database connection
1016
   */
1017
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
1018
               HttpServletResponse response, String user, String group) {
1019

    
1020
    Connection conn = null;
1021

    
1022
    try {
1023
      // Get the document indicated
1024
      String[] doctext = (String[])params.get("doctext");
1025

    
1026
      String pub = null;
1027
      if (params.containsKey("public")) {
1028
        pub = ((String[])params.get("public"))[0];
1029
      }
1030

    
1031
      StringReader dtd = null;
1032
      if (params.containsKey("dtdtext")) {
1033
        String[] dtdtext = (String[])params.get("dtdtext");
1034
        try {
1035
          if ( !dtdtext[0].equals("") ) {
1036
            dtd = new StringReader(dtdtext[0]);
1037
          }
1038
        } catch (NullPointerException npe) {}
1039
      }
1040
      
1041
      StringReader xml = null;
1042
      boolean validate = false;
1043
      try {
1044
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... > 
1045
        // in order to decide whether to use validation parser
1046
        validate = validateXML(doctext[0]);
1047
        xml = new StringReader(doctext[0]);
1048

    
1049
        String[] action = (String[])params.get("action");
1050
        String[] docid = (String[])params.get("docid");
1051
        String newdocid = null;
1052

    
1053
        String doAction = null;
1054
        if (action[0].equals("insert")) {
1055
          doAction = "INSERT";
1056
        } else if (action[0].equals("update")) {
1057
          doAction = "UPDATE";
1058
        }
1059

    
1060
        try {
1061
          // get a connection from the pool
1062
          conn = util.getConnection();
1063

    
1064
          // write the document to the database
1065
          try {
1066
            String accNumber = docid[0];
1067
            if (accNumber.equals("")) {
1068
              accNumber = null;
1069
            }
1070
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1071
                                          accNumber, user, group, validate);
1072
          } catch (NullPointerException npe) {
1073
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1074
                                          null, user, group, validate);
1075
          }
1076
        } finally {
1077
          util.returnConnection(conn);
1078
        }    
1079

    
1080
        // set content type and other response header fields first
1081
        response.setContentType("text/xml");
1082
        out.println("<?xml version=\"1.0\"?>");
1083
        out.println("<success>");
1084
        out.println("<docid>" + newdocid + "</docid>"); 
1085
        out.println("</success>");
1086

    
1087
      } catch (NullPointerException npe) {
1088
        response.setContentType("text/xml");
1089
        out.println("<?xml version=\"1.0\"?>");
1090
        out.println("<error>");
1091
        out.println(npe.getMessage()); 
1092
        out.println("</error>");
1093
      }
1094
    } catch (Exception e) {
1095
      response.setContentType("text/xml");
1096
      out.println("<?xml version=\"1.0\"?>");
1097
      out.println("<error>");
1098
      out.println(e.getMessage()); 
1099
      if (e instanceof SAXException) {
1100
        Exception e2 = ((SAXException)e).getException();
1101
        out.println("<error>");
1102
        out.println(e2.getMessage()); 
1103
        out.println("</error>");
1104
      }
1105
      //e.printStackTrace(out);
1106
      out.println("</error>");
1107
    }
1108
  }
1109

    
1110
  /** 
1111
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > 
1112
   * in order to decide whether to use validation parser
1113
   */
1114
  private static boolean validateXML(String xmltext) throws IOException {
1115
    
1116
    StringReader xmlreader = new StringReader(xmltext);
1117
    StringBuffer cbuff = new StringBuffer();
1118
    java.util.Stack st = new java.util.Stack();
1119
    boolean validate = false;
1120
    int c;
1121
    int inx;
1122
    
1123
    // read from the stream until find the keywords
1124
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1125
      cbuff.append((char)c);
1126

    
1127
      // "<!DOCTYPE" keyword is found; put it in the stack
1128
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1129
        cbuff = new StringBuffer();
1130
        st.push("<!DOCTYPE");
1131
      }
1132
      // "PUBLIC" keyword is found; put it in the stack
1133
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1134
        cbuff = new StringBuffer();
1135
        st.push("PUBLIC");
1136
      }
1137
      // "SYSTEM" keyword is found; put it in the stack
1138
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1139
        cbuff = new StringBuffer();
1140
        st.push("SYSTEM");
1141
      }
1142
      // ">" character is found; put it in the stack
1143
      // ">" is found twice: fisrt from <?xml ...?> 
1144
      // and second from <!DOCTYPE ... >
1145
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1146
        cbuff = new StringBuffer();
1147
        st.push(">");
1148
      }
1149
    }
1150

    
1151
    // close the stream
1152
    xmlreader.close();
1153

    
1154
    // check the stack whether it contains the keywords:
1155
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1156
    if ( st.size() == 4 ) {
1157
      if ( ((String)st.pop()).equals(">") &&
1158
           ( ((String)st.peek()).equals("PUBLIC") |
1159
             ((String)st.pop()).equals("SYSTEM") ) &&
1160
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1161
        validate = true;
1162
      }
1163
    }
1164

    
1165
System.out.println("Validation is " + validate);
1166
    return validate;
1167
  }
1168
  // END OF INSERT/UPDATE SECTION
1169

    
1170
  // DELETE SECTION
1171
  /** 
1172
   * Handle the database delete request and delete an XML document 
1173
   * from the database connection
1174
   */
1175
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1176
               HttpServletResponse response, String user, String group) {
1177

    
1178
    String[] docid = (String[])params.get("docid");
1179
    Connection conn = null;
1180

    
1181
    // delete the document from the database
1182
    try {
1183
      // get a connection from the pool
1184
      conn = util.getConnection();
1185
                                      // NOTE -- NEED TO TEST HERE
1186
                                      // FOR EXISTENCE OF DOCID PARAM
1187
                                      // BEFORE ACCESSING ARRAY
1188
      try { 
1189
        DocumentImpl.delete(conn, docid[0], user, group);
1190
        response.setContentType("text/xml");
1191
        out.println("<?xml version=\"1.0\"?>");
1192
        out.println("<success>");
1193
        out.println("Document deleted."); 
1194
        out.println("</success>");
1195
      } catch (AccessionNumberException ane) {
1196
        response.setContentType("text/xml");
1197
        out.println("<?xml version=\"1.0\"?>");
1198
        out.println("<error>");
1199
        out.println("Error deleting document!!!");
1200
        out.println(ane.getMessage()); 
1201
        out.println("</error>");
1202
      }
1203
    } catch (Exception e) {
1204
      response.setContentType("text/xml");
1205
      out.println("<?xml version=\"1.0\"?>");
1206
      out.println("<error>");
1207
      out.println(e.getMessage()); 
1208
      out.println("</error>");
1209
    } finally {
1210
      util.returnConnection(conn);
1211
    }  
1212
  }
1213
  // END OF DELETE SECTION
1214
  
1215
  // VALIDATE SECTION
1216
  /** 
1217
   * Handle the validation request and return the results to the requestor
1218
   */
1219
  private void handleValidateAction(PrintWriter out, Hashtable params, 
1220
               HttpServletResponse response) {
1221

    
1222
    // Get the document indicated
1223
    String valtext = null;
1224
    
1225
    try {
1226
      valtext = ((String[])params.get("valtext"))[0];
1227
    } catch (Exception nullpe) {
1228

    
1229
      Connection conn = null;
1230
      String docid = null;
1231
      try {
1232
        // Find the document id number
1233
        docid = ((String[])params.get("docid"))[0]; 
1234

    
1235
        // get a connection from the pool
1236
        conn = util.getConnection();
1237

    
1238
        // Get the document indicated from the db
1239
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1240
        valtext = xmldoc.toString();
1241

    
1242
      } catch (NullPointerException npe) {
1243
        response.setContentType("text/xml");
1244
        out.println("<error>Error getting document ID: " + docid + "</error>");
1245
        if ( conn != null ) { util.returnConnection(conn); }
1246
        return;
1247
      } catch (Exception e) {
1248
        response.setContentType("text/html");
1249
        out.println(e.getMessage()); 
1250
      } finally {
1251
        util.returnConnection(conn);
1252
      }  
1253
    }
1254

    
1255
    Connection conn = null;
1256
    try {
1257
      // get a connection from the pool
1258
      conn = util.getConnection();
1259
      DBValidate valobj = new DBValidate(saxparser,conn);
1260
      boolean valid = valobj.validateString(valtext);
1261

    
1262
      // set content type and other response header fields first
1263
      response.setContentType("text/xml");
1264
      out.println(valobj.returnErrors());
1265

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

    
1330
    Connection conn = null;
1331
    String docid = ((String[])params.get("docid"))[0];
1332
    
1333
    try {
1334

    
1335
        // get connection from the pool
1336
        conn = util.getConnection();
1337
        AccessControlList aclobj = new AccessControlList(conn);
1338
        String acltext = aclobj.getACL(docid, username, groupname);
1339
        out.println(acltext);
1340

    
1341
    } catch (Exception e) {
1342
      out.println("<?xml version=\"1.0\"?>");
1343
      out.println("<error>");
1344
      out.println(e.getMessage());
1345
      out.println("</error>");
1346
    } finally {
1347
      util.returnConnection(conn);
1348
    }  
1349
    
1350
  }
1351

    
1352
  /** 
1353
   * Handle the "getprincipals" action.
1354
   * Read all principals from authentication scheme in XML format
1355
   */
1356
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1357
                                         String password) {
1358

    
1359
    Connection conn = null;
1360

    
1361
    try {
1362

    
1363
        // get connection from the pool
1364
        AuthSession auth = new AuthSession();
1365
        String principals = auth.getPrincipals(user, password);
1366
        out.println(principals);
1367

    
1368
    } catch (Exception e) {
1369
      out.println("<?xml version=\"1.0\"?>");
1370
      out.println("<error>");
1371
      out.println(e.getMessage());
1372
      out.println("</error>");
1373
    } finally {
1374
      util.returnConnection(conn);
1375
    }  
1376
    
1377
  }
1378

    
1379
  /** 
1380
   * Handle "getdoctypes" action.
1381
   * Read all doctypes from db connection in XML format
1382
   */
1383
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1384
                                       HttpServletResponse response) {
1385

    
1386
    Connection conn = null;
1387
    
1388
    try {
1389

    
1390
        // get connection from the pool
1391
        conn = util.getConnection();
1392
        DBUtil dbutil = new DBUtil(conn);
1393
        String doctypes = dbutil.readDoctypes();
1394
        out.println(doctypes);
1395

    
1396
    } catch (Exception e) {
1397
      out.println("<?xml version=\"1.0\"?>");
1398
      out.println("<error>");
1399
      out.println(e.getMessage());
1400
      out.println("</error>");
1401
    } finally {
1402
      util.returnConnection(conn);
1403
    }  
1404
    
1405
  }
1406

    
1407
  /** 
1408
   * Handle the "getdtdschema" action.
1409
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1410
   */
1411
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1412
                                        HttpServletResponse response) {
1413

    
1414
    Connection conn = null;
1415
    String doctype = null;
1416
    String[] doctypeArr = (String[])params.get("doctype");
1417

    
1418
    // get only the first doctype specified in the list of doctypes
1419
    // it could be done for all doctypes in that list
1420
    if (doctypeArr != null) {
1421
        doctype = ((String[])params.get("doctype"))[0]; 
1422
    }
1423

    
1424
    try {
1425

    
1426
        // get connection from the pool
1427
        conn = util.getConnection();
1428
        DBUtil dbutil = new DBUtil(conn);
1429
        String dtdschema = dbutil.readDTDSchema(doctype);
1430
        out.println(dtdschema);
1431

    
1432
    } catch (Exception e) {
1433
      out.println("<?xml version=\"1.0\"?>");
1434
      out.println("<error>");
1435
      out.println(e.getMessage());
1436
      out.println("</error>");
1437
    } finally {
1438
      util.returnConnection(conn);
1439
    }  
1440
    
1441
  }
1442

    
1443
  /** 
1444
   * Handle the "getdataguide" action.
1445
   * Read Data Guide for a given doctype from db connection in XML format
1446
   */
1447
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1448
                                        HttpServletResponse response) {
1449

    
1450
    Connection conn = null;
1451
    String doctype = null;
1452
    String[] doctypeArr = (String[])params.get("doctype");
1453

    
1454
    // get only the first doctype specified in the list of doctypes
1455
    // it could be done for all doctypes in that list
1456
    if (doctypeArr != null) {
1457
        doctype = ((String[])params.get("doctype"))[0]; 
1458
    }
1459

    
1460
    try {
1461

    
1462
        // get connection from the pool
1463
        conn = util.getConnection();
1464
        DBUtil dbutil = new DBUtil(conn);
1465
        String dataguide = dbutil.readDataGuide(doctype);
1466
        out.println(dataguide);
1467

    
1468
    } catch (Exception e) {
1469
      out.println("<?xml version=\"1.0\"?>");
1470
      out.println("<error>");
1471
      out.println(e.getMessage());
1472
      out.println("</error>");
1473
    } finally {
1474
      util.returnConnection(conn);
1475
    }  
1476
    
1477
  }
1478

    
1479
}
(32-32/43)