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 798 jones
import com.oreilly.servlet.multipart.FilePart;
31
import com.oreilly.servlet.multipart.MultipartParser;
32
import com.oreilly.servlet.multipart.ParamPart;
33
import com.oreilly.servlet.multipart.Part;
34
35 733 bojilova
import java.io.File;
36 46 jones
import java.io.PrintWriter;
37
import java.io.IOException;
38 50 jones
import java.io.StringReader;
39 185 jones
import java.io.FileInputStream;
40 731 bojilova
import java.io.BufferedInputStream;
41 46 jones
import java.util.Enumeration;
42
import java.util.Hashtable;
43 341 berkley
import java.util.ResourceBundle;
44 648 berkley
import java.util.Random;
45 82 jones
import java.util.PropertyResourceBundle;
46 50 jones
import java.net.URL;
47
import java.net.MalformedURLException;
48 85 jones
import java.sql.PreparedStatement;
49
import java.sql.ResultSet;
50 50 jones
import java.sql.Connection;
51 55 jones
import java.sql.SQLException;
52 361 berkley
import java.lang.reflect.*;
53 453 berkley
import java.net.*;
54 458 berkley
import java.util.zip.*;
55 46 jones
56
import javax.servlet.ServletConfig;
57
import javax.servlet.ServletContext;
58
import javax.servlet.ServletException;
59 48 jones
import javax.servlet.ServletInputStream;
60 46 jones
import javax.servlet.http.HttpServlet;
61
import javax.servlet.http.HttpServletRequest;
62
import javax.servlet.http.HttpServletResponse;
63 210 bojilova
import javax.servlet.http.HttpSession;
64 47 jones
import javax.servlet.http.HttpUtils;
65 458 berkley
import javax.servlet.ServletOutputStream;
66 46 jones
67 50 jones
import oracle.xml.parser.v2.XSLStylesheet;
68
import oracle.xml.parser.v2.XSLException;
69
import oracle.xml.parser.v2.XMLDocumentFragment;
70
import oracle.xml.parser.v2.XSLProcessor;
71
72 204 jones
import org.xml.sax.SAXException;
73
74 46 jones
/**
75
 * A metadata catalog server implemented as a Java Servlet
76 154 jones
 *
77
 * <p>Valid parameters are:<br>
78
 * action=query -- query the values of all elements and attributes
79
 *                     and return a result set of nodes<br>
80 205 jones
 * action=squery -- structured query (see pathquery.dtd)<br>
81 731 bojilova
 * action=read -- read any metadata/data file from Metacat and from Internet<br>
82 205 jones
 * action=insert -- insert an XML document into the database store<br>
83
 * action=update -- update an XML document that is in the database store<br>
84
 * action=delete --  delete an XML document from the database store<br>
85
 * action=validate -- vallidate the xml contained in valtext<br>
86
 * doctype -- document type list returned by the query (publicID)<br>
87 154 jones
 * qformat=xml -- display resultset from query in XML<br>
88
 * qformat=html -- display resultset from query in HTML<br>
89 731 bojilova
 * qformat=zip -- zip resultset from query<br>
90 154 jones
 * docid=34 -- display the document with the document ID number 34<br>
91 205 jones
 * doctext -- XML text of the document to load into the database<br>
92 598 bojilova
 * acltext -- XML access text for a document to load into the database<br>
93
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog<br>
94 183 jones
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
95 205 jones
 * valtext -- XML text to be validated<br>
96 731 bojilova
 * abstractpath -- XPath in metadata document to read from<br>
97 688 bojilova
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
98
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
99 699 bojilova
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
100 688 bojilova
 * action=getdataguide -- retrieve a Data Guide<br>
101 725 bojilova
 * action=getprincipals -- retrieve a list of principals in XML<br>
102 205 jones
 * datadoc -- data document name (id)<br>
103
 * <p>
104
 * The particular combination of parameters that are valid for each
105
 * particular action value is quite specific.  This documentation
106
 * will be reorganized to reflect this information.
107 46 jones
 */
108
public class MetaCatServlet extends HttpServlet {
109
110 370 berkley
  private ServletConfig config = null;
111
  private ServletContext context = null;
112
  private Hashtable connectionPool = new Hashtable();
113
  private String resultStyleURL = null;
114
  private String xmlcatalogfile = null;
115
  private String saxparser = null;
116 798 jones
  private String datafilepath = null;
117
  private File dataDirectory = null;
118 370 berkley
  private String servletpath = null;
119 822 jones
  private String htmlpath = null;
120 380 jones
  private PropertyResourceBundle options = null;
121
  private MetaCatUtil util = null;
122
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 798 jones
      datafilepath = util.getOption("datafilepath");
140
      dataDirectory = new File(datafilepath);
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 798 jones
                               HttpServletResponse response)
188
                               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 798 jones
208
    // Deal with forms that are encoded as "multipart/form-data" differently
209
    // this is mainly used for uploading non-xml files using that may be binary
210 800 jones
    String ctype = request.getContentType();
211
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
212 798 jones
      handleMultipartForm(request, response);
213
    } else {
214
      // This probably means the data is "application/x-www-url-encoded", we hope :-)
215 49 jones
216 798 jones
      String name = null;
217
      String[] value = null;
218
      String[] docid = new String[3];
219
      Hashtable params = new Hashtable();
220
      Enumeration paramlist = request.getParameterNames();
221
      while (paramlist.hasMoreElements()) {
222
        name = (String)paramlist.nextElement();
223
        value = request.getParameterValues(name);
224
225
        // Decode the docid and mouse click information
226
        if (name.endsWith(".y")) {
227
          docid[0] = name.substring(0,name.length()-2);
228
          params.put("docid", docid);
229
          name = "ypos";
230 648 berkley
        }
231 798 jones
        if (name.endsWith(".x")) {
232
          name = "xpos";
233
        }
234
235
        params.put(name,value);
236 425 bojilova
      }
237 798 jones
238
      //if the user clicked on the input images, decode which image
239
      //was clicked then set the action.
240
      String action = ((String[])params.get("action"))[0];
241
      util.debugMessage("Line 213: Action is: " + action);
242
243
      // This block handles session management for the servlet
244
      // by looking up the current session information for all actions
245
      // other than "login" and "logout"
246
      String username = null;
247
      String password = null;
248 802 bojilova
      String[] groupnames = null;
249 798 jones
      String sess_id = null;
250
251
      // handle login action
252
      if (action.equals("login")) {
253
254
        handleLoginAction(response.getWriter(), params, request, response);
255
256
      // handle logout action
257
      } else if (action.equals("logout")) {
258
259
        handleLogoutAction(response.getWriter(), params, request, response);
260
261
      // aware of session expiration on every request
262
      } else {
263
264
        HttpSession sess = request.getSession(true);
265
        if (sess.isNew()) {
266
          // session expired or has not been stored b/w user requests
267
          username = "public";
268
          sess.setAttribute("username", username);
269
        } else {
270
          username = (String)sess.getAttribute("username");
271
          password = (String)sess.getAttribute("password");
272 802 bojilova
          groupnames = (String[])sess.getAttribute("groupnames");
273 798 jones
          try {
274
            sess_id = (String)sess.getId();
275
          } catch(IllegalStateException ise) {
276
            System.out.println("error in handleGetOrPost: this shouldn't " +
277
                               "happen: the session should be valid: " +
278
                               ise.getMessage());
279
          }
280
        }
281
      }
282
283
      // Now that we know the session is valid, we can delegate the request
284
      // to a particular action handler
285
      if(action.equals("query")) {
286 802 bojilova
        handleQuery(response.getWriter(),params,response,username,groupnames);
287 798 jones
      } else if(action.equals("squery")) {
288
        if(params.containsKey("query")) {
289 802 bojilova
          handleSQuery(response.getWriter(),params,response,username,groupnames);
290 798 jones
        } else {
291
          PrintWriter out = response.getWriter();
292
          out.println("Illegal action squery without \"query\" parameter");
293
        }
294
      } else if (action.equals("read")) {
295 802 bojilova
        handleReadAction(params, response, username, groupnames);
296 798 jones
      } else if (action.equals("insert") || action.equals("update")) {
297 458 berkley
        PrintWriter out = response.getWriter();
298 798 jones
        if ( (username != null) &&  !username.equals("public") ) {
299 802 bojilova
          handleInsertOrUpdateAction(out,params,response,username,groupnames);
300 798 jones
        } else {
301
          out.println("Permission denied for " + action);
302
        }
303
      } else if (action.equals("delete")) {
304
        PrintWriter out = response.getWriter();
305
        if ( (username != null) &&  !username.equals("public") ) {
306 802 bojilova
          handleDeleteAction(out, params, response, username, groupnames);
307 798 jones
        } else {
308
          out.println("Permission denied for " + action);
309
        }
310
      } else if (action.equals("validate")) {
311
        PrintWriter out = response.getWriter();
312
        handleValidateAction(out, params, response);
313
      } else if (action.equals("getaccesscontrol")) {
314
        PrintWriter out = response.getWriter();
315 802 bojilova
        handleGetAccessControlAction(out,params,response,username,groupnames);
316 798 jones
      } else if (action.equals("getprincipals")) {
317
        PrintWriter out = response.getWriter();
318
        handleGetPrincipalsAction(out, username, password);
319
      } else if (action.equals("getdoctypes")) {
320
        PrintWriter out = response.getWriter();
321
        handleGetDoctypesAction(out, params, response);
322
      } else if (action.equals("getdtdschema")) {
323
        PrintWriter out = response.getWriter();
324
        handleGetDTDSchemaAction(out, params, response);
325
      } else if (action.equals("getdataguide")) {
326
        PrintWriter out = response.getWriter();
327
        handleGetDataGuideAction(out, params, response);
328
      } else if (action.equals("getlastdocid")) {
329
        PrintWriter out = response.getWriter();
330 847 jones
        handleGetMaxDocidAction(out, params, response);
331 798 jones
      } else if (action.equals("login") || action.equals("logout")) {
332
      } else if (action.equals("protocoltest")) {
333
        String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
334
        try {
335
          testURL = ((String[])params.get("url"))[0];
336
        } catch (Throwable t) {
337
        }
338
        String phandler = System.getProperty("java.protocol.handler.pkgs");
339
        response.setContentType("text/html");
340
        PrintWriter out = response.getWriter();
341
        out.println("<body bgcolor=\"white\">");
342
        out.println("<p>Handler property: <code>" + phandler + "</code></p>");
343
        out.println("<p>Starting test for:<br>");
344
        out.println("    " + testURL + "</p>");
345
        try {
346
          URL u = new URL(testURL);
347
          out.println("<pre>");
348
          out.println("Protocol: " + u.getProtocol());
349
          out.println("    Host: " + u.getHost());
350
          out.println("    Port: " + u.getPort());
351
          out.println("    Path: " + u.getPath());
352
          out.println("     Ref: " + u.getRef());
353
          String pquery = u.getQuery();
354
          out.println("   Query: " + pquery);
355
          out.println("  Params: ");
356
          if (pquery != null) {
357
            Hashtable qparams = util.parseQuery(u.getQuery());
358
            for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
359
              String pname = (String)en.nextElement();
360
              String pvalue = (String)qparams.get(pname);
361
              out.println("    " + pname + ": " + pvalue);
362
            }
363 566 jones
          }
364 798 jones
          out.println("</pre>");
365
          out.println("</body>");
366
          out.close();
367
        } catch (MalformedURLException mue) {
368
          System.out.println("bad url from MetacatServlet.handleGetOrPost");
369
          out.println(mue.getMessage());
370
          mue.printStackTrace(out);
371
          out.close();
372 566 jones
        }
373 798 jones
      } else {
374
        PrintWriter out = response.getWriter();
375
        out.println("<?xml version=\"1.0\"?>");
376
        out.println("<error>");
377
        out.println("Error: action not registered.  Please report this error.");
378
        out.println("</error>");
379 566 jones
      }
380 798 jones
381
      util.closeConnections();
382
      // Close the stream to the client
383
      // out.close();
384 46 jones
    }
385
  }
386 355 berkley
387 731 bojilova
  // LOGIN & LOGOUT SECTION
388 50 jones
  /**
389 509 bojilova
   * Handle the login request. Create a new session object.
390 503 bojilova
   * Do user authentication through the session.
391 210 bojilova
   */
392
  private void handleLoginAction(PrintWriter out, Hashtable params,
393
               HttpServletRequest request, HttpServletResponse response) {
394 251 bojilova
395 503 bojilova
    AuthSession sess = null;
396 228 bojilova
    String un = ((String[])params.get("username"))[0];
397
    String pw = ((String[])params.get("password"))[0];
398 297 bojilova
    String action = ((String[])params.get("action"))[0];
399 509 bojilova
    String qformat = ((String[])params.get("qformat"))[0];
400 332 bojilova
401 297 bojilova
    try {
402 509 bojilova
      sess = new AuthSession();
403 297 bojilova
    } catch (Exception e) {
404 675 berkley
      System.out.println("error in MetacatServlet.handleLoginAction: " +
405
                          e.getMessage());
406 297 bojilova
      out.println(e.getMessage());
407 509 bojilova
      return;
408 297 bojilova
    }
409 509 bojilova
    boolean isValid = sess.authenticate(request, un, pw);
410
    // format and transform the output
411 832 jones
    if (qformat.equals("xml")) {
412
      response.setContentType("text/xml");
413
      out.println(sess.getMessage());
414
    } else {
415 509 bojilova
      Connection conn = null;
416 503 bojilova
      try {
417 509 bojilova
        conn = util.getConnection();
418
        DBTransform trans = new DBTransform(conn);
419
        response.setContentType("text/html");
420 510 bojilova
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
421 832 jones
                                   "-//W3C//HTML//EN", qformat, out);
422 509 bojilova
        util.returnConnection(conn);
423
      } catch(Exception e) {
424
        util.returnConnection(conn);
425
      }
426
427
    // any output is returned
428 503 bojilova
    }
429 370 berkley
  }
430 509 bojilova
431
  /**
432
   * Handle the logout request. Close the connection.
433
   */
434
  private void handleLogoutAction(PrintWriter out, Hashtable params,
435
               HttpServletRequest request, HttpServletResponse response) {
436
437
    String qformat = ((String[])params.get("qformat"))[0];
438
439
    // close the connection
440
    HttpSession sess = request.getSession(false);
441
    if (sess != null) { sess.invalidate();  }
442
443
    // produce output
444
    StringBuffer output = new StringBuffer();
445
    output.append("<?xml version=\"1.0\"?>");
446 510 bojilova
    output.append("<logout>");
447
    output.append("User logged out");
448
    output.append("</logout>");
449 509 bojilova
450
    //format and transform the output
451 832 jones
    if (qformat.equals("xml")) {
452
      response.setContentType("text/xml");
453
      out.println(output.toString());
454
    } else {
455 509 bojilova
      Connection conn = null;
456
      try {
457
        conn = util.getConnection();
458
        DBTransform trans = new DBTransform(conn);
459
        response.setContentType("text/html");
460 510 bojilova
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
461 832 jones
                                   "-//W3C//HTML//EN", qformat, out);
462 509 bojilova
        util.returnConnection(conn);
463
      } catch(Exception e) {
464
        util.returnConnection(conn);
465
      }
466
    }
467
  }
468 731 bojilova
  // END OF LOGIN & LOGOUT SECTION
469 370 berkley
470 731 bojilova
  // SQUERY & QUERY SECTION
471 373 berkley
  /**
472 380 jones
   * Retreive the squery xml, execute it and display it
473
   *
474
   * @param out the output stream to the client
475
   * @param params the Hashtable of parameters that should be included
476
   * in the squery.
477
   * @param response the response object linked to the client
478
   * @param conn the database connection
479
   */
480
  protected void handleSQuery(PrintWriter out, Hashtable params,
481 802 bojilova
                 HttpServletResponse response, String user, String[] groups)
482 373 berkley
  {
483 380 jones
    String xmlquery = ((String[])params.get("query"))[0];
484
    String qformat = ((String[])params.get("qformat"))[0];
485 465 berkley
    String resultdoc = null;
486
487 802 bojilova
    Hashtable doclist = runQuery(xmlquery, user, groups);
488 444 berkley
489 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
490
491 380 jones
    //format and transform the results
492 832 jones
    if(qformat.equals("xml")) {
493 380 jones
      response.setContentType("text/xml");
494
      out.println(resultdoc);
495
    } else {
496 832 jones
      transformResultset(resultdoc, response, out, qformat);
497 380 jones
    }
498 341 berkley
  }
499
500
   /**
501 380 jones
    * Create the xml query, execute it and display the results.
502
    *
503
    * @param out the output stream to the client
504
    * @param params the Hashtable of parameters that should be included
505 370 berkley
    * in the squery.
506 380 jones
    * @param response the response object linked to the client
507 370 berkley
    */
508 375 berkley
  protected void handleQuery(PrintWriter out, Hashtable params,
509 802 bojilova
                 HttpServletResponse response, String user, String[] groups)
510 341 berkley
  {
511 370 berkley
    //create the query and run it
512 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
513 802 bojilova
    Hashtable doclist = runQuery(xmlquery, user, groups);
514 465 berkley
    String qformat = ((String[])params.get("qformat"))[0];
515
    String resultdoc = null;
516
517
    resultdoc = createResultDocument(doclist, transformQuery(params));
518 425 bojilova
519 370 berkley
    //format and transform the results
520 832 jones
    if(qformat.equals("xml")) {
521 370 berkley
      response.setContentType("text/xml");
522
      out.println(resultdoc);
523 443 berkley
    } else {
524 832 jones
      transformResultset(resultdoc, response, out, qformat);
525 370 berkley
    }
526 341 berkley
  }
527
528
  /**
529 384 berkley
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
530
   * so it can properly be placed in the <query> tag of the resultset.
531
   * This method is overwritable so that other applications can customize
532
   * the structure of what is in the <query> tag.
533
   *
534
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
535
   */
536
  protected String transformQuery(Hashtable params)
537
  {
538
    //DBQuery.createSQuery is a re-calling of a previously called
539
    //function but it is necessary
540
    //so that overriding methods have access to the params hashtable
541
    String xmlquery = DBQuery.createSQuery(params);
542
    //the <?xml version="1.0"?> tag is the first 22 characters of the
543
    xmlquery = xmlquery.trim();
544
    int index = xmlquery.indexOf("?>");
545
    return xmlquery.substring(index + 2, xmlquery.length());
546
  }
547
548
  /**
549 443 berkley
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
550
   * string as a param instead of a hashtable.
551
   *
552
   * @param xmlquery a string representing a query.
553
   */
554
  protected String transformQuery(String xmlquery)
555
  {
556
    xmlquery = xmlquery.trim();
557
    int index = xmlquery.indexOf("?>");
558
    return xmlquery.substring(index + 2, xmlquery.length());
559
  }
560
561
  /**
562 380 jones
   * Run the query and return a hashtable of results.
563
   *
564
   * @param xmlquery the query to run
565
   */
566 802 bojilova
  private Hashtable runQuery(String xmlquery, String user, String[] groups)
567 341 berkley
  {
568
    Hashtable doclist=null;
569
    Connection conn = null;
570
    try
571
    {
572 441 bojilova
      conn = util.getConnection();
573
      DBQuery queryobj = new DBQuery(conn, saxparser);
574 802 bojilova
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,groups);
575 441 bojilova
      util.returnConnection(conn);
576
      return doclist;
577 341 berkley
    }
578
    catch (Exception e)
579
    {
580 441 bojilova
      util.returnConnection(conn);
581 675 berkley
      util.debugMessage("Error in MetacatServlet.runQuery: " + e.getMessage());
582 341 berkley
      doclist = null;
583
      return doclist;
584
    }
585
  }
586
587 380 jones
  /**
588 370 berkley
   * Transorms an xml resultset document to html and sends it to the browser
589 380 jones
   *
590 370 berkley
   * @param resultdoc the string representation of the document that needs
591
   * to be transformed.
592
   * @param response the HttpServletResponse object bound to the client.
593
   * @param out the output stream to the client
594 832 jones
   * @param qformat the name of the style-set to use for transformations
595 375 berkley
   */
596
  protected void transformResultset(String resultdoc,
597 380 jones
                                    HttpServletResponse response,
598 832 jones
                                    PrintWriter out, String qformat)
599 370 berkley
  {
600
    Connection conn = null;
601 380 jones
    try {
602 370 berkley
      conn = util.getConnection();
603
      DBTransform trans = new DBTransform(conn);
604
      response.setContentType("text/html");
605
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
606 832 jones
                                 "-//W3C//HTML//EN", qformat, out);
607 382 berkley
      util.returnConnection(conn);
608
    }
609
    catch(Exception e)
610
    {
611 441 bojilova
      util.returnConnection(conn);
612 370 berkley
    }
613
  }
614
615 355 berkley
  /**
616
   * Transforms a hashtable of documents to an xml or html result.
617 380 jones
   *
618 355 berkley
   * @param doclist- the hashtable to transform
619 744 jones
   * @param xmlquery- the query that returned the doclist result
620 355 berkley
   */
621 375 berkley
  protected String createResultDocument(Hashtable doclist, String xmlquery)
622 341 berkley
  {
623
    // Create a buffer to hold the xml result
624
    StringBuffer resultset = new StringBuffer();
625
626 382 berkley
    // Print the resulting root nodes
627 341 berkley
    String docid = null;
628
    String document = null;
629
    resultset.append("<?xml version=\"1.0\"?>\n");
630
    resultset.append("<resultset>\n");
631 465 berkley
632 384 berkley
    resultset.append("  <query>" + xmlquery + "</query>");
633 478 berkley
634
    if(doclist != null)
635 341 berkley
    {
636 478 berkley
      Enumeration doclistkeys = doclist.keys();
637
      while (doclistkeys.hasMoreElements())
638
      {
639
        docid = (String)doclistkeys.nextElement();
640
        document = (String)doclist.get(docid);
641
        resultset.append("  <document>" + document + "</document>");
642
      }
643
    }
644
645 341 berkley
    resultset.append("</resultset>");
646 370 berkley
    return resultset.toString();
647 341 berkley
  }
648 731 bojilova
  // END OF SQUERY & QUERY SECTION
649 437 berkley
650 731 bojilova
  // READ SECTION
651
  /**
652
   * Handle the "read" request of metadata/data files from Metacat
653
   * or any files from Internet;
654
   * transformed metadata XML document into HTML presentation if requested;
655
   * zip files when more than one were requested.
656
   *
657
   * @param params the Hashtable of HTTP request parameters
658
   * @param response the HTTP response object linked to the client
659
   * @param user the username sent the request
660 802 bojilova
   * @param groups the user's groupnames
661 437 berkley
   */
662 731 bojilova
  private void handleReadAction(Hashtable params, HttpServletResponse response,
663 802 bojilova
                                String user, String[] groups)
664 437 berkley
  {
665 731 bojilova
    ServletOutputStream out = null;
666
    ZipOutputStream zout = null;
667
668
    try {
669
      String[] docs = new String[0];
670
      String docid = "";
671
      String qformat = "";
672
      String abstrpath = null;
673
      boolean zip = false;
674
      // read the params
675
      if (params.containsKey("docid")) {
676
        docs = (String[])params.get("docid");
677 437 berkley
      }
678 731 bojilova
      if (params.containsKey("qformat")) {
679
        qformat = ((String[])params.get("qformat"))[0];
680 437 berkley
      }
681 731 bojilova
      if (params.containsKey("abstractpath")) {
682
        abstrpath = ((String[])params.get("abstractpath"))[0];
683 738 bojilova
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
684
          viewAbstract(response, abstrpath, docs[0]);
685
          return;
686
        }
687 437 berkley
      }
688 731 bojilova
      if ( (docs.length > 1) || qformat.equals("zip") ) {
689
        zip = true;
690
        out = response.getOutputStream();
691
        response.setContentType("application/zip"); //MIME type
692
        zout = new ZipOutputStream(out);
693
      }
694
      // go through the list of docs to read
695
      for (int i=0; i < docs.length; i++ ) {
696
        try {
697
698
          URL murl = new URL(docs[i]);
699
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
700
          // case docid="http://.../?docid=aaa"
701
          // or docid="metacat://.../?docid=bbb"
702
          if (murlQueryStr.containsKey("docid")) {
703
            // get only docid, eliminate the rest
704
            docid = (String)murlQueryStr.get("docid");
705
            if ( zip ) {
706
              addDocToZip(docid, zout);
707
            } else {
708
              readFromMetacat(response, docid, qformat, abstrpath,
709 802 bojilova
                              user, groups, zip, zout);
710 731 bojilova
            }
711
712
          // case docid="http://.../filename"
713
          } else {
714
            docid = docs[i];
715
            if ( zip ) {
716
              addDocToZip(docid, zout);
717
            } else {
718
              readFromURLConnection(response, docid);
719
            }
720
          }
721
722
        // case docid="ccc"
723
        } catch (MalformedURLException mue) {
724
          docid = docs[i];
725
          if ( zip ) {
726
            addDocToZip(docid, zout);
727
          } else {
728
            readFromMetacat(response, docid, qformat, abstrpath,
729 802 bojilova
                            user, groups, zip, zout);
730 731 bojilova
          }
731
        }
732
733
      } /* end for */
734
735
      if ( zip ) {
736
        zout.finish(); //terminate the zip file
737
        zout.close();  //close the zip stream
738
      }
739
740 845 jones
        /*
741
    } catch (ClassNotFoundException cnfe) {
742
    } catch (IOException ioe1) {
743
    } catch (SQLException se) {
744
    } catch (McdbException mcdbe) {
745 731 bojilova
    } catch (Exception e) {
746 845 jones
      */
747
    } catch (Exception e) {
748 731 bojilova
      try {
749 845 jones
        response.setContentType("text/xml"); //MIME type
750
        //PrintWriter pw = response.getWriter();
751
        if (out != null) {
752
            PrintWriter pw = new PrintWriter(out);
753
            pw.println("<?xml version=\"1.0\"?>");
754
            pw.println("<error>");
755
            pw.println(e.getMessage());
756
            pw.println("</error>");
757
            pw.close();
758
        }
759
        //if ( out != null ) { out.close(); }
760 731 bojilova
        if ( zout != null ) { zout.close(); }
761
      } catch (IOException ioe) {
762
        System.out.println("Problem with the servlet output " +
763
                           "in MetacatServlet.handleReadAction: " +
764
                           ioe.getMessage());
765
        ioe.printStackTrace(System.out);
766
767
      }
768
769
      System.out.println("Error in MetacatServlet.handleReadAction: " +
770 675 berkley
                         e.getMessage());
771 731 bojilova
      e.printStackTrace(System.out);
772 437 berkley
    }
773
774
  }
775 731 bojilova
776
  // read metadata or data from Metacat
777
  private void readFromMetacat(HttpServletResponse response, String docid,
778
                               String qformat, String abstrpath, String user,
779 802 bojilova
                               String[] groups, boolean zip, ZipOutputStream zout)
780 731 bojilova
               throws ClassNotFoundException, IOException, SQLException,
781
                      McdbException, Exception
782 453 berkley
  {
783
    Connection conn = null;
784 731 bojilova
    try {
785
      conn = util.getConnection();
786
      DocumentImpl doc = new DocumentImpl(conn, docid);
787 453 berkley
788 731 bojilova
      if ( doc.getRootNodeID() == 0 ) {
789
        // this is data file
790
        ServletOutputStream out = response.getOutputStream();
791
        String filepath = util.getOption("datafilepath");
792
        if(!filepath.endsWith("/")) {
793
          filepath += "/";
794
        }
795 846 berkley
        String filename = filepath + docid;      //MIME type
796 731 bojilova
        String contentType = getServletContext().getMimeType(filename);
797
        if (contentType == null) {
798
          if (filename.endsWith(".xml")) {
799
            contentType="text/xml";
800
          } else if (filename.endsWith(".css")) {
801
            contentType="text/css";
802
          } else if (filename.endsWith(".dtd")) {
803
            contentType="text/plain";
804
          } else if (filename.endsWith(".xsd")) {
805 733 bojilova
            contentType="text/xml";
806 731 bojilova
          } else if (filename.endsWith("/")) {
807 733 bojilova
            contentType="text/html";
808 731 bojilova
          } else {
809 733 bojilova
            File f = new File(filename);
810
            if ( f.isDirectory() ) {
811
              contentType="text/html";
812
            } else {
813
              contentType="application/octet-stream";
814
            }
815 453 berkley
          }
816
        }
817 731 bojilova
        response.setContentType(contentType);
818 733 bojilova
        // if we decide to use "application/octet-stream" for all data returns
819
        // response.setContentType("application/octet-stream");
820 731 bojilova
        FileInputStream fin = null;
821
        try {
822
          fin = new FileInputStream(filename);
823
          byte[] buf = new byte[4 * 1024]; // 4K buffer
824
          int b = fin.read(buf);
825
          while (b != -1) {
826
            out.write(buf, 0, b);
827
            b = fin.read(buf);
828 453 berkley
          }
829 731 bojilova
        } finally {
830
          if (fin != null) fin.close();
831 453 berkley
        }
832 731 bojilova
833
      } else {
834
        // this is metadata doc
835 832 jones
        if ( qformat.equals("xml") ) {
836
          // set content type first
837
          response.setContentType("text/xml");   //MIME type
838
          PrintWriter out = response.getWriter();
839
          doc.toXml(out);
840
        } else {
841 731 bojilova
          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 832 jones
                                   doctype,"-//W3C//HTML//EN", qformat, out);
850 731 bojilova
        }
851
852 453 berkley
      }
853 731 bojilova
    } finally {
854
      util.returnConnection(conn);
855
    }
856
857
  }
858 453 berkley
859 731 bojilova
  // read data from URLConnection
860
  private void readFromURLConnection(HttpServletResponse response, String docid)
861
               throws IOException, MalformedURLException
862 566 jones
  {
863 731 bojilova
    ServletOutputStream out = response.getOutputStream();
864
    String contentType = getServletContext().getMimeType(docid); //MIME type
865
    if (contentType == null) {
866
      if (docid.endsWith(".xml")) {
867
        contentType="text/xml";
868
      } else if (docid.endsWith(".css")) {
869
        contentType="text/css";
870
      } else if (docid.endsWith(".dtd")) {
871
        contentType="text/plain";
872
      } else if (docid.endsWith(".xsd")) {
873 733 bojilova
        contentType="text/xml";
874 731 bojilova
      } else if (docid.endsWith("/")) {
875 733 bojilova
        contentType="text/html";
876 731 bojilova
      } else {
877 733 bojilova
        File f = new File(docid);
878
        if ( f.isDirectory() ) {
879
          contentType="text/html";
880
        } else {
881
          contentType="application/octet-stream";
882
        }
883 731 bojilova
      }
884
    }
885
    response.setContentType(contentType);
886 733 bojilova
    // if we decide to use "application/octet-stream" for all data returns
887
    // response.setContentType("application/octet-stream");
888 731 bojilova
889
    // this is http url
890
    URL url = new URL(docid);
891
    BufferedInputStream bis = null;
892 566 jones
    try {
893 731 bojilova
      bis = new BufferedInputStream(url.openStream());
894
      byte[] buf = new byte[4 * 1024]; // 4K buffer
895
      int b = bis.read(buf);
896
      while (b != -1) {
897
        out.write(buf, 0, b);
898
        b = bis.read(buf);
899 636 berkley
      }
900 731 bojilova
    } finally {
901
      if (bis != null) bis.close();
902 566 jones
    }
903 731 bojilova
904 566 jones
  }
905 636 berkley
906 731 bojilova
  // read file/doc and write to ZipOutputStream
907
  private void addDocToZip(String docid, ZipOutputStream zout)
908
               throws ClassNotFoundException, IOException, SQLException,
909
                      McdbException, Exception
910 636 berkley
  {
911 731 bojilova
    byte[] bytestring = null;
912
    ZipEntry zentry = null;
913
914
    try {
915
      URL url = new URL(docid);
916
917
      // this http url; read from URLConnection; add to zip
918
      zentry = new ZipEntry(docid);
919
      zout.putNextEntry(zentry);
920
      BufferedInputStream bis = null;
921
      try {
922
        bis = new BufferedInputStream(url.openStream());
923
        byte[] buf = new byte[4 * 1024]; // 4K buffer
924
        int b = bis.read(buf);
925
        while(b != -1) {
926
          zout.write(buf, 0, b);
927
          b = bis.read(buf);
928
        }
929
      } finally {
930
        if (bis != null) bis.close();
931 636 berkley
      }
932 731 bojilova
      zout.closeEntry();
933
934
    } catch (MalformedURLException mue) {
935 661 berkley
936 731 bojilova
      // this is metacat doc (data file or metadata doc)
937
      Connection conn = null;
938
      try {
939
        conn = util.getConnection();
940
        DocumentImpl doc = new DocumentImpl(conn, docid);
941 661 berkley
942 731 bojilova
        if ( doc.getRootNodeID() == 0 ) {
943
          // this is data file; add file to zip
944
          String filepath = util.getOption("datafilepath");
945
          if(!filepath.endsWith("/")) {
946
            filepath += "/";
947
          }
948
          String filename = filepath + doc.getDocname();
949
          zentry = new ZipEntry(filename);
950
          zout.putNextEntry(zentry);
951
          FileInputStream fin = null;
952
          try {
953
            fin = new FileInputStream(filename);
954
            byte[] buf = new byte[4 * 1024]; // 4K buffer
955
            int b = fin.read(buf);
956
            while (b != -1) {
957
              zout.write(buf, 0, b);
958
              b = fin.read(buf);
959
            }
960
          } finally {
961
            if (fin != null) fin.close();
962
          }
963
          zout.closeEntry();
964
965
        } else {
966
          // this is metadata doc; add doc to zip
967
          bytestring = doc.toString().getBytes();
968
          zentry = new ZipEntry(docid + ".xml");
969
          zentry.setSize(bytestring.length);
970
          zout.putNextEntry(zentry);
971
          zout.write(bytestring, 0, bytestring.length);
972
          zout.closeEntry();
973 636 berkley
        }
974 731 bojilova
      } finally {
975
        util.returnConnection(conn);
976 636 berkley
      }
977
978
    }
979 731 bojilova
980 636 berkley
  }
981 731 bojilova
982
  // view abstract within document
983
  private void viewAbstract(HttpServletResponse response,
984
                            String abstractpath, String docid)
985
               throws ClassNotFoundException, IOException, SQLException,
986
                      McdbException, Exception
987
  {
988 309 bojilova
    Connection conn = null;
989 102 jones
    try {
990 309 bojilova
      conn = util.getConnection();
991 731 bojilova
992
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
993
994
      response.setContentType("text/html");  //MIME type
995
      PrintWriter out = response.getWriter();
996
      out.println("<html><head><title>Abstract</title></head>");
997
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
998
      for (int i=0; i<abstracts.length; i++) {
999
        out.println("<p>" + (String)abstracts[i] + "</p>");
1000
      }
1001
      out.println("</body></html>");
1002 85 jones
1003 309 bojilova
    } finally {
1004 320 bojilova
      util.returnConnection(conn);
1005 731 bojilova
    }
1006 49 jones
  }
1007 731 bojilova
  // END OF READ SECTION
1008
1009
  // INSERT/UPDATE SECTION
1010 55 jones
  /**
1011
   * Handle the database putdocument request and write an XML document
1012
   * to the database connection
1013
   */
1014 382 berkley
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1015 802 bojilova
               HttpServletResponse response, String user, String[] groups) {
1016 59 jones
1017 309 bojilova
    Connection conn = null;
1018
1019 204 jones
    try {
1020
      // Get the document indicated
1021
      String[] doctext = (String[])params.get("doctext");
1022 557 bojilova
1023 680 bojilova
      String pub = null;
1024
      if (params.containsKey("public")) {
1025
        pub = ((String[])params.get("public"))[0];
1026 557 bojilova
      }
1027 680 bojilova
1028 598 bojilova
      StringReader dtd = null;
1029 680 bojilova
      if (params.containsKey("dtdtext")) {
1030 598 bojilova
        String[] dtdtext = (String[])params.get("dtdtext");
1031
        try {
1032 619 bojilova
          if ( !dtdtext[0].equals("") ) {
1033
            dtd = new StringReader(dtdtext[0]);
1034
          }
1035 598 bojilova
        } catch (NullPointerException npe) {}
1036
      }
1037 557 bojilova
1038 204 jones
      StringReader xml = null;
1039 695 bojilova
      boolean validate = false;
1040 204 jones
      try {
1041 695 bojilova
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1042
        // in order to decide whether to use validation parser
1043
        validate = validateXML(doctext[0]);
1044 204 jones
        xml = new StringReader(doctext[0]);
1045 59 jones
1046 204 jones
        String[] action = (String[])params.get("action");
1047
        String[] docid = (String[])params.get("docid");
1048
        String newdocid = null;
1049 203 jones
1050 204 jones
        String doAction = null;
1051
        if (action[0].equals("insert")) {
1052
          doAction = "INSERT";
1053
        } else if (action[0].equals("update")) {
1054
          doAction = "UPDATE";
1055
        }
1056 203 jones
1057 204 jones
        try {
1058 680 bojilova
          // get a connection from the pool
1059
          conn = util.getConnection();
1060 408 jones
1061 680 bojilova
          // write the document to the database
1062
          try {
1063
            String accNumber = docid[0];
1064
            if (accNumber.equals("")) {
1065
              accNumber = null;
1066 309 bojilova
            }
1067 680 bojilova
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1068 802 bojilova
                                          accNumber, user, groups, validate);
1069 680 bojilova
          } catch (NullPointerException npe) {
1070
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1071 802 bojilova
                                          null, user, groups, validate);
1072 680 bojilova
          }
1073 309 bojilova
        } finally {
1074 320 bojilova
          util.returnConnection(conn);
1075 309 bojilova
        }
1076
1077 204 jones
        // set content type and other response header fields first
1078
        response.setContentType("text/xml");
1079
        out.println("<?xml version=\"1.0\"?>");
1080
        out.println("<success>");
1081
        out.println("<docid>" + newdocid + "</docid>");
1082
        out.println("</success>");
1083
1084 203 jones
      } catch (NullPointerException npe) {
1085 204 jones
        response.setContentType("text/xml");
1086
        out.println("<?xml version=\"1.0\"?>");
1087
        out.println("<error>");
1088
        out.println(npe.getMessage());
1089
        out.println("</error>");
1090 55 jones
      }
1091 204 jones
    } catch (Exception e) {
1092
      response.setContentType("text/xml");
1093
      out.println("<?xml version=\"1.0\"?>");
1094
      out.println("<error>");
1095
      out.println(e.getMessage());
1096
      if (e instanceof SAXException) {
1097
        Exception e2 = ((SAXException)e).getException();
1098
        out.println("<error>");
1099 780 berkley
        try
1100
        {
1101
          out.println(e2.getMessage());
1102
        }
1103
        catch(NullPointerException npe)
1104
        {
1105
          out.println(e.getMessage());
1106
        }
1107 204 jones
        out.println("</error>");
1108
      }
1109
      //e.printStackTrace(out);
1110
      out.println("</error>");
1111 203 jones
    }
1112 55 jones
  }
1113 203 jones
1114
  /**
1115 695 bojilova
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1116
   * in order to decide whether to use validation parser
1117
   */
1118
  private static boolean validateXML(String xmltext) throws IOException {
1119
1120
    StringReader xmlreader = new StringReader(xmltext);
1121
    StringBuffer cbuff = new StringBuffer();
1122
    java.util.Stack st = new java.util.Stack();
1123
    boolean validate = false;
1124
    int c;
1125
    int inx;
1126
1127
    // read from the stream until find the keywords
1128
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1129
      cbuff.append((char)c);
1130
1131
      // "<!DOCTYPE" keyword is found; put it in the stack
1132
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1133
        cbuff = new StringBuffer();
1134
        st.push("<!DOCTYPE");
1135
      }
1136
      // "PUBLIC" keyword is found; put it in the stack
1137
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1138
        cbuff = new StringBuffer();
1139
        st.push("PUBLIC");
1140
      }
1141
      // "SYSTEM" keyword is found; put it in the stack
1142
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1143
        cbuff = new StringBuffer();
1144
        st.push("SYSTEM");
1145
      }
1146
      // ">" character is found; put it in the stack
1147
      // ">" is found twice: fisrt from <?xml ...?>
1148
      // and second from <!DOCTYPE ... >
1149
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1150
        cbuff = new StringBuffer();
1151
        st.push(">");
1152
      }
1153
    }
1154
1155
    // close the stream
1156
    xmlreader.close();
1157
1158
    // check the stack whether it contains the keywords:
1159
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1160
    if ( st.size() == 4 ) {
1161
      if ( ((String)st.pop()).equals(">") &&
1162
           ( ((String)st.peek()).equals("PUBLIC") |
1163
             ((String)st.pop()).equals("SYSTEM") ) &&
1164
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1165
        validate = true;
1166
      }
1167
    }
1168
1169
System.out.println("Validation is " + validate);
1170
    return validate;
1171
  }
1172 731 bojilova
  // END OF INSERT/UPDATE SECTION
1173 695 bojilova
1174 731 bojilova
  // DELETE SECTION
1175 695 bojilova
  /**
1176 203 jones
   * Handle the database delete request and delete an XML document
1177
   * from the database connection
1178
   */
1179
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1180 802 bojilova
               HttpServletResponse response, String user, String[] groups) {
1181 203 jones
1182
    String[] docid = (String[])params.get("docid");
1183 309 bojilova
    Connection conn = null;
1184 203 jones
1185
    // delete the document from the database
1186
    try {
1187 309 bojilova
      // get a connection from the pool
1188
      conn = util.getConnection();
1189 203 jones
                                      // NOTE -- NEED TO TEST HERE
1190 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
1191 203 jones
                                      // BEFORE ACCESSING ARRAY
1192 375 berkley
      try {
1193 802 bojilova
        DocumentImpl.delete(conn, docid[0], user, groups);
1194 204 jones
        response.setContentType("text/xml");
1195
        out.println("<?xml version=\"1.0\"?>");
1196
        out.println("<success>");
1197 203 jones
        out.println("Document deleted.");
1198 204 jones
        out.println("</success>");
1199 203 jones
      } catch (AccessionNumberException ane) {
1200 204 jones
        response.setContentType("text/xml");
1201
        out.println("<?xml version=\"1.0\"?>");
1202
        out.println("<error>");
1203
        out.println("Error deleting document!!!");
1204 203 jones
        out.println(ane.getMessage());
1205 204 jones
        out.println("</error>");
1206 203 jones
      }
1207 204 jones
    } catch (Exception e) {
1208
      response.setContentType("text/xml");
1209
      out.println("<?xml version=\"1.0\"?>");
1210
      out.println("<error>");
1211
      out.println(e.getMessage());
1212
      out.println("</error>");
1213 309 bojilova
    } finally {
1214 320 bojilova
      util.returnConnection(conn);
1215 309 bojilova
    }
1216 203 jones
  }
1217 731 bojilova
  // END OF DELETE SECTION
1218 68 higgins
1219 731 bojilova
  // VALIDATE SECTION
1220 68 higgins
  /**
1221 380 jones
   * Handle the validation request and return the results to the requestor
1222 68 higgins
   */
1223 185 jones
  private void handleValidateAction(PrintWriter out, Hashtable params,
1224
               HttpServletResponse response) {
1225 68 higgins
1226 103 jones
    // Get the document indicated
1227
    String valtext = null;
1228 309 bojilova
1229 103 jones
    try {
1230
      valtext = ((String[])params.get("valtext"))[0];
1231
    } catch (Exception nullpe) {
1232 68 higgins
1233 309 bojilova
      Connection conn = null;
1234 162 bojilova
      String docid = null;
1235 103 jones
      try {
1236
        // Find the document id number
1237 185 jones
        docid = ((String[])params.get("docid"))[0];
1238 309 bojilova
1239
        // get a connection from the pool
1240
        conn = util.getConnection();
1241 393 jones
1242 309 bojilova
        // Get the document indicated from the db
1243 393 jones
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1244
        valtext = xmldoc.toString();
1245 185 jones
1246 103 jones
      } catch (NullPointerException npe) {
1247 253 jones
        response.setContentType("text/xml");
1248
        out.println("<error>Error getting document ID: " + docid + "</error>");
1249 320 bojilova
        if ( conn != null ) { util.returnConnection(conn); }
1250 380 jones
        return;
1251 309 bojilova
      } catch (Exception e) {
1252
        response.setContentType("text/html");
1253
        out.println(e.getMessage());
1254
      } finally {
1255 320 bojilova
        util.returnConnection(conn);
1256 309 bojilova
      }
1257 103 jones
    }
1258 68 higgins
1259 309 bojilova
    Connection conn = null;
1260 103 jones
    try {
1261 309 bojilova
      // get a connection from the pool
1262
      conn = util.getConnection();
1263 253 jones
      DBValidate valobj = new DBValidate(saxparser,conn);
1264 185 jones
      boolean valid = valobj.validateString(valtext);
1265 68 higgins
1266
      // set content type and other response header fields first
1267 253 jones
      response.setContentType("text/xml");
1268
      out.println(valobj.returnErrors());
1269
1270 103 jones
    } catch (NullPointerException npe2) {
1271
      // set content type and other response header fields first
1272 253 jones
      response.setContentType("text/xml");
1273
      out.println("<error>Error validating document.</error>");
1274 309 bojilova
    } catch (Exception e) {
1275
      response.setContentType("text/html");
1276
      out.println(e.getMessage());
1277
    } finally {
1278 320 bojilova
      util.returnConnection(conn);
1279 309 bojilova
    }
1280 103 jones
  }
1281 731 bojilova
  // END OF VALIDATE SECTION
1282
1283
  // OTHER ACTION HANDLERS
1284 302 bojilova
1285
  /**
1286 688 bojilova
   * Handle "getaccesscontrol" action.
1287
   * Read Access Control List from db connection in XML format
1288
   */
1289
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
1290
                                       HttpServletResponse response,
1291 802 bojilova
                                       String username, String[] groupnames) {
1292 688 bojilova
1293
    Connection conn = null;
1294
    String docid = ((String[])params.get("docid"))[0];
1295
1296
    try {
1297
1298
        // get connection from the pool
1299
        conn = util.getConnection();
1300
        AccessControlList aclobj = new AccessControlList(conn);
1301 802 bojilova
        String acltext = aclobj.getACL(docid, username, groupnames);
1302 688 bojilova
        out.println(acltext);
1303
1304
    } catch (Exception e) {
1305
      out.println("<?xml version=\"1.0\"?>");
1306
      out.println("<error>");
1307
      out.println(e.getMessage());
1308
      out.println("</error>");
1309
    } finally {
1310
      util.returnConnection(conn);
1311
    }
1312
1313
  }
1314
1315
  /**
1316 731 bojilova
   * Handle the "getprincipals" action.
1317
   * Read all principals from authentication scheme in XML format
1318
   */
1319
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1320
                                         String password) {
1321
1322
    Connection conn = null;
1323
1324
    try {
1325
1326
        // get connection from the pool
1327
        AuthSession auth = new AuthSession();
1328
        String principals = auth.getPrincipals(user, password);
1329
        out.println(principals);
1330
1331
    } catch (Exception e) {
1332
      out.println("<?xml version=\"1.0\"?>");
1333
      out.println("<error>");
1334
      out.println(e.getMessage());
1335
      out.println("</error>");
1336
    } finally {
1337
      util.returnConnection(conn);
1338
    }
1339
1340
  }
1341
1342
  /**
1343 688 bojilova
   * Handle "getdoctypes" action.
1344 302 bojilova
   * Read all doctypes from db connection in XML format
1345
   */
1346
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1347
                                       HttpServletResponse response) {
1348
1349 309 bojilova
    Connection conn = null;
1350
1351 302 bojilova
    try {
1352
1353 309 bojilova
        // get connection from the pool
1354
        conn = util.getConnection();
1355
        DBUtil dbutil = new DBUtil(conn);
1356 302 bojilova
        String doctypes = dbutil.readDoctypes();
1357
        out.println(doctypes);
1358
1359
    } catch (Exception e) {
1360
      out.println("<?xml version=\"1.0\"?>");
1361
      out.println("<error>");
1362
      out.println(e.getMessage());
1363
      out.println("</error>");
1364 309 bojilova
    } finally {
1365 320 bojilova
      util.returnConnection(conn);
1366 309 bojilova
    }
1367 302 bojilova
1368
  }
1369
1370
  /**
1371 699 bojilova
   * Handle the "getdtdschema" action.
1372
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1373
   */
1374
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1375
                                        HttpServletResponse response) {
1376
1377
    Connection conn = null;
1378
    String doctype = null;
1379
    String[] doctypeArr = (String[])params.get("doctype");
1380
1381
    // get only the first doctype specified in the list of doctypes
1382
    // it could be done for all doctypes in that list
1383
    if (doctypeArr != null) {
1384
        doctype = ((String[])params.get("doctype"))[0];
1385
    }
1386
1387
    try {
1388
1389
        // get connection from the pool
1390
        conn = util.getConnection();
1391
        DBUtil dbutil = new DBUtil(conn);
1392
        String dtdschema = dbutil.readDTDSchema(doctype);
1393
        out.println(dtdschema);
1394
1395
    } catch (Exception e) {
1396
      out.println("<?xml version=\"1.0\"?>");
1397
      out.println("<error>");
1398
      out.println(e.getMessage());
1399
      out.println("</error>");
1400
    } finally {
1401
      util.returnConnection(conn);
1402
    }
1403
1404
  }
1405
1406
  /**
1407 688 bojilova
   * Handle the "getdataguide" action.
1408 302 bojilova
   * Read Data Guide for a given doctype from db connection in XML format
1409
   */
1410
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
1411
                                        HttpServletResponse response) {
1412
1413 309 bojilova
    Connection conn = null;
1414 316 bojilova
    String doctype = null;
1415
    String[] doctypeArr = (String[])params.get("doctype");
1416 309 bojilova
1417 316 bojilova
    // get only the first doctype specified in the list of doctypes
1418
    // it could be done for all doctypes in that list
1419
    if (doctypeArr != null) {
1420
        doctype = ((String[])params.get("doctype"))[0];
1421
    }
1422
1423 302 bojilova
    try {
1424
1425 309 bojilova
        // get connection from the pool
1426
        conn = util.getConnection();
1427
        DBUtil dbutil = new DBUtil(conn);
1428 316 bojilova
        String dataguide = dbutil.readDataGuide(doctype);
1429 302 bojilova
        out.println(dataguide);
1430
1431
    } catch (Exception e) {
1432
      out.println("<?xml version=\"1.0\"?>");
1433
      out.println("<error>");
1434
      out.println(e.getMessage());
1435
      out.println("</error>");
1436 309 bojilova
    } finally {
1437 320 bojilova
      util.returnConnection(conn);
1438 309 bojilova
    }
1439 302 bojilova
1440
  }
1441
1442 793 bojilova
  /**
1443
   * Handle the "getlastdocid" action.
1444
   * Get the latest docid with rev number from db connection in XML format
1445
   */
1446 847 jones
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
1447 793 bojilova
                                        HttpServletResponse response) {
1448
1449
    Connection conn = null;
1450 847 jones
    String scope = ((String[])params.get("scope"))[0];
1451
    if (scope == null) {
1452
        scope = ((String[])params.get("username"))[0];
1453
    }
1454 793 bojilova
1455
    try {
1456
1457
        // get connection from the pool
1458
        conn = util.getConnection();
1459
        DBUtil dbutil = new DBUtil(conn);
1460 847 jones
        String lastDocid = dbutil.getMaxDocid(scope);
1461 793 bojilova
        out.println("<?xml version=\"1.0\"?>");
1462
        out.println("<lastDocid>");
1463 847 jones
        out.println("  <scope>" + scope + "</scope>");
1464 793 bojilova
        out.println("  <docid>" + lastDocid + "</docid>");
1465
        out.println("</lastDocid>");
1466
1467
    } catch (Exception e) {
1468
      out.println("<?xml version=\"1.0\"?>");
1469
      out.println("<error>");
1470
      out.println(e.getMessage());
1471
      out.println("</error>");
1472
    } finally {
1473
      util.returnConnection(conn);
1474
    }
1475
1476
  }
1477
1478 798 jones
  /**
1479
   * Handle documents passed to metacat that are encoded using the
1480
   * "multipart/form-data" mime type.  This is typically used for uploading
1481
   * data files which may be binary and large.
1482
   */
1483
  private void handleMultipartForm(HttpServletRequest request,
1484
                                   HttpServletResponse response)
1485
  {
1486
    PrintWriter out = null;
1487
    String action = null;
1488
1489
    // Parse the multipart form, and save the parameters in a Hashtable and
1490
    // save the FileParts in a hashtable
1491
1492
    Hashtable params = new Hashtable();
1493
    Hashtable fileList = new Hashtable();
1494
1495
    try {
1496
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
1497
      MultipartParser mp = new MultipartParser(request, 200*1024*1024); // 200MB
1498
      Part part;
1499
      while ((part = mp.readNextPart()) != null) {
1500
        String name = part.getName();
1501
1502
        if (part.isParam()) {
1503
          // it's a parameter part
1504
          ParamPart paramPart = (ParamPart) part;
1505
          String value = paramPart.getStringValue();
1506
          params.put(name, value);
1507
          if (name.equals("action")) {
1508
            action = value;
1509
          }
1510
        } else if (part.isFile()) {
1511
          // it's a file part
1512
          FilePart filePart = (FilePart) part;
1513
          fileList.put(name, filePart);
1514
1515
          // Stop once the first file part is found, otherwise going onto the
1516
          // next part prevents access to the file contents.  So...for upload
1517
          // to work, the datafile must be the last part
1518
          break;
1519
        }
1520
      }
1521
    } catch (IOException ioe) {
1522
      try {
1523
        out = response.getWriter();
1524
      } catch (IOException ioe2) {
1525
        System.err.println("Fatal Error: couldn't get response output stream.");
1526
      }
1527
      out.println("<?xml version=\"1.0\"?>");
1528
      out.println("<error>");
1529
      out.println("Error: problem reading multipart data.");
1530
      out.println("</error>");
1531
    }
1532
1533
    // Get the session information
1534
    String username = null;
1535
    String password = null;
1536 802 bojilova
    String[] groupnames = null;
1537 798 jones
    String sess_id = null;
1538
1539
    // be aware of session expiration on every request
1540
    HttpSession sess = request.getSession(true);
1541
    if (sess.isNew()) {
1542
      // session expired or has not been stored b/w user requests
1543
      username = "public";
1544
      sess.setAttribute("username", username);
1545
    } else {
1546
      username = (String)sess.getAttribute("username");
1547
      password = (String)sess.getAttribute("password");
1548 802 bojilova
      groupnames = (String[])sess.getAttribute("groupnames");
1549 798 jones
      try {
1550
        sess_id = (String)sess.getId();
1551
      } catch(IllegalStateException ise) {
1552
        System.out.println("error in  handleMultipartForm: this shouldn't " +
1553
                           "happen: the session should be valid: " +
1554
                           ise.getMessage());
1555
      }
1556
    }
1557
1558
    if ( action.equals("upload")) {
1559
      if (username != null &&  !username.equals("public")) {
1560
        handleUploadAction(request, response, params, fileList,
1561 802 bojilova
                           username, groupnames);
1562 798 jones
      } else {
1563
        try {
1564
          out = response.getWriter();
1565
        } catch (IOException ioe2) {
1566
          System.err.println("Fatal Error: couldn't get response output stream.");
1567
        }
1568
        out.println("<?xml version=\"1.0\"?>");
1569
        out.println("<error>");
1570
        out.println("Permission denied for " + action);
1571
        out.println("</error>");
1572
      }
1573
    } else {
1574
      try {
1575
        out = response.getWriter();
1576
      } catch (IOException ioe2) {
1577
        System.err.println("Fatal Error: couldn't get response output stream.");
1578
      }
1579
      out.println("<?xml version=\"1.0\"?>");
1580
      out.println("<error>");
1581
      out.println("Error: action not registered.  Please report this error.");
1582
      out.println("</error>");
1583
    }
1584
  }
1585
1586
  /**
1587
   * Handle the upload action by saving the attached file to disk and
1588
   * registering it in the Metacat db
1589
   */
1590
  private void handleUploadAction(HttpServletRequest request,
1591
                                  HttpServletResponse response,
1592
                                  Hashtable params, Hashtable fileList,
1593 802 bojilova
                                  String username, String[] groupnames)
1594 798 jones
  {
1595
    PrintWriter out = null;
1596
    Connection conn = null;
1597
    String action = null;
1598
    String docid = null;
1599
1600
    response.setContentType("text/xml");
1601
    try {
1602
      out = response.getWriter();
1603
    } catch (IOException ioe2) {
1604
      System.err.println("Fatal Error: couldn't get response output stream.");
1605
    }
1606
1607
    if (params.containsKey("docid")) {
1608
      docid = (String)params.get("docid");
1609
    }
1610
1611
    // Make sure we have a docid and datafile
1612
    if (docid != null && fileList.containsKey("datafile")) {
1613
1614
      // Get a reference to the file part of the form
1615
      FilePart filePart = (FilePart)fileList.get("datafile");
1616
      String fileName = filePart.getFileName();
1617
      MetaCatUtil.debugMessage("Uploading filename: " + fileName);
1618
1619
      // Check if the right file existed in the uploaded data
1620
      if (fileName != null) {
1621
1622
        try {
1623
          // register the file in the database (which generates an exception if
1624
          // the docid is not acceptable or other untoward things happen
1625
          DocumentImpl.registerDocument(fileName, "BIN", docid, username, 1);
1626
1627
          // Save the data file to disk using "docid" as the name
1628
          dataDirectory.mkdirs();
1629
          File newFile = new File(dataDirectory, docid);
1630
          long size = filePart.writeTo(newFile);
1631
1632
          // set content type and other response header fields first
1633
          out.println("<?xml version=\"1.0\"?>");
1634
          out.println("<success>");
1635
          out.println("<docid>" + docid + "</docid>");
1636
          out.println("<size>" + size + "</size>");
1637
          out.println("</success>");
1638
1639
        } catch (Exception e) {
1640
          out.println("<?xml version=\"1.0\"?>");
1641
          out.println("<error>");
1642
          out.println(e.getMessage());
1643
          out.println("</error>");
1644
        }
1645
      } else {
1646
        // the field did not contain a file
1647
        out.println("<?xml version=\"1.0\"?>");
1648
        out.println("<error>");
1649
        out.println("The uploaded data did not contain a valid file.");
1650
        out.println("</error>");
1651
      }
1652
    } else {
1653
      // Error bcse docid missing or file missing
1654
      out.println("<?xml version=\"1.0\"?>");
1655
      out.println("<error>");
1656
      out.println("The uploaded data did not contain a valid docid " +
1657
                  "or valid file.");
1658
      out.println("</error>");
1659
    }
1660
  }
1661 46 jones
}