Project

General

Profile

1 51 jones
/**
2 203 jones
 *  '$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 361 berkley
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7 348 jones
 *    Release: @release@
8 154 jones
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
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 51 jones
 */
27
28
package edu.ucsb.nceas.metacat;
29
30 733 bojilova
import java.io.File;
31 46 jones
import java.io.PrintWriter;
32
import java.io.IOException;
33 50 jones
import java.io.StringReader;
34 185 jones
import java.io.FileInputStream;
35 731 bojilova
import java.io.BufferedInputStream;
36 46 jones
import java.util.Enumeration;
37
import java.util.Hashtable;
38 341 berkley
import java.util.ResourceBundle;
39 648 berkley
import java.util.Random;
40 82 jones
import java.util.PropertyResourceBundle;
41 50 jones
import java.net.URL;
42
import java.net.MalformedURLException;
43 85 jones
import java.sql.PreparedStatement;
44
import java.sql.ResultSet;
45 50 jones
import java.sql.Connection;
46 55 jones
import java.sql.SQLException;
47 361 berkley
import java.lang.reflect.*;
48 453 berkley
import java.net.*;
49 458 berkley
import java.util.zip.*;
50 46 jones
51
import javax.servlet.ServletConfig;
52
import javax.servlet.ServletContext;
53
import javax.servlet.ServletException;
54 48 jones
import javax.servlet.ServletInputStream;
55 46 jones
import javax.servlet.http.HttpServlet;
56
import javax.servlet.http.HttpServletRequest;
57
import javax.servlet.http.HttpServletResponse;
58 210 bojilova
import javax.servlet.http.HttpSession;
59 47 jones
import javax.servlet.http.HttpUtils;
60 458 berkley
import javax.servlet.ServletOutputStream;
61 46 jones
62 50 jones
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 204 jones
import org.xml.sax.SAXException;
68
69 46 jones
/**
70
 * A metadata catalog server implemented as a Java Servlet
71 154 jones
 *
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 205 jones
 * action=squery -- structured query (see pathquery.dtd)<br>
76 731 bojilova
 * action=read -- read any metadata/data file from Metacat and from Internet<br>
77 205 jones
 * 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 154 jones
 * qformat=xml -- display resultset from query in XML<br>
83
 * qformat=html -- display resultset from query in HTML<br>
84 731 bojilova
 * qformat=zip -- zip resultset from query<br>
85 154 jones
 * docid=34 -- display the document with the document ID number 34<br>
86 205 jones
 * doctext -- XML text of the document to load into the database<br>
87 598 bojilova
 * 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 183 jones
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
90 205 jones
 * valtext -- XML text to be validated<br>
91 731 bojilova
 * abstractpath -- XPath in metadata document to read from<br>
92 688 bojilova
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
93
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
94 699 bojilova
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
95 688 bojilova
 * action=getdataguide -- retrieve a Data Guide<br>
96 725 bojilova
 * action=getprincipals -- retrieve a list of principals in XML<br>
97 205 jones
 * 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 46 jones
 */
103
public class MetaCatServlet extends HttpServlet {
104
105 370 berkley
  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 380 jones
  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 370 berkley
  private String htmlpath = null;
119 380 jones
  // script to get data file and put it
120
  // in defaultdocpath dir
121 370 berkley
  private String executescript  = null;
122 46 jones
123 50 jones
  /**
124
   * Initialize the servlet by creating appropriate database connections
125
   */
126 46 jones
  public void init( ServletConfig config ) throws ServletException {
127
    try {
128
      super.init( config );
129
      this.config = config;
130 332 bojilova
      this.context = config.getServletContext();
131 184 jones
      System.out.println("MetaCatServlet Initialize");
132 82 jones
133 184 jones
      util = new MetaCatUtil();
134
135 83 jones
      // Get the configuration file information
136 184 jones
      resultStyleURL = util.getOption("resultStyleURL");
137
      xmlcatalogfile = util.getOption("xmlcatalogfile");
138
      saxparser = util.getOption("saxparser");
139
      defaultdatapath = util.getOption("defaultdatapath");
140 593 berkley
      executescript = util.getOption("executescript");
141 360 bojilova
      servletpath = util.getOption("servletpath");
142
      htmlpath = util.getOption("htmlpath");
143 598 bojilova
144 731 bojilova
// MOVED IT TO doGet() & doPost()
145 598 bojilova
//      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 46 jones
    } catch ( ServletException ex ) {
153
      throw ex;
154
    }
155
  }
156
157 320 bojilova
  /**
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 50 jones
  /** Handle "GET" method requests from HTTP clients */
168 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
169
    throws ServletException, IOException {
170
171 48 jones
    // Process the data and send back the response
172 59 jones
    handleGetOrPost(request, response);
173 48 jones
  }
174
175 50 jones
  /** Handle "POST" method requests from HTTP clients */
176 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
177
    throws ServletException, IOException {
178
179
    // Process the data and send back the response
180 59 jones
    handleGetOrPost(request, response);
181 48 jones
  }
182
183 49 jones
  /**
184 50 jones
   * Control servlet response depending on the action parameter specified
185 49 jones
   */
186 382 berkley
  private void handleGetOrPost(HttpServletRequest request,
187 59 jones
    HttpServletResponse response)
188 355 berkley
    throws ServletException, IOException
189
 {
190 48 jones
191 309 bojilova
    if ( util == null ) {
192
        util = new MetaCatUtil();
193
    }
194 598 bojilova
    if ( connectionPool.isEmpty() ) {
195 309 bojilova
      try {
196
        // Open a pool of db connections
197
        connectionPool = util.getConnectionPool();
198
      } catch (Exception e) {
199 675 berkley
        System.err.println("Error creating pool of database connections in " +
200
                            " MetaCatServlet.handleGetOrPost");
201 309 bojilova
        System.err.println(e.getMessage());
202
      }
203
    }
204 49 jones
    // Get a handle to the output stream back to the client
205 566 jones
    //PrintWriter pwout = response.getWriter();
206 102 jones
    //response.setContentType("text/html");
207 49 jones
208 59 jones
    String name = null;
209
    String[] value = null;
210 103 jones
    String[] docid = new String[3];
211 59 jones
    Hashtable params = new Hashtable();
212
    Enumeration paramlist = request.getParameterNames();
213
    while (paramlist.hasMoreElements()) {
214
      name = (String)paramlist.nextElement();
215
      value = request.getParameterValues(name);
216 103 jones
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 373 berkley
      }
226 103 jones
227 373 berkley
      params.put(name,value);
228
    }
229 355 berkley
230 509 bojilova
    //if the user clicked on the input images, decode which image
231
    //was clicked then set the action.
232 505 jones
    String action = ((String[])params.get("action"))[0];
233
    util.debugMessage("Line 213: Action is: " + action);
234 509 bojilova
235 380 jones
    // This block handles session management for the servlet
236
    // by looking up the current session information for all actions
237 509 bojilova
    // other than "login" and "logout"
238 425 bojilova
    String username = null;
239 725 bojilova
    String password = null;
240 425 bojilova
    String groupname = null;
241 648 berkley
    String sess_id = null;
242 509 bojilova
243
    // handle login action
244
    if (action.equals("login")) {
245
246 458 berkley
      handleLoginAction(response.getWriter(), params, request, response);
247 509 bojilova
248 210 bojilova
    // handle logout action
249 509 bojilova
    } else if (action.equals("logout")) {
250 361 berkley
251 509 bojilova
      handleLogoutAction(response.getWriter(), params, request, response);
252 361 berkley
253 251 bojilova
    // aware of session expiration on every request
254 343 jones
    } else {
255 509 bojilova
256 332 bojilova
      HttpSession sess = request.getSession(true);
257
      if (sess.isNew()) {
258 251 bojilova
        // session expired or has not been stored b/w user requests
259 441 bojilova
        username = "public";
260 673 bojilova
        sess.setAttribute("username", username);
261 425 bojilova
      } else {
262
        username = (String)sess.getAttribute("username");
263 725 bojilova
        password = (String)sess.getAttribute("password");
264 425 bojilova
        groupname = (String)sess.getAttribute("groupname");
265 731 bojilova
        try {
266 648 berkley
          sess_id = (String)sess.getId();
267 731 bojilova
        } catch(IllegalStateException ise) {
268 648 berkley
          System.out.println("error in handleGetOrPost: this shouldn't " +
269
                             "happen: the session should be valid: " +
270
                             ise.getMessage());
271
        }
272 425 bojilova
      }
273 210 bojilova
    }
274 219 jones
275 380 jones
    // Now that we know the session is valid, we can delegate the request
276
    // to a particular action handler
277 731 bojilova
    if(action.equals("query")) {
278 458 berkley
      handleQuery(response.getWriter(), params, response, username, groupname);
279 731 bojilova
    } else if(action.equals("squery")) {
280
      if(params.containsKey("query")) {
281 458 berkley
        handleSQuery(response.getWriter(), params, response, username, groupname);
282 731 bojilova
      } else {
283 458 berkley
        PrintWriter out = response.getWriter();
284 373 berkley
        out.println("Illegal action squery without \"query\" parameter");
285
      }
286 731 bojilova
    } else if (action.equals("read")) {
287
      handleReadAction(params, response, username, groupname);
288
    } else if (action.equals("insert") || action.equals("update")) {
289 458 berkley
      PrintWriter out = response.getWriter();
290 509 bojilova
      if ( (username != null) &&  !username.equals("public") ) {
291 425 bojilova
        handleInsertOrUpdateAction(out, params, response, username, groupname);
292
      } else {
293
        out.println("Permission denied for " + action);
294
      }
295 203 jones
    } else if (action.equals("delete")) {
296 458 berkley
      PrintWriter out = response.getWriter();
297 509 bojilova
      if ( (username != null) &&  !username.equals("public") ) {
298 425 bojilova
        handleDeleteAction(out, params, response, username, groupname);
299
      } else {
300
        out.println("Permission denied for " + action);
301
      }
302 68 higgins
    } else if (action.equals("validate")) {
303 458 berkley
      PrintWriter out = response.getWriter();
304 437 berkley
      handleValidateAction(out, params, response);
305 648 berkley
    } else if (action.equals("getdataport")) {
306
      PrintWriter out = response.getWriter();
307 649 berkley
      if ( (username != null) &&  !username.equals("public") ) {
308 648 berkley
      handleGetDataPortAction(out, params, response, username, groupname,
309
                              sess_id);
310 649 berkley
      } else {
311
        out.println("You must be authenticated to perform the getdataport " +
312
                    "action!");
313
      }
314 731 bojilova
    } 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 699 bojilova
    } else if (action.equals("getdtdschema")) {
324
      PrintWriter out = response.getWriter();
325
      handleGetDTDSchemaAction(out, params, response);
326 302 bojilova
    } else if (action.equals("getdataguide")) {
327 458 berkley
      PrintWriter out = response.getWriter();
328 302 bojilova
      handleGetDataGuideAction(out, params, response);
329 509 bojilova
    } else if (action.equals("login") || action.equals("logout")) {
330 566 jones
    } 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 675 berkley
        System.out.println("bad url from MetacatServlet.handleGetOrPost");
367 566 jones
        out.println(mue.getMessage());
368
        mue.printStackTrace(out);
369
        out.close();
370
      }
371 50 jones
    } else {
372 458 berkley
      PrintWriter out = response.getWriter();
373 50 jones
      out.println("Error: action not registered.  Please report this error.");
374 46 jones
    }
375 731 bojilova
376 465 berkley
    util.closeConnections();
377 49 jones
    // Close the stream to the client
378 731 bojilova
    // out.close();
379 46 jones
  }
380 355 berkley
381 731 bojilova
  // LOGIN & LOGOUT SECTION
382 50 jones
  /**
383 509 bojilova
   * Handle the login request. Create a new session object.
384 503 bojilova
   * Do user authentication through the session.
385 210 bojilova
   */
386
  private void handleLoginAction(PrintWriter out, Hashtable params,
387
               HttpServletRequest request, HttpServletResponse response) {
388 251 bojilova
389 503 bojilova
    AuthSession sess = null;
390 228 bojilova
    String un = ((String[])params.get("username"))[0];
391
    String pw = ((String[])params.get("password"))[0];
392 297 bojilova
    String action = ((String[])params.get("action"))[0];
393 509 bojilova
    String qformat = ((String[])params.get("qformat"))[0];
394 332 bojilova
395 297 bojilova
    try {
396 509 bojilova
      sess = new AuthSession();
397 297 bojilova
    } catch (Exception e) {
398 675 berkley
      System.out.println("error in MetacatServlet.handleLoginAction: " +
399
                          e.getMessage());
400 297 bojilova
      out.println(e.getMessage());
401 509 bojilova
      return;
402 297 bojilova
    }
403 411 bojilova
404 509 bojilova
    boolean isValid = sess.authenticate(request, un, pw);
405
406
    // format and transform the output
407
    if (qformat.equals("html")) {
408
      Connection conn = null;
409 503 bojilova
      try {
410 509 bojilova
        conn = util.getConnection();
411
        DBTransform trans = new DBTransform(conn);
412
        response.setContentType("text/html");
413 510 bojilova
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
414
                                   "-//W3C//HTML//EN", out);
415 509 bojilova
        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 503 bojilova
    }
425 370 berkley
  }
426 509 bojilova
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 510 bojilova
    output.append("<logout>");
443
    output.append("User logged out");
444
    output.append("</logout>");
445 509 bojilova
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 510 bojilova
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
454
                                   "-//W3C//HTML//EN", out);
455 509 bojilova
        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 731 bojilova
  // END OF LOGIN & LOGOUT SECTION
466 370 berkley
467 731 bojilova
  // SQUERY & QUERY SECTION
468 373 berkley
  /**
469 380 jones
   * 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 441 bojilova
                 HttpServletResponse response, String user, String group)
479 373 berkley
  {
480 380 jones
    String xmlquery = ((String[])params.get("query"))[0];
481
    String qformat = ((String[])params.get("qformat"))[0];
482 465 berkley
    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 444 berkley
492 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
493
494 380 jones
    //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 341 berkley
  }
504
505
   /**
506 380 jones
    * 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 370 berkley
    * in the squery.
511 380 jones
    * @param response the response object linked to the client
512 370 berkley
    */
513 375 berkley
  protected void handleQuery(PrintWriter out, Hashtable params,
514 441 bojilova
                 HttpServletResponse response, String user, String group)
515 341 berkley
  {
516 370 berkley
    //create the query and run it
517 465 berkley
    String[] returndoc = null;
518
    if(params.containsKey("returndoc"))
519
    {
520
      returndoc = (String[])params.get("returndoc");
521
    }
522 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
523 465 berkley
    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 425 bojilova
529 370 berkley
    //format and transform the results
530 380 jones
    if(qformat.equals("html")) {
531 370 berkley
      transformResultset(resultdoc, response, out);
532 380 jones
    } else if(qformat.equals("xml")) {
533 370 berkley
      response.setContentType("text/xml");
534
      out.println(resultdoc);
535 443 berkley
    } else {
536 370 berkley
      out.println("invalid qformat: " + qformat);
537
    }
538 341 berkley
  }
539
540
  /**
541 384 berkley
   * 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 443 berkley
   * 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 380 jones
   * Run the query and return a hashtable of results.
575
   *
576
   * @param xmlquery the query to run
577
   */
578 465 berkley
  private Hashtable runQuery(String xmlquery, String user, String group,
579
                             String[] returndoc)
580 341 berkley
  {
581
    Hashtable doclist=null;
582
    Connection conn = null;
583
    try
584
    {
585 441 bojilova
      conn = util.getConnection();
586
      DBQuery queryobj = new DBQuery(conn, saxparser);
587 465 berkley
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,group,
588
                                       returndoc);
589 441 bojilova
      util.returnConnection(conn);
590
      return doclist;
591 341 berkley
    }
592
    catch (Exception e)
593
    {
594 441 bojilova
      util.returnConnection(conn);
595 675 berkley
      util.debugMessage("Error in MetacatServlet.runQuery: " + e.getMessage());
596 341 berkley
      doclist = null;
597
      return doclist;
598
    }
599
  }
600
601 380 jones
  /**
602 370 berkley
   * Transorms an xml resultset document to html and sends it to the browser
603 380 jones
   *
604 370 berkley
   * @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 375 berkley
   */
609
  protected void transformResultset(String resultdoc,
610 380 jones
                                    HttpServletResponse response,
611
                                    PrintWriter out)
612 370 berkley
  {
613
    Connection conn = null;
614 380 jones
    try {
615 370 berkley
      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 382 berkley
      util.returnConnection(conn);
621
    }
622
    catch(Exception e)
623
    {
624 441 bojilova
      util.returnConnection(conn);
625 370 berkley
    }
626
  }
627
628 355 berkley
  /**
629
   * Transforms a hashtable of documents to an xml or html result.
630 465 berkley
   * 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 380 jones
   *
635 355 berkley
   * @param doclist- the hashtable to transform
636
   * @param xmlquery- the query that returned the dolist result
637 465 berkley
   * @param resultdoc- the document type to backtrack to.
638 355 berkley
   */
639 375 berkley
  protected String createResultDocument(Hashtable doclist, String xmlquery)
640 341 berkley
  {
641
    // Create a buffer to hold the xml result
642
    StringBuffer resultset = new StringBuffer();
643
644 382 berkley
    // Print the resulting root nodes
645 341 berkley
    String docid = null;
646
    String document = null;
647
    resultset.append("<?xml version=\"1.0\"?>\n");
648
    resultset.append("<resultset>\n");
649 465 berkley
650 384 berkley
    resultset.append("  <query>" + xmlquery + "</query>");
651 478 berkley
652
    if(doclist != null)
653 341 berkley
    {
654 478 berkley
      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 341 berkley
    resultset.append("</resultset>");
664 444 berkley
    //System.out.println(resultset.toString());
665 370 berkley
    return resultset.toString();
666 341 berkley
  }
667 731 bojilova
  // END OF SQUERY & QUERY SECTION
668 437 berkley
669 731 bojilova
  // 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 437 berkley
   */
681 731 bojilova
  private void handleReadAction(Hashtable params, HttpServletResponse response,
682
                                String user, String group)
683 437 berkley
  {
684 731 bojilova
    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 437 berkley
      }
697 731 bojilova
      if (params.containsKey("qformat")) {
698
        qformat = ((String[])params.get("qformat"))[0];
699 437 berkley
      }
700 731 bojilova
      if (params.containsKey("abstractpath")) {
701
        abstrpath = ((String[])params.get("abstractpath"))[0];
702 738 bojilova
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
703
          viewAbstract(response, abstrpath, docs[0]);
704
          return;
705
        }
706 437 berkley
      }
707 731 bojilova
      if ( (docs.length > 1) || qformat.equals("zip") ) {
708
        zip = true;
709
        out = response.getOutputStream();
710
        response.setContentType("application/zip"); //MIME type
711
        zout = new ZipOutputStream(out);
712
      }
713
      // go through the list of docs to read
714
      for (int i=0; i < docs.length; i++ ) {
715
        try {
716
717
          URL murl = new URL(docs[i]);
718
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
719
          // case docid="http://.../?docid=aaa"
720
          // or docid="metacat://.../?docid=bbb"
721
          if (murlQueryStr.containsKey("docid")) {
722
            // get only docid, eliminate the rest
723
            docid = (String)murlQueryStr.get("docid");
724
            if ( zip ) {
725
              addDocToZip(docid, zout);
726
            } else {
727
              readFromMetacat(response, docid, qformat, abstrpath,
728
                              user, group, zip, zout);
729
            }
730
731
          // case docid="http://.../filename"
732
          } else {
733
            docid = docs[i];
734
            if ( zip ) {
735
              addDocToZip(docid, zout);
736
            } else {
737
              readFromURLConnection(response, docid);
738
            }
739
          }
740
741
        // case docid="ccc"
742
        } catch (MalformedURLException mue) {
743
          docid = docs[i];
744
          if ( zip ) {
745
            addDocToZip(docid, zout);
746
          } else {
747
            readFromMetacat(response, docid, qformat, abstrpath,
748
                            user, group, zip, zout);
749
          }
750
        }
751
752
      } /* end for */
753
754
      if ( zip ) {
755
        zout.finish(); //terminate the zip file
756
        zout.close();  //close the zip stream
757
      }
758
759
    } catch (Exception e) {
760
      try {
761
        if ( out != null ) { out.close(); }
762
        if ( zout != null ) { zout.close(); }
763
        response.setContentType("text/xml"); //MIME type
764
        PrintWriter pw = response.getWriter();
765
        pw.println(e.getMessage());
766
      } catch (IOException ioe) {
767
        System.out.println("Problem with the servlet output " +
768
                           "in MetacatServlet.handleReadAction: " +
769
                           ioe.getMessage());
770
        ioe.printStackTrace(System.out);
771
772
      }
773
774
      System.out.println("Error in MetacatServlet.handleReadAction: " +
775 675 berkley
                         e.getMessage());
776 731 bojilova
      e.printStackTrace(System.out);
777 437 berkley
    }
778
779
  }
780 731 bojilova
781
  // read metadata or data from Metacat
782
  private void readFromMetacat(HttpServletResponse response, String docid,
783
                               String qformat, String abstrpath, String user,
784
                               String group, boolean zip, ZipOutputStream zout)
785
               throws ClassNotFoundException, IOException, SQLException,
786
                      McdbException, Exception
787 453 berkley
  {
788
    Connection conn = null;
789 731 bojilova
    try {
790
      conn = util.getConnection();
791
      DocumentImpl doc = new DocumentImpl(conn, docid);
792 453 berkley
793 731 bojilova
      if ( doc.getRootNodeID() == 0 ) {
794
        // this is data file
795
        ServletOutputStream out = response.getOutputStream();
796
        String filepath = util.getOption("datafilepath");
797
        if(!filepath.endsWith("/")) {
798
          filepath += "/";
799
        }
800
        String filename = filepath + doc.getDocname();      //MIME type
801
        String contentType = getServletContext().getMimeType(filename);
802
        if (contentType == null) {
803
          if (filename.endsWith(".xml")) {
804
            contentType="text/xml";
805
          } else if (filename.endsWith(".css")) {
806
            contentType="text/css";
807
          } else if (filename.endsWith(".dtd")) {
808
            contentType="text/plain";
809
          } else if (filename.endsWith(".xsd")) {
810 733 bojilova
            contentType="text/xml";
811 731 bojilova
          } else if (filename.endsWith("/")) {
812 733 bojilova
            contentType="text/html";
813 731 bojilova
          } else {
814 733 bojilova
            File f = new File(filename);
815
            if ( f.isDirectory() ) {
816
              contentType="text/html";
817
            } else {
818
              contentType="application/octet-stream";
819
            }
820 453 berkley
          }
821
        }
822 731 bojilova
        response.setContentType(contentType);
823 733 bojilova
        // if we decide to use "application/octet-stream" for all data returns
824
        // response.setContentType("application/octet-stream");
825 731 bojilova
        FileInputStream fin = null;
826
        try {
827
          fin = new FileInputStream(filename);
828
          byte[] buf = new byte[4 * 1024]; // 4K buffer
829
          int b = fin.read(buf);
830
          while (b != -1) {
831
            out.write(buf, 0, b);
832
            b = fin.read(buf);
833 453 berkley
          }
834 731 bojilova
        } finally {
835
          if (fin != null) fin.close();
836 453 berkley
        }
837 731 bojilova
838
      } else {
839
        // this is metadata doc
840
        if ( qformat.equals("html") ) {
841
          response.setContentType("text/html");  //MIME type
842
          PrintWriter out = response.getWriter();
843
844
          // Look up the document type
845
          String doctype = doc.getDoctype();
846
          // Transform the document to the new doctype
847
          DBTransform dbt = new DBTransform(conn);
848
          dbt.transformXMLDocument(doc.toString(),
849
                                   doctype,"-//W3C//HTML//EN",out);
850
        } else {
851
          // set content type first
852
          response.setContentType("text/xml");   //MIME type
853
          PrintWriter out = response.getWriter();
854
          doc.toXml(out);
855
        }
856
857 453 berkley
      }
858 731 bojilova
    } finally {
859
      util.returnConnection(conn);
860
    }
861
862
  }
863 453 berkley
864 731 bojilova
  // read data from URLConnection
865
  private void readFromURLConnection(HttpServletResponse response, String docid)
866
               throws IOException, MalformedURLException
867 566 jones
  {
868 731 bojilova
    ServletOutputStream out = response.getOutputStream();
869
    String contentType = getServletContext().getMimeType(docid); //MIME type
870
    if (contentType == null) {
871
      if (docid.endsWith(".xml")) {
872
        contentType="text/xml";
873
      } else if (docid.endsWith(".css")) {
874
        contentType="text/css";
875
      } else if (docid.endsWith(".dtd")) {
876
        contentType="text/plain";
877
      } else if (docid.endsWith(".xsd")) {
878 733 bojilova
        contentType="text/xml";
879 731 bojilova
      } else if (docid.endsWith("/")) {
880 733 bojilova
        contentType="text/html";
881 731 bojilova
      } else {
882 733 bojilova
        File f = new File(docid);
883
        if ( f.isDirectory() ) {
884
          contentType="text/html";
885
        } else {
886
          contentType="application/octet-stream";
887
        }
888 731 bojilova
      }
889
    }
890
    response.setContentType(contentType);
891 733 bojilova
    // if we decide to use "application/octet-stream" for all data returns
892
    // response.setContentType("application/octet-stream");
893 731 bojilova
894
    // this is http url
895
    URL url = new URL(docid);
896
    BufferedInputStream bis = null;
897 566 jones
    try {
898 731 bojilova
      bis = new BufferedInputStream(url.openStream());
899
      byte[] buf = new byte[4 * 1024]; // 4K buffer
900
      int b = bis.read(buf);
901
      while (b != -1) {
902
        out.write(buf, 0, b);
903
        b = bis.read(buf);
904 636 berkley
      }
905 731 bojilova
    } finally {
906
      if (bis != null) bis.close();
907 566 jones
    }
908 731 bojilova
909 566 jones
  }
910 636 berkley
911 731 bojilova
  // read file/doc and write to ZipOutputStream
912
  private void addDocToZip(String docid, ZipOutputStream zout)
913
               throws ClassNotFoundException, IOException, SQLException,
914
                      McdbException, Exception
915 636 berkley
  {
916 731 bojilova
    byte[] bytestring = null;
917
    ZipEntry zentry = null;
918
919
    try {
920
      URL url = new URL(docid);
921
922
      // this http url; read from URLConnection; add to zip
923
      zentry = new ZipEntry(docid);
924
      zout.putNextEntry(zentry);
925
      BufferedInputStream bis = null;
926
      try {
927
        bis = new BufferedInputStream(url.openStream());
928
        byte[] buf = new byte[4 * 1024]; // 4K buffer
929
        int b = bis.read(buf);
930
        while(b != -1) {
931
          zout.write(buf, 0, b);
932
          b = bis.read(buf);
933
        }
934
      } finally {
935
        if (bis != null) bis.close();
936 636 berkley
      }
937 731 bojilova
      zout.closeEntry();
938
939
    } catch (MalformedURLException mue) {
940 661 berkley
941 731 bojilova
      // this is metacat doc (data file or metadata doc)
942
      Connection conn = null;
943
      try {
944
        conn = util.getConnection();
945
        DocumentImpl doc = new DocumentImpl(conn, docid);
946 661 berkley
947 731 bojilova
        if ( doc.getRootNodeID() == 0 ) {
948
          // this is data file; add file to zip
949
          String filepath = util.getOption("datafilepath");
950
          if(!filepath.endsWith("/")) {
951
            filepath += "/";
952
          }
953
          String filename = filepath + doc.getDocname();
954
          zentry = new ZipEntry(filename);
955
          zout.putNextEntry(zentry);
956
          FileInputStream fin = null;
957
          try {
958
            fin = new FileInputStream(filename);
959
            byte[] buf = new byte[4 * 1024]; // 4K buffer
960
            int b = fin.read(buf);
961
            while (b != -1) {
962
              zout.write(buf, 0, b);
963
              b = fin.read(buf);
964
            }
965
          } finally {
966
            if (fin != null) fin.close();
967
          }
968
          zout.closeEntry();
969
970
        } else {
971
          // this is metadata doc; add doc to zip
972
          bytestring = doc.toString().getBytes();
973
          zentry = new ZipEntry(docid + ".xml");
974
          zentry.setSize(bytestring.length);
975
          zout.putNextEntry(zentry);
976
          zout.write(bytestring, 0, bytestring.length);
977
          zout.closeEntry();
978 636 berkley
        }
979 731 bojilova
      } finally {
980
        util.returnConnection(conn);
981 636 berkley
      }
982
983
    }
984 731 bojilova
985 636 berkley
  }
986 731 bojilova
987
  // view abstract within document
988
  private void viewAbstract(HttpServletResponse response,
989
                            String abstractpath, String docid)
990
               throws ClassNotFoundException, IOException, SQLException,
991
                      McdbException, Exception
992
  {
993 309 bojilova
    Connection conn = null;
994 102 jones
    try {
995 309 bojilova
      conn = util.getConnection();
996 731 bojilova
997
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
998
999
      response.setContentType("text/html");  //MIME type
1000
      PrintWriter out = response.getWriter();
1001
      out.println("<html><head><title>Abstract</title></head>");
1002
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
1003
      for (int i=0; i<abstracts.length; i++) {
1004
        out.println("<p>" + (String)abstracts[i] + "</p>");
1005
      }
1006
      out.println("</body></html>");
1007 85 jones
1008 309 bojilova
    } finally {
1009 320 bojilova
      util.returnConnection(conn);
1010 731 bojilova
    }
1011 49 jones
  }
1012 731 bojilova
  // END OF READ SECTION
1013
1014
  // INSERT/UPDATE SECTION
1015 55 jones
  /**
1016
   * Handle the database putdocument request and write an XML document
1017
   * to the database connection
1018
   */
1019 382 berkley
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1020 425 bojilova
               HttpServletResponse response, String user, String group) {
1021 59 jones
1022 309 bojilova
    Connection conn = null;
1023
1024 204 jones
    try {
1025
      // Get the document indicated
1026
      String[] doctext = (String[])params.get("doctext");
1027 557 bojilova
1028 680 bojilova
      String pub = null;
1029
      if (params.containsKey("public")) {
1030
        pub = ((String[])params.get("public"))[0];
1031 557 bojilova
      }
1032 680 bojilova
1033 598 bojilova
      StringReader dtd = null;
1034 680 bojilova
      if (params.containsKey("dtdtext")) {
1035 598 bojilova
        String[] dtdtext = (String[])params.get("dtdtext");
1036
        try {
1037 619 bojilova
          if ( !dtdtext[0].equals("") ) {
1038
            dtd = new StringReader(dtdtext[0]);
1039
          }
1040 598 bojilova
        } catch (NullPointerException npe) {}
1041
      }
1042 557 bojilova
1043 204 jones
      StringReader xml = null;
1044 695 bojilova
      boolean validate = false;
1045 204 jones
      try {
1046 695 bojilova
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1047
        // in order to decide whether to use validation parser
1048
        validate = validateXML(doctext[0]);
1049 204 jones
        xml = new StringReader(doctext[0]);
1050 59 jones
1051 204 jones
        String[] action = (String[])params.get("action");
1052
        String[] docid = (String[])params.get("docid");
1053
        String newdocid = null;
1054 203 jones
1055 204 jones
        String doAction = null;
1056
        if (action[0].equals("insert")) {
1057
          doAction = "INSERT";
1058
        } else if (action[0].equals("update")) {
1059
          doAction = "UPDATE";
1060
        }
1061 203 jones
1062 204 jones
        try {
1063 680 bojilova
          // get a connection from the pool
1064
          conn = util.getConnection();
1065 408 jones
1066 680 bojilova
          // write the document to the database
1067
          try {
1068
            String accNumber = docid[0];
1069
            if (accNumber.equals("")) {
1070
              accNumber = null;
1071 309 bojilova
            }
1072 680 bojilova
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1073 695 bojilova
                                          accNumber, user, group, validate);
1074 680 bojilova
          } catch (NullPointerException npe) {
1075
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1076 695 bojilova
                                          null, user, group, validate);
1077 680 bojilova
          }
1078 309 bojilova
        } finally {
1079 320 bojilova
          util.returnConnection(conn);
1080 309 bojilova
        }
1081
1082 204 jones
        // set content type and other response header fields first
1083
        response.setContentType("text/xml");
1084
        out.println("<?xml version=\"1.0\"?>");
1085
        out.println("<success>");
1086
        out.println("<docid>" + newdocid + "</docid>");
1087
        out.println("</success>");
1088
1089 203 jones
      } catch (NullPointerException npe) {
1090 204 jones
        response.setContentType("text/xml");
1091
        out.println("<?xml version=\"1.0\"?>");
1092
        out.println("<error>");
1093
        out.println(npe.getMessage());
1094
        out.println("</error>");
1095 55 jones
      }
1096 204 jones
    } catch (Exception e) {
1097
      response.setContentType("text/xml");
1098
      out.println("<?xml version=\"1.0\"?>");
1099
      out.println("<error>");
1100
      out.println(e.getMessage());
1101
      if (e instanceof SAXException) {
1102
        Exception e2 = ((SAXException)e).getException();
1103
        out.println("<error>");
1104
        out.println(e2.getMessage());
1105
        out.println("</error>");
1106
      }
1107
      //e.printStackTrace(out);
1108
      out.println("</error>");
1109 203 jones
    }
1110 55 jones
  }
1111 203 jones
1112
  /**
1113 695 bojilova
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1114
   * in order to decide whether to use validation parser
1115
   */
1116
  private static boolean validateXML(String xmltext) throws IOException {
1117
1118
    StringReader xmlreader = new StringReader(xmltext);
1119
    StringBuffer cbuff = new StringBuffer();
1120
    java.util.Stack st = new java.util.Stack();
1121
    boolean validate = false;
1122
    int c;
1123
    int inx;
1124
1125
    // read from the stream until find the keywords
1126
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1127
      cbuff.append((char)c);
1128
1129
      // "<!DOCTYPE" keyword is found; put it in the stack
1130
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1131
        cbuff = new StringBuffer();
1132
        st.push("<!DOCTYPE");
1133
      }
1134
      // "PUBLIC" keyword is found; put it in the stack
1135
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1136
        cbuff = new StringBuffer();
1137
        st.push("PUBLIC");
1138
      }
1139
      // "SYSTEM" keyword is found; put it in the stack
1140
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1141
        cbuff = new StringBuffer();
1142
        st.push("SYSTEM");
1143
      }
1144
      // ">" character is found; put it in the stack
1145
      // ">" is found twice: fisrt from <?xml ...?>
1146
      // and second from <!DOCTYPE ... >
1147
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1148
        cbuff = new StringBuffer();
1149
        st.push(">");
1150
      }
1151
    }
1152
1153
    // close the stream
1154
    xmlreader.close();
1155
1156
    // check the stack whether it contains the keywords:
1157
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1158
    if ( st.size() == 4 ) {
1159
      if ( ((String)st.pop()).equals(">") &&
1160
           ( ((String)st.peek()).equals("PUBLIC") |
1161
             ((String)st.pop()).equals("SYSTEM") ) &&
1162
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1163
        validate = true;
1164
      }
1165
    }
1166
1167
System.out.println("Validation is " + validate);
1168
    return validate;
1169
  }
1170 731 bojilova
  // END OF INSERT/UPDATE SECTION
1171 695 bojilova
1172 731 bojilova
  // DELETE SECTION
1173 695 bojilova
  /**
1174 203 jones
   * Handle the database delete request and delete an XML document
1175
   * from the database connection
1176
   */
1177
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1178 425 bojilova
               HttpServletResponse response, String user, String group) {
1179 203 jones
1180
    String[] docid = (String[])params.get("docid");
1181 309 bojilova
    Connection conn = null;
1182 203 jones
1183
    // delete the document from the database
1184
    try {
1185 309 bojilova
      // get a connection from the pool
1186
      conn = util.getConnection();
1187 203 jones
                                      // NOTE -- NEED TO TEST HERE
1188 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
1189 203 jones
                                      // BEFORE ACCESSING ARRAY
1190 375 berkley
      try {
1191 425 bojilova
        DocumentImpl.delete(conn, docid[0], user, group);
1192 204 jones
        response.setContentType("text/xml");
1193
        out.println("<?xml version=\"1.0\"?>");
1194
        out.println("<success>");
1195 203 jones
        out.println("Document deleted.");
1196 204 jones
        out.println("</success>");
1197 203 jones
      } catch (AccessionNumberException ane) {
1198 204 jones
        response.setContentType("text/xml");
1199
        out.println("<?xml version=\"1.0\"?>");
1200
        out.println("<error>");
1201
        out.println("Error deleting document!!!");
1202 203 jones
        out.println(ane.getMessage());
1203 204 jones
        out.println("</error>");
1204 203 jones
      }
1205 204 jones
    } catch (Exception e) {
1206
      response.setContentType("text/xml");
1207
      out.println("<?xml version=\"1.0\"?>");
1208
      out.println("<error>");
1209
      out.println(e.getMessage());
1210
      out.println("</error>");
1211 309 bojilova
    } finally {
1212 320 bojilova
      util.returnConnection(conn);
1213 309 bojilova
    }
1214 203 jones
  }
1215 731 bojilova
  // END OF DELETE SECTION
1216 68 higgins
1217 731 bojilova
  // VALIDATE SECTION
1218 68 higgins
  /**
1219 380 jones
   * Handle the validation request and return the results to the requestor
1220 68 higgins
   */
1221 185 jones
  private void handleValidateAction(PrintWriter out, Hashtable params,
1222
               HttpServletResponse response) {
1223 68 higgins
1224 103 jones
    // Get the document indicated
1225
    String valtext = null;
1226 309 bojilova
1227 103 jones
    try {
1228
      valtext = ((String[])params.get("valtext"))[0];
1229
    } catch (Exception nullpe) {
1230 68 higgins
1231 309 bojilova
      Connection conn = null;
1232 162 bojilova
      String docid = null;
1233 103 jones
      try {
1234
        // Find the document id number
1235 185 jones
        docid = ((String[])params.get("docid"))[0];
1236 309 bojilova
1237
        // get a connection from the pool
1238
        conn = util.getConnection();
1239 393 jones
1240 309 bojilova
        // Get the document indicated from the db
1241 393 jones
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1242
        valtext = xmldoc.toString();
1243 185 jones
1244 103 jones
      } catch (NullPointerException npe) {
1245 253 jones
        response.setContentType("text/xml");
1246
        out.println("<error>Error getting document ID: " + docid + "</error>");
1247 320 bojilova
        if ( conn != null ) { util.returnConnection(conn); }
1248 380 jones
        return;
1249 309 bojilova
      } catch (Exception e) {
1250
        response.setContentType("text/html");
1251
        out.println(e.getMessage());
1252
      } finally {
1253 320 bojilova
        util.returnConnection(conn);
1254 309 bojilova
      }
1255 103 jones
    }
1256 68 higgins
1257 309 bojilova
    Connection conn = null;
1258 103 jones
    try {
1259 309 bojilova
      // get a connection from the pool
1260
      conn = util.getConnection();
1261 253 jones
      DBValidate valobj = new DBValidate(saxparser,conn);
1262 185 jones
      boolean valid = valobj.validateString(valtext);
1263 68 higgins
1264
      // set content type and other response header fields first
1265 253 jones
      response.setContentType("text/xml");
1266
      out.println(valobj.returnErrors());
1267
1268 103 jones
    } catch (NullPointerException npe2) {
1269
      // set content type and other response header fields first
1270 253 jones
      response.setContentType("text/xml");
1271
      out.println("<error>Error validating document.</error>");
1272 309 bojilova
    } catch (Exception e) {
1273
      response.setContentType("text/html");
1274
      out.println(e.getMessage());
1275
    } finally {
1276 320 bojilova
      util.returnConnection(conn);
1277 309 bojilova
    }
1278 103 jones
  }
1279 731 bojilova
  // END OF VALIDATE SECTION
1280
1281
  // OTHER ACTION HANDLERS
1282
  /**
1283
   * sends the port number that the data socket is running on.
1284
   * This is a parameter set in the metacat.properties file.
1285 91 higgins
   */
1286 731 bojilova
  private void handleGetDataPortAction(PrintWriter out, Hashtable params,
1287
                                       HttpServletResponse response,
1288
                                       String username, String groupname,
1289
                                       String sess_id)
1290 458 berkley
  {
1291 731 bojilova
    int port;
1292
    String filedir = null;
1293
    try
1294 458 berkley
    {
1295 731 bojilova
      filedir = util.getOption("datafilepath");
1296
1297
      Random r = new Random();
1298
      port = r.nextInt(65000);  //pick a random port between 0-65000
1299
      //System.out.println("random port is: " + port);
1300
      while(!DataFileServer.portIsAvailable(port))
1301 458 berkley
      {
1302 731 bojilova
        port = r.nextInt(65000);
1303
        //System.out.println("next port used: " + port);
1304 458 berkley
      }
1305 731 bojilova
      DataFileServer dfs = new DataFileServer(port, username, sess_id);
1306
      dfs.start();
1307
1308
      //System.out.println("filedir: " + filedir);
1309
      //System.out.println("port: " + port);
1310
      response.setContentType("text/xml");
1311
      out.println("<?xml version=\"1.0\"?>");
1312
      out.println("<port>");
1313
      out.print(port);
1314
      out.print("</port>");
1315
1316 458 berkley
    }
1317 731 bojilova
	  catch (Exception e)
1318
    {
1319
      System.out.println("error in MetacatServlet.handleGetDataPortAction: " +
1320
                          e.getMessage());
1321
    }
1322 458 berkley
  }
1323 302 bojilova
1324
  /**
1325 688 bojilova
   * Handle "getaccesscontrol" action.
1326
   * Read Access Control List from db connection in XML format
1327
   */
1328
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
1329
                                       HttpServletResponse response,
1330
                                       String username, String groupname) {
1331
1332
    Connection conn = null;
1333
    String docid = ((String[])params.get("docid"))[0];
1334
1335
    try {
1336
1337
        // get connection from the pool
1338
        conn = util.getConnection();
1339
        AccessControlList aclobj = new AccessControlList(conn);
1340
        String acltext = aclobj.getACL(docid, username, groupname);
1341
        out.println(acltext);
1342
1343
    } catch (Exception e) {
1344
      out.println("<?xml version=\"1.0\"?>");
1345
      out.println("<error>");
1346
      out.println(e.getMessage());
1347
      out.println("</error>");
1348
    } finally {
1349
      util.returnConnection(conn);
1350
    }
1351
1352
  }
1353
1354
  /**
1355 731 bojilova
   * Handle the "getprincipals" action.
1356
   * Read all principals from authentication scheme in XML format
1357
   */
1358
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1359
                                         String password) {
1360
1361
    Connection conn = null;
1362
1363
    try {
1364
1365
        // get connection from the pool
1366
        AuthSession auth = new AuthSession();
1367
        String principals = auth.getPrincipals(user, password);
1368
        out.println(principals);
1369
1370
    } catch (Exception e) {
1371
      out.println("<?xml version=\"1.0\"?>");
1372
      out.println("<error>");
1373
      out.println(e.getMessage());
1374
      out.println("</error>");
1375
    } finally {
1376
      util.returnConnection(conn);
1377
    }
1378
1379
  }
1380
1381
  /**
1382 688 bojilova
   * Handle "getdoctypes" action.
1383 302 bojilova
   * Read all doctypes from db connection in XML format
1384
   */
1385
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1386
                                       HttpServletResponse response) {
1387
1388 309 bojilova
    Connection conn = null;
1389
1390 302 bojilova
    try {
1391
1392 309 bojilova
        // get connection from the pool
1393
        conn = util.getConnection();
1394
        DBUtil dbutil = new DBUtil(conn);
1395 302 bojilova
        String doctypes = dbutil.readDoctypes();
1396
        out.println(doctypes);
1397
1398
    } catch (Exception e) {
1399
      out.println("<?xml version=\"1.0\"?>");
1400
      out.println("<error>");
1401
      out.println(e.getMessage());
1402
      out.println("</error>");
1403 309 bojilova
    } finally {
1404 320 bojilova
      util.returnConnection(conn);
1405 309 bojilova
    }
1406 302 bojilova
1407
  }
1408
1409
  /**
1410 699 bojilova
   * Handle the "getdtdschema" action.
1411
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1412
   */
1413
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1414
                                        HttpServletResponse response) {
1415
1416
    Connection conn = null;
1417
    String doctype = null;
1418
    String[] doctypeArr = (String[])params.get("doctype");
1419
1420
    // get only the first doctype specified in the list of doctypes
1421
    // it could be done for all doctypes in that list
1422
    if (doctypeArr != null) {
1423
        doctype = ((String[])params.get("doctype"))[0];
1424
    }
1425
1426
    try {
1427
1428
        // get connection from the pool
1429
        conn = util.getConnection();
1430
        DBUtil dbutil = new DBUtil(conn);
1431
        String dtdschema = dbutil.readDTDSchema(doctype);
1432
        out.println(dtdschema);
1433
1434
    } catch (Exception e) {
1435
      out.println("<?xml version=\"1.0\"?>");
1436
      out.println("<error>");
1437
      out.println(e.getMessage());
1438
      out.println("</error>");
1439
    } finally {
1440
      util.returnConnection(conn);
1441
    }
1442
1443
  }
1444
1445
  /**
1446 688 bojilova
   * Handle the "getdataguide" action.
1447 302 bojilova
   * Read Data Guide for a given doctype from db connection in XML format
1448
   */
1449
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
1450
                                        HttpServletResponse response) {
1451
1452 309 bojilova
    Connection conn = null;
1453 316 bojilova
    String doctype = null;
1454
    String[] doctypeArr = (String[])params.get("doctype");
1455 309 bojilova
1456 316 bojilova
    // get only the first doctype specified in the list of doctypes
1457
    // it could be done for all doctypes in that list
1458
    if (doctypeArr != null) {
1459
        doctype = ((String[])params.get("doctype"))[0];
1460
    }
1461
1462 302 bojilova
    try {
1463
1464 309 bojilova
        // get connection from the pool
1465
        conn = util.getConnection();
1466
        DBUtil dbutil = new DBUtil(conn);
1467 316 bojilova
        String dataguide = dbutil.readDataGuide(doctype);
1468 302 bojilova
        out.println(dataguide);
1469
1470
    } catch (Exception e) {
1471
      out.println("<?xml version=\"1.0\"?>");
1472
      out.println("<error>");
1473
      out.println(e.getMessage());
1474
      out.println("</error>");
1475 309 bojilova
    } finally {
1476 320 bojilova
      util.returnConnection(conn);
1477 309 bojilova
    }
1478 302 bojilova
1479
  }
1480
1481 46 jones
}