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-21 13:51:10 -0700 (Mon, 21 May 2001) $'
11
 * '$Revision: 743 $'
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("returndoctype"))
485
    {
486
      returndoc = (String[])params.get("returndoctype");
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("returndoctype"))
519
    {
520
      returndoc = (String[])params.get("returndoctype");
521
      if (((String)returndoc[0]).equals("any") ||
522
          ((String)returndoc[0]).equals("ANY") ||
523
          ((String)returndoc[0]).equals("")) {
524
        returndoc = null;
525
      }
526
    }
527
    String xmlquery = DBQuery.createSQuery(params);
528
    Hashtable doclist = runQuery(xmlquery, user, group, returndoc);
529
    String qformat = ((String[])params.get("qformat"))[0];
530
    String resultdoc = null;
531
    
532
    resultdoc = createResultDocument(doclist, transformQuery(params));
533

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

    
657
    if(doclist != null)
658
    {
659
      Enumeration doclistkeys = doclist.keys(); 
660
      while (doclistkeys.hasMoreElements()) 
661
      {
662
        docid = (String)doclistkeys.nextElement();
663
        document = (String)doclist.get(docid);
664
        resultset.append("  <document>" + document + "</document>");
665
      }
666
    }
667

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

    
722
          URL murl = new URL(docs[i]);
723
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
724
          // case docid="http://.../?docid=aaa" 
725
          // or docid="metacat://.../?docid=bbb"
726
          if (murlQueryStr.containsKey("docid")) {
727
            // get only docid, eliminate the rest
728
            docid = (String)murlQueryStr.get("docid");
729
            if ( zip ) {
730
              addDocToZip(docid, zout);
731
            } else {
732
              readFromMetacat(response, docid, qformat, abstrpath,
733
                              user, group, zip, zout);
734
            }
735

    
736
          // case docid="http://.../filename"
737
          } else {
738
            docid = docs[i];
739
            if ( zip ) {
740
              addDocToZip(docid, zout);
741
            } else {
742
              readFromURLConnection(response, docid);
743
            }
744
          }
745

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

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

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

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

    
924
    try {
925
      URL url = new URL(docid);
926

    
927
      // this http url; read from URLConnection; add to zip
928
      zentry = new ZipEntry(docid);
929
      zout.putNextEntry(zentry);
930
      BufferedInputStream bis = null;
931
      try {
932
        bis = new BufferedInputStream(url.openStream());
933
        byte[] buf = new byte[4 * 1024]; // 4K buffer
934
        int b = bis.read(buf);
935
        while(b != -1) {
936
          zout.write(buf, 0, b);
937
          b = bis.read(buf);
938
        }
939
      } finally {
940
        if (bis != null) bis.close();
941
      }
942
      zout.closeEntry();
943

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

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

    
1013
    } finally {
1014
      util.returnConnection(conn);
1015
    }
1016
  }
1017
  // END OF READ SECTION
1018
    
1019
  // INSERT/UPDATE SECTION
1020
  /** 
1021
   * Handle the database putdocument request and write an XML document 
1022
   * to the database connection
1023
   */
1024
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
1025
               HttpServletResponse response, String user, String group) {
1026

    
1027
    Connection conn = null;
1028

    
1029
    try {
1030
      // Get the document indicated
1031
      String[] doctext = (String[])params.get("doctext");
1032

    
1033
      String pub = null;
1034
      if (params.containsKey("public")) {
1035
        pub = ((String[])params.get("public"))[0];
1036
      }
1037

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

    
1056
        String[] action = (String[])params.get("action");
1057
        String[] docid = (String[])params.get("docid");
1058
        String newdocid = null;
1059

    
1060
        String doAction = null;
1061
        if (action[0].equals("insert")) {
1062
          doAction = "INSERT";
1063
        } else if (action[0].equals("update")) {
1064
          doAction = "UPDATE";
1065
        }
1066

    
1067
        try {
1068
          // get a connection from the pool
1069
          conn = util.getConnection();
1070

    
1071
          // write the document to the database
1072
          try {
1073
            String accNumber = docid[0];
1074
            if (accNumber.equals("")) {
1075
              accNumber = null;
1076
            }
1077
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1078
                                          accNumber, user, group, validate);
1079
          } catch (NullPointerException npe) {
1080
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1081
                                          null, user, group, validate);
1082
          }
1083
        } finally {
1084
          util.returnConnection(conn);
1085
        }    
1086

    
1087
        // set content type and other response header fields first
1088
        response.setContentType("text/xml");
1089
        out.println("<?xml version=\"1.0\"?>");
1090
        out.println("<success>");
1091
        out.println("<docid>" + newdocid + "</docid>"); 
1092
        out.println("</success>");
1093

    
1094
      } catch (NullPointerException npe) {
1095
        response.setContentType("text/xml");
1096
        out.println("<?xml version=\"1.0\"?>");
1097
        out.println("<error>");
1098
        out.println(npe.getMessage()); 
1099
        out.println("</error>");
1100
      }
1101
    } catch (Exception e) {
1102
      response.setContentType("text/xml");
1103
      out.println("<?xml version=\"1.0\"?>");
1104
      out.println("<error>");
1105
      out.println(e.getMessage()); 
1106
      if (e instanceof SAXException) {
1107
        Exception e2 = ((SAXException)e).getException();
1108
        out.println("<error>");
1109
        out.println(e2.getMessage()); 
1110
        out.println("</error>");
1111
      }
1112
      //e.printStackTrace(out);
1113
      out.println("</error>");
1114
    }
1115
  }
1116

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

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

    
1158
    // close the stream
1159
    xmlreader.close();
1160

    
1161
    // check the stack whether it contains the keywords:
1162
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1163
    if ( st.size() == 4 ) {
1164
      if ( ((String)st.pop()).equals(">") &&
1165
           ( ((String)st.peek()).equals("PUBLIC") |
1166
             ((String)st.pop()).equals("SYSTEM") ) &&
1167
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1168
        validate = true;
1169
      }
1170
    }
1171

    
1172
System.out.println("Validation is " + validate);
1173
    return validate;
1174
  }
1175
  // END OF INSERT/UPDATE SECTION
1176

    
1177
  // DELETE SECTION
1178
  /** 
1179
   * Handle the database delete request and delete an XML document 
1180
   * from the database connection
1181
   */
1182
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1183
               HttpServletResponse response, String user, String group) {
1184

    
1185
    String[] docid = (String[])params.get("docid");
1186
    Connection conn = null;
1187

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

    
1229
    // Get the document indicated
1230
    String valtext = null;
1231
    
1232
    try {
1233
      valtext = ((String[])params.get("valtext"))[0];
1234
    } catch (Exception nullpe) {
1235

    
1236
      Connection conn = null;
1237
      String docid = null;
1238
      try {
1239
        // Find the document id number
1240
        docid = ((String[])params.get("docid"))[0]; 
1241

    
1242
        // get a connection from the pool
1243
        conn = util.getConnection();
1244

    
1245
        // Get the document indicated from the db
1246
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1247
        valtext = xmldoc.toString();
1248

    
1249
      } catch (NullPointerException npe) {
1250
        response.setContentType("text/xml");
1251
        out.println("<error>Error getting document ID: " + docid + "</error>");
1252
        if ( conn != null ) { util.returnConnection(conn); }
1253
        return;
1254
      } catch (Exception e) {
1255
        response.setContentType("text/html");
1256
        out.println(e.getMessage()); 
1257
      } finally {
1258
        util.returnConnection(conn);
1259
      }  
1260
    }
1261

    
1262
    Connection conn = null;
1263
    try {
1264
      // get a connection from the pool
1265
      conn = util.getConnection();
1266
      DBValidate valobj = new DBValidate(saxparser,conn);
1267
      boolean valid = valobj.validateString(valtext);
1268

    
1269
      // set content type and other response header fields first
1270
      response.setContentType("text/xml");
1271
      out.println(valobj.returnErrors());
1272

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

    
1337
    Connection conn = null;
1338
    String docid = ((String[])params.get("docid"))[0];
1339
    
1340
    try {
1341

    
1342
        // get connection from the pool
1343
        conn = util.getConnection();
1344
        AccessControlList aclobj = new AccessControlList(conn);
1345
        String acltext = aclobj.getACL(docid, username, groupname);
1346
        out.println(acltext);
1347

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

    
1359
  /** 
1360
   * Handle the "getprincipals" action.
1361
   * Read all principals from authentication scheme in XML format
1362
   */
1363
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1364
                                         String password) {
1365

    
1366
    Connection conn = null;
1367

    
1368
    try {
1369

    
1370
        // get connection from the pool
1371
        AuthSession auth = new AuthSession();
1372
        String principals = auth.getPrincipals(user, password);
1373
        out.println(principals);
1374

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

    
1386
  /** 
1387
   * Handle "getdoctypes" action.
1388
   * Read all doctypes from db connection in XML format
1389
   */
1390
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1391
                                       HttpServletResponse response) {
1392

    
1393
    Connection conn = null;
1394
    
1395
    try {
1396

    
1397
        // get connection from the pool
1398
        conn = util.getConnection();
1399
        DBUtil dbutil = new DBUtil(conn);
1400
        String doctypes = dbutil.readDoctypes();
1401
        out.println(doctypes);
1402

    
1403
    } catch (Exception e) {
1404
      out.println("<?xml version=\"1.0\"?>");
1405
      out.println("<error>");
1406
      out.println(e.getMessage());
1407
      out.println("</error>");
1408
    } finally {
1409
      util.returnConnection(conn);
1410
    }  
1411
    
1412
  }
1413

    
1414
  /** 
1415
   * Handle the "getdtdschema" action.
1416
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1417
   */
1418
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1419
                                        HttpServletResponse response) {
1420

    
1421
    Connection conn = null;
1422
    String doctype = null;
1423
    String[] doctypeArr = (String[])params.get("doctype");
1424

    
1425
    // get only the first doctype specified in the list of doctypes
1426
    // it could be done for all doctypes in that list
1427
    if (doctypeArr != null) {
1428
        doctype = ((String[])params.get("doctype"))[0]; 
1429
    }
1430

    
1431
    try {
1432

    
1433
        // get connection from the pool
1434
        conn = util.getConnection();
1435
        DBUtil dbutil = new DBUtil(conn);
1436
        String dtdschema = dbutil.readDTDSchema(doctype);
1437
        out.println(dtdschema);
1438

    
1439
    } catch (Exception e) {
1440
      out.println("<?xml version=\"1.0\"?>");
1441
      out.println("<error>");
1442
      out.println(e.getMessage());
1443
      out.println("</error>");
1444
    } finally {
1445
      util.returnConnection(conn);
1446
    }  
1447
    
1448
  }
1449

    
1450
  /** 
1451
   * Handle the "getdataguide" action.
1452
   * Read Data Guide for a given doctype from db connection in XML format
1453
   */
1454
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1455
                                        HttpServletResponse response) {
1456

    
1457
    Connection conn = null;
1458
    String doctype = null;
1459
    String[] doctypeArr = (String[])params.get("doctype");
1460

    
1461
    // get only the first doctype specified in the list of doctypes
1462
    // it could be done for all doctypes in that list
1463
    if (doctypeArr != null) {
1464
        doctype = ((String[])params.get("doctype"))[0]; 
1465
    }
1466

    
1467
    try {
1468

    
1469
        // get connection from the pool
1470
        conn = util.getConnection();
1471
        DBUtil dbutil = new DBUtil(conn);
1472
        String dataguide = dbutil.readDataGuide(doctype);
1473
        out.println(dataguide);
1474

    
1475
    } catch (Exception e) {
1476
      out.println("<?xml version=\"1.0\"?>");
1477
      out.println("<error>");
1478
      out.println(e.getMessage());
1479
      out.println("</error>");
1480
    } finally {
1481
      util.returnConnection(conn);
1482
    }  
1483
    
1484
  }
1485

    
1486
}
(32-32/43)