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 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 943 tao
 * action=squery -- structured query (see pathquery.dtd)<br>
76
 * action= -- export a zip format for data packadge<br>
77 731 bojilova
 * action=read -- read any metadata/data file from Metacat and from Internet<br>
78 205 jones
 * action=insert -- insert an XML document into the database store<br>
79
 * action=update -- update an XML document that is in the database store<br>
80
 * action=delete --  delete an XML document from the database store<br>
81
 * action=validate -- vallidate the xml contained in valtext<br>
82
 * doctype -- document type list returned by the query (publicID)<br>
83 154 jones
 * qformat=xml -- display resultset from query in XML<br>
84
 * qformat=html -- display resultset from query in HTML<br>
85 731 bojilova
 * qformat=zip -- zip resultset from query<br>
86 154 jones
 * docid=34 -- display the document with the document ID number 34<br>
87 205 jones
 * doctext -- XML text of the document to load into the database<br>
88 598 bojilova
 * acltext -- XML access text for a document to load into the database<br>
89
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog<br>
90 183 jones
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
91 205 jones
 * valtext -- XML text to be validated<br>
92 731 bojilova
 * abstractpath -- XPath in metadata document to read from<br>
93 688 bojilova
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
94
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
95 699 bojilova
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
96 688 bojilova
 * action=getdataguide -- retrieve a Data Guide<br>
97 725 bojilova
 * action=getprincipals -- retrieve a list of principals in XML<br>
98 205 jones
 * datadoc -- data document name (id)<br>
99
 * <p>
100
 * The particular combination of parameters that are valid for each
101
 * particular action value is quite specific.  This documentation
102
 * will be reorganized to reflect this information.
103 46 jones
 */
104
public class MetaCatServlet extends HttpServlet {
105
106 370 berkley
  private ServletConfig config = null;
107
  private ServletContext context = null;
108
  private String resultStyleURL = null;
109
  private String xmlcatalogfile = null;
110
  private String saxparser = null;
111 798 jones
  private String datafilepath = null;
112
  private File dataDirectory = null;
113 370 berkley
  private String servletpath = null;
114 822 jones
  private String htmlpath = null;
115 380 jones
  private PropertyResourceBundle options = null;
116
  private MetaCatUtil util = null;
117 1217 tao
  private DBConnectionPool connPool = null;
118 380 jones
119 50 jones
  /**
120
   * Initialize the servlet by creating appropriate database connections
121
   */
122 46 jones
  public void init( ServletConfig config ) throws ServletException {
123
    try {
124
      super.init( config );
125
      this.config = config;
126 332 bojilova
      this.context = config.getServletContext();
127 184 jones
      System.out.println("MetaCatServlet Initialize");
128 82 jones
129 184 jones
      util = new MetaCatUtil();
130 1217 tao
131
      //initial DBConnection pool
132
      connPool = DBConnectionPool.getInstance();
133 184 jones
134 83 jones
      // Get the configuration file information
135 184 jones
      resultStyleURL = util.getOption("resultStyleURL");
136
      xmlcatalogfile = util.getOption("xmlcatalogfile");
137
      saxparser = util.getOption("saxparser");
138 798 jones
      datafilepath = util.getOption("datafilepath");
139
      dataDirectory = new File(datafilepath);
140 360 bojilova
      servletpath = util.getOption("servletpath");
141
      htmlpath = util.getOption("htmlpath");
142 598 bojilova
143 1217 tao
144 46 jones
    } catch ( ServletException ex ) {
145
      throw ex;
146 1217 tao
    } catch (SQLException e) {
147
      MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
148
                                          +e.getMessage(), 20);
149 46 jones
    }
150
  }
151
152 320 bojilova
  /**
153
   * Close all db connections from the pool
154
   */
155
  public void destroy() {
156 1217 tao
      // Close all db connection
157
      connPool.release();
158 320 bojilova
  }
159
160 50 jones
  /** Handle "GET" method requests from HTTP clients */
161 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
162
    throws ServletException, IOException {
163
164 48 jones
    // Process the data and send back the response
165 59 jones
    handleGetOrPost(request, response);
166 48 jones
  }
167
168 50 jones
  /** Handle "POST" method requests from HTTP clients */
169 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
170
    throws ServletException, IOException {
171
172
    // Process the data and send back the response
173 59 jones
    handleGetOrPost(request, response);
174 48 jones
  }
175
176 49 jones
  /**
177 50 jones
   * Control servlet response depending on the action parameter specified
178 49 jones
   */
179 382 berkley
  private void handleGetOrPost(HttpServletRequest request,
180 798 jones
                               HttpServletResponse response)
181
                               throws ServletException, IOException
182
  {
183 48 jones
184 309 bojilova
    if ( util == null ) {
185
        util = new MetaCatUtil();
186
    }
187 1221 tao
    /*MetaCatUtil.debugMessage("Connection pool size: "
188 1217 tao
                                     +connPool.getSizeOfDBConnectionPool(),10);
189
    MetaCatUtil.debugMessage("Free DBConnection number: "
190 1221 tao
                                  +connPool.getFreeDBConnectionNumber(), 10);*/
191
    //If all DBConnection in the pool are free and DBConnection pool
192
    //size is greater than initial value, shrink the connection pool
193
    //size to initial value
194
    DBConnectionPool.shrinkDBConnectionPoolSize();
195
196 1217 tao
    //Debug message to print out the method which have a busy DBConnection
197
    connPool.printMethodNameHavingBusyDBConnection();
198
199 800 jones
    String ctype = request.getContentType();
200
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
201 798 jones
      handleMultipartForm(request, response);
202
    } else {
203 943 tao
204 49 jones
205 798 jones
      String name = null;
206
      String[] value = null;
207
      String[] docid = new String[3];
208
      Hashtable params = new Hashtable();
209
      Enumeration paramlist = request.getParameterNames();
210 1217 tao
211
212 798 jones
      while (paramlist.hasMoreElements()) {
213 1217 tao
214 798 jones
        name = (String)paramlist.nextElement();
215
        value = request.getParameterValues(name);
216
217
        // Decode the docid and mouse click information
218
        if (name.endsWith(".y")) {
219
          docid[0] = name.substring(0,name.length()-2);
220
          params.put("docid", docid);
221
          name = "ypos";
222 648 berkley
        }
223 798 jones
        if (name.endsWith(".x")) {
224
          name = "xpos";
225
        }
226
227
        params.put(name,value);
228 425 bojilova
      }
229 798 jones
230 1217 tao
231
      //handle param is emptpy
232
      if (params.isEmpty() || params == null)
233
      {
234
        return;
235
      }
236 798 jones
      //if the user clicked on the input images, decode which image
237
      //was clicked then set the action.
238
      String action = ((String[])params.get("action"))[0];
239 1217 tao
      util.debugMessage("Line 230: Action is: " + action, 1);
240 798 jones
241
      // This block handles session management for the servlet
242
      // by looking up the current session information for all actions
243
      // other than "login" and "logout"
244
      String username = null;
245
      String password = null;
246 802 bojilova
      String[] groupnames = null;
247 798 jones
      String sess_id = null;
248
249
      // handle login action
250
      if (action.equals("login")) {
251 1217 tao
        PrintWriter out = response.getWriter();
252
        handleLoginAction(out, params, request, response);
253
        out.close();
254 798 jones
255
      // handle logout action
256
      } else if (action.equals("logout")) {
257 1217 tao
        PrintWriter out = response.getWriter();
258
        handleLogoutAction(out, params, request, response);
259
        out.close();
260 1221 tao
261
      // handle shrink DBConnection request
262
      } else if (action.equals("shrink")) {
263
        PrintWriter out = response.getWriter();
264
        boolean success = false;
265
        //If all DBConnection in the pool are free and DBConnection pool
266
        //size is greater than initial value, shrink the connection pool
267
        //size to initial value
268
        success = DBConnectionPool.shrinkConnectionPoolSize();
269
        if (success)
270
        {
271
          //if successfully shrink the pool size to initial value
272
          out.println("DBConnection Pool shrink successfully");
273
        }//if
274
        else
275
        {
276
          out.println("DBConnection pool couldn't shrink successfully");
277
        }
278
       //close out put
279
        out.close();
280
281 798 jones
      // aware of session expiration on every request
282
      } else {
283
284
        HttpSession sess = request.getSession(true);
285
        if (sess.isNew()) {
286
          // session expired or has not been stored b/w user requests
287
          username = "public";
288
          sess.setAttribute("username", username);
289
        } else {
290
          username = (String)sess.getAttribute("username");
291
          password = (String)sess.getAttribute("password");
292 802 bojilova
          groupnames = (String[])sess.getAttribute("groupnames");
293 798 jones
          try {
294
            sess_id = (String)sess.getId();
295
          } catch(IllegalStateException ise) {
296
            System.out.println("error in handleGetOrPost: this shouldn't " +
297
                               "happen: the session should be valid: " +
298
                               ise.getMessage());
299
          }
300
        }
301
      }
302
303 947 tao
       // Now that we know the session is valid, we can delegate the request
304 798 jones
      // to a particular action handler
305
      if(action.equals("query")) {
306 1217 tao
        PrintWriter out = response.getWriter();
307
        handleQuery(out,params,response,username,groupnames);
308
        out.close();
309 798 jones
      } else if(action.equals("squery")) {
310 1217 tao
        PrintWriter out = response.getWriter();
311 798 jones
        if(params.containsKey("query")) {
312 1217 tao
         handleSQuery(out, params,response,username,groupnames);
313
         out.close();
314 798 jones
        } else {
315
          out.println("Illegal action squery without \"query\" parameter");
316 1217 tao
          out.close();
317 798 jones
        }
318 943 tao
      } else if (action.equals("export")) {
319 949 tao
320 1292 tao
        handleExportAction(params, response, username, groupnames, password);
321 798 jones
      } else if (action.equals("read")) {
322 1292 tao
        handleReadAction(params, response, username,password, groupnames);
323 798 jones
      } else if (action.equals("insert") || action.equals("update")) {
324 458 berkley
        PrintWriter out = response.getWriter();
325 798 jones
        if ( (username != null) &&  !username.equals("public") ) {
326 802 bojilova
          handleInsertOrUpdateAction(out,params,response,username,groupnames);
327 798 jones
        } else {
328
          out.println("Permission denied for " + action);
329 1217 tao
        }
330
        out.close();
331 798 jones
      } else if (action.equals("delete")) {
332
        PrintWriter out = response.getWriter();
333
        if ( (username != null) &&  !username.equals("public") ) {
334 802 bojilova
          handleDeleteAction(out, params, response, username, groupnames);
335 798 jones
        } else {
336
          out.println("Permission denied for " + action);
337 1217 tao
        }
338
        out.close();
339 798 jones
      } else if (action.equals("validate")) {
340
        PrintWriter out = response.getWriter();
341 1217 tao
        handleValidateAction(out, params, response);
342
        out.close();
343 798 jones
      } else if (action.equals("getaccesscontrol")) {
344
        PrintWriter out = response.getWriter();
345 802 bojilova
        handleGetAccessControlAction(out,params,response,username,groupnames);
346 1217 tao
        out.close();
347 798 jones
      } else if (action.equals("getprincipals")) {
348
        PrintWriter out = response.getWriter();
349 1217 tao
        handleGetPrincipalsAction(out, username, password);
350
        out.close();
351 798 jones
      } else if (action.equals("getdoctypes")) {
352
        PrintWriter out = response.getWriter();
353 1217 tao
        handleGetDoctypesAction(out, params, response);
354
        out.close();
355 798 jones
      } else if (action.equals("getdtdschema")) {
356
        PrintWriter out = response.getWriter();
357 1217 tao
        handleGetDTDSchemaAction(out, params, response);
358
        out.close();
359 798 jones
      } else if (action.equals("getdataguide")) {
360
        PrintWriter out = response.getWriter();
361 1217 tao
        handleGetDataGuideAction(out, params, response);
362
        out.close();
363 798 jones
      } else if (action.equals("getlastdocid")) {
364
        PrintWriter out = response.getWriter();
365 1217 tao
        handleGetMaxDocidAction(out, params, response);
366
        out.close();
367 1292 tao
      } else if (action.equals("getrevisionanddoctype")) {
368
        PrintWriter out = response.getWriter();
369
        handleGetRevisionAndDocTypeAction(out, params);
370
        out.close();
371 798 jones
      } else if (action.equals("login") || action.equals("logout")) {
372
      } else if (action.equals("protocoltest")) {
373
        String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
374
        try {
375
          testURL = ((String[])params.get("url"))[0];
376
        } catch (Throwable t) {
377
        }
378
        String phandler = System.getProperty("java.protocol.handler.pkgs");
379
        response.setContentType("text/html");
380
        PrintWriter out = response.getWriter();
381
        out.println("<body bgcolor=\"white\">");
382
        out.println("<p>Handler property: <code>" + phandler + "</code></p>");
383
        out.println("<p>Starting test for:<br>");
384
        out.println("    " + testURL + "</p>");
385
        try {
386
          URL u = new URL(testURL);
387
          out.println("<pre>");
388
          out.println("Protocol: " + u.getProtocol());
389
          out.println("    Host: " + u.getHost());
390
          out.println("    Port: " + u.getPort());
391
          out.println("    Path: " + u.getPath());
392
          out.println("     Ref: " + u.getRef());
393
          String pquery = u.getQuery();
394
          out.println("   Query: " + pquery);
395
          out.println("  Params: ");
396
          if (pquery != null) {
397
            Hashtable qparams = util.parseQuery(u.getQuery());
398
            for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
399
              String pname = (String)en.nextElement();
400
              String pvalue = (String)qparams.get(pname);
401
              out.println("    " + pname + ": " + pvalue);
402
            }
403 566 jones
          }
404 798 jones
          out.println("</pre>");
405
          out.println("</body>");
406
          out.close();
407
        } catch (MalformedURLException mue) {
408
          System.out.println("bad url from MetacatServlet.handleGetOrPost");
409
          out.println(mue.getMessage());
410
          mue.printStackTrace(out);
411
          out.close();
412 566 jones
        }
413 798 jones
      } else {
414
        PrintWriter out = response.getWriter();
415
        out.println("<?xml version=\"1.0\"?>");
416
        out.println("<error>");
417
        out.println("Error: action not registered.  Please report this error.");
418
        out.println("</error>");
419 1217 tao
        out.close();
420 566 jones
      }
421 798 jones
422 1217 tao
      //util.closeConnections();
423 798 jones
      // Close the stream to the client
424 1217 tao
      //out.close();
425 46 jones
    }
426
  }
427 355 berkley
428 731 bojilova
  // LOGIN & LOGOUT SECTION
429 50 jones
  /**
430 509 bojilova
   * Handle the login request. Create a new session object.
431 503 bojilova
   * Do user authentication through the session.
432 210 bojilova
   */
433
  private void handleLoginAction(PrintWriter out, Hashtable params,
434
               HttpServletRequest request, HttpServletResponse response) {
435 251 bojilova
436 503 bojilova
    AuthSession sess = null;
437 228 bojilova
    String un = ((String[])params.get("username"))[0];
438
    String pw = ((String[])params.get("password"))[0];
439 297 bojilova
    String action = ((String[])params.get("action"))[0];
440 509 bojilova
    String qformat = ((String[])params.get("qformat"))[0];
441 332 bojilova
442 297 bojilova
    try {
443 509 bojilova
      sess = new AuthSession();
444 297 bojilova
    } catch (Exception e) {
445 675 berkley
      System.out.println("error in MetacatServlet.handleLoginAction: " +
446
                          e.getMessage());
447 297 bojilova
      out.println(e.getMessage());
448 509 bojilova
      return;
449 297 bojilova
    }
450 509 bojilova
    boolean isValid = sess.authenticate(request, un, pw);
451
    // format and transform the output
452 832 jones
    if (qformat.equals("xml")) {
453
      response.setContentType("text/xml");
454
      out.println(sess.getMessage());
455
    } else {
456 1217 tao
457 503 bojilova
      try {
458 1217 tao
459
        DBTransform trans = new DBTransform();
460 509 bojilova
        response.setContentType("text/html");
461 510 bojilova
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
462 832 jones
                                   "-//W3C//HTML//EN", qformat, out);
463 1217 tao
464 509 bojilova
      } catch(Exception e) {
465 1217 tao
466
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
467
                                +e.getMessage(), 30);
468 509 bojilova
      }
469
470
    // any output is returned
471 503 bojilova
    }
472 370 berkley
  }
473 509 bojilova
474
  /**
475
   * Handle the logout request. Close the connection.
476
   */
477
  private void handleLogoutAction(PrintWriter out, Hashtable params,
478
               HttpServletRequest request, HttpServletResponse response) {
479
480
    String qformat = ((String[])params.get("qformat"))[0];
481
482
    // close the connection
483
    HttpSession sess = request.getSession(false);
484
    if (sess != null) { sess.invalidate();  }
485
486
    // produce output
487
    StringBuffer output = new StringBuffer();
488
    output.append("<?xml version=\"1.0\"?>");
489 510 bojilova
    output.append("<logout>");
490
    output.append("User logged out");
491
    output.append("</logout>");
492 509 bojilova
493
    //format and transform the output
494 832 jones
    if (qformat.equals("xml")) {
495
      response.setContentType("text/xml");
496
      out.println(output.toString());
497
    } else {
498 1217 tao
499 509 bojilova
      try {
500 1217 tao
501
        DBTransform trans = new DBTransform();
502 509 bojilova
        response.setContentType("text/html");
503 510 bojilova
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
504 832 jones
                                   "-//W3C//HTML//EN", qformat, out);
505 1217 tao
506 509 bojilova
      } catch(Exception e) {
507 1217 tao
508
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
509
                                  +e.getMessage(), 30);
510 509 bojilova
      }
511
    }
512
  }
513 731 bojilova
  // END OF LOGIN & LOGOUT SECTION
514 370 berkley
515 731 bojilova
  // SQUERY & QUERY SECTION
516 373 berkley
  /**
517 380 jones
   * Retreive the squery xml, execute it and display it
518
   *
519
   * @param out the output stream to the client
520
   * @param params the Hashtable of parameters that should be included
521
   * in the squery.
522
   * @param response the response object linked to the client
523
   * @param conn the database connection
524
   */
525
  protected void handleSQuery(PrintWriter out, Hashtable params,
526 802 bojilova
                 HttpServletResponse response, String user, String[] groups)
527 373 berkley
  {
528 380 jones
    String xmlquery = ((String[])params.get("query"))[0];
529
    String qformat = ((String[])params.get("qformat"))[0];
530 465 berkley
    String resultdoc = null;
531
532 802 bojilova
    Hashtable doclist = runQuery(xmlquery, user, groups);
533 444 berkley
534 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
535
536 380 jones
    //format and transform the results
537 832 jones
    if(qformat.equals("xml")) {
538 380 jones
      response.setContentType("text/xml");
539
      out.println(resultdoc);
540
    } else {
541 832 jones
      transformResultset(resultdoc, response, out, qformat);
542 380 jones
    }
543 341 berkley
  }
544
545
   /**
546 380 jones
    * Create the xml query, execute it and display the results.
547
    *
548
    * @param out the output stream to the client
549
    * @param params the Hashtable of parameters that should be included
550 370 berkley
    * in the squery.
551 380 jones
    * @param response the response object linked to the client
552 370 berkley
    */
553 375 berkley
  protected void handleQuery(PrintWriter out, Hashtable params,
554 802 bojilova
                 HttpServletResponse response, String user, String[] groups)
555 341 berkley
  {
556 370 berkley
    //create the query and run it
557 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
558 802 bojilova
    Hashtable doclist = runQuery(xmlquery, user, groups);
559 465 berkley
    String qformat = ((String[])params.get("qformat"))[0];
560
    String resultdoc = null;
561
562
    resultdoc = createResultDocument(doclist, transformQuery(params));
563 425 bojilova
564 370 berkley
    //format and transform the results
565 832 jones
    if(qformat.equals("xml")) {
566 370 berkley
      response.setContentType("text/xml");
567
      out.println(resultdoc);
568 443 berkley
    } else {
569 832 jones
      transformResultset(resultdoc, response, out, qformat);
570 370 berkley
    }
571 341 berkley
  }
572
573
  /**
574 384 berkley
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
575
   * so it can properly be placed in the <query> tag of the resultset.
576
   * This method is overwritable so that other applications can customize
577
   * the structure of what is in the <query> tag.
578
   *
579
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
580
   */
581
  protected String transformQuery(Hashtable params)
582
  {
583
    //DBQuery.createSQuery is a re-calling of a previously called
584
    //function but it is necessary
585
    //so that overriding methods have access to the params hashtable
586
    String xmlquery = DBQuery.createSQuery(params);
587
    //the <?xml version="1.0"?> tag is the first 22 characters of the
588
    xmlquery = xmlquery.trim();
589
    int index = xmlquery.indexOf("?>");
590
    return xmlquery.substring(index + 2, xmlquery.length());
591
  }
592
593
  /**
594 443 berkley
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
595
   * string as a param instead of a hashtable.
596
   *
597
   * @param xmlquery a string representing a query.
598
   */
599
  protected String transformQuery(String xmlquery)
600
  {
601
    xmlquery = xmlquery.trim();
602
    int index = xmlquery.indexOf("?>");
603
    return xmlquery.substring(index + 2, xmlquery.length());
604
  }
605
606
  /**
607 380 jones
   * Run the query and return a hashtable of results.
608
   *
609
   * @param xmlquery the query to run
610
   */
611 802 bojilova
  private Hashtable runQuery(String xmlquery, String user, String[] groups)
612 341 berkley
  {
613
    Hashtable doclist=null;
614 1217 tao
615 341 berkley
    try
616
    {
617 1217 tao
618
      DBQuery queryobj = new DBQuery(saxparser);
619 802 bojilova
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,groups);
620 1217 tao
621 441 bojilova
      return doclist;
622 341 berkley
    }
623
    catch (Exception e)
624
    {
625 1217 tao
626
      MetaCatUtil.debugMessage("Error in MetacatServlet.runQuery: "
627
                                                      + e.getMessage(), 30);
628 341 berkley
      doclist = null;
629
      return doclist;
630
    }
631
  }
632
633 380 jones
  /**
634 370 berkley
   * Transorms an xml resultset document to html and sends it to the browser
635 380 jones
   *
636 370 berkley
   * @param resultdoc the string representation of the document that needs
637
   * to be transformed.
638
   * @param response the HttpServletResponse object bound to the client.
639
   * @param out the output stream to the client
640 832 jones
   * @param qformat the name of the style-set to use for transformations
641 375 berkley
   */
642
  protected void transformResultset(String resultdoc,
643 380 jones
                                    HttpServletResponse response,
644 832 jones
                                    PrintWriter out, String qformat)
645 370 berkley
  {
646 1217 tao
647 380 jones
    try {
648 1217 tao
649
      DBTransform trans = new DBTransform();
650 370 berkley
      response.setContentType("text/html");
651
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
652 832 jones
                                 "-//W3C//HTML//EN", qformat, out);
653 1217 tao
654 382 berkley
    }
655
    catch(Exception e)
656
    {
657 1217 tao
658
      MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
659
                                +e.getMessage(), 30);
660 370 berkley
    }
661
  }
662
663 355 berkley
  /**
664
   * Transforms a hashtable of documents to an xml or html result.
665 380 jones
   *
666 355 berkley
   * @param doclist- the hashtable to transform
667 744 jones
   * @param xmlquery- the query that returned the doclist result
668 355 berkley
   */
669 375 berkley
  protected String createResultDocument(Hashtable doclist, String xmlquery)
670 341 berkley
  {
671
    // Create a buffer to hold the xml result
672
    StringBuffer resultset = new StringBuffer();
673
674 382 berkley
    // Print the resulting root nodes
675 341 berkley
    String docid = null;
676
    String document = null;
677
    resultset.append("<?xml version=\"1.0\"?>\n");
678
    resultset.append("<resultset>\n");
679 465 berkley
680 384 berkley
    resultset.append("  <query>" + xmlquery + "</query>");
681 478 berkley
682
    if(doclist != null)
683 341 berkley
    {
684 478 berkley
      Enumeration doclistkeys = doclist.keys();
685
      while (doclistkeys.hasMoreElements())
686
      {
687
        docid = (String)doclistkeys.nextElement();
688
        document = (String)doclist.get(docid);
689
        resultset.append("  <document>" + document + "</document>");
690
      }
691
    }
692
693 341 berkley
    resultset.append("</resultset>");
694 370 berkley
    return resultset.toString();
695 341 berkley
  }
696 731 bojilova
  // END OF SQUERY & QUERY SECTION
697 437 berkley
698 943 tao
 //Exoport section
699
 /**
700
   * Handle the "export" request of data package from Metacat in zip format
701
   * @param params the Hashtable of HTTP request parameters
702
   * @param response the HTTP response object linked to the client
703
   * @param user the username sent the request
704
   * @param groups the user's groupnames
705
   */
706 1292 tao
  private void handleExportAction(Hashtable params,
707
    HttpServletResponse response, String user, String[] groups, String passWord)
708 943 tao
  {
709 1292 tao
    // Output stream
710 943 tao
    ServletOutputStream out = null;
711 1292 tao
    // Zip output stream
712 943 tao
    ZipOutputStream zOut = null;
713
    DocumentImpl docImpls=null;
714
    DBQuery queryObj=null;
715 1217 tao
716 943 tao
    String[] docs = new String[10];
717
    String docId = "";
718
719
    try
720
    {
721
      // read the params
722 1292 tao
      if (params.containsKey("docid"))
723
      {
724 943 tao
        docs = (String[])params.get("docid");
725 1292 tao
      }//if
726
      // Create a DBuery to handle export
727
      queryObj = new DBQuery(saxparser);
728
      // Get the docid
729 943 tao
      docId=docs[0];
730 1292 tao
      // Make sure the client specify docid
731
      if (docId == null || docId.equals(""))
732
      {
733
        response.setContentType("text/xml"); //MIME type
734
        // Get a printwriter
735
        PrintWriter pw = response.getWriter();
736
        // Send back message
737
        pw.println("<?xml version=\"1.0\"?>");
738
        pw.println("<error>");
739
        pw.println("You didn't specify requested docid");
740
        pw.println("</error>");
741
        // Close printwriter
742
        pw.close();
743
        return;
744
      }//if
745
      // Get output stream
746 943 tao
      out = response.getOutputStream();
747
      response.setContentType("application/zip"); //MIME type
748
      zOut = new ZipOutputStream(out);
749 1292 tao
      zOut =queryObj.getZippedPackage(docId, out, user, groups, passWord);
750 943 tao
      zOut.finish(); //terminate the zip file
751
      zOut.close();  //close the zip stream
752 1056 tao
753 1292 tao
    }//try
754 943 tao
    catch (Exception e)
755
    {
756
      try
757
      {
758
        response.setContentType("text/xml"); //MIME type
759 1292 tao
        // Send error message back
760 943 tao
        if (out != null)
761
        {
762
            PrintWriter pw = new PrintWriter(out);
763
            pw.println("<?xml version=\"1.0\"?>");
764
            pw.println("<error>");
765
            pw.println(e.getMessage());
766
            pw.println("</error>");
767 1292 tao
            // Close printwriter
768 943 tao
            pw.close();
769 1292 tao
            // Close output stream
770
            out.close();
771
        }//if
772
        // Close zip output stream
773 943 tao
        if ( zOut != null )
774
        {
775
          zOut.close();
776 1292 tao
        }//if
777
      }//try
778 943 tao
      catch (IOException ioe)
779
      {
780 1217 tao
        MetaCatUtil.debugMessage("Problem with the servlet output " +
781 1292 tao
                           "in MetacatServlet.handleExportAction: " +
782 1217 tao
                           ioe.getMessage(), 30);
783 1292 tao
      }//catch
784 943 tao
785 1292 tao
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleExportAction: " +
786 1217 tao
                         e.getMessage(), 30);
787 1292 tao
      e.printStackTrace(System.out);
788 943 tao
789
    }//catch
790 1292 tao
791 943 tao
  }//handleExportAction
792
793 731 bojilova
  // READ SECTION
794
  /**
795
   * Handle the "read" request of metadata/data files from Metacat
796
   * or any files from Internet;
797
   * transformed metadata XML document into HTML presentation if requested;
798
   * zip files when more than one were requested.
799
   *
800
   * @param params the Hashtable of HTTP request parameters
801
   * @param response the HTTP response object linked to the client
802
   * @param user the username sent the request
803 802 bojilova
   * @param groups the user's groupnames
804 437 berkley
   */
805 731 bojilova
  private void handleReadAction(Hashtable params, HttpServletResponse response,
806 1292 tao
                                String user, String passWord, String[] groups)
807 437 berkley
  {
808 731 bojilova
    ServletOutputStream out = null;
809
    ZipOutputStream zout = null;
810 1292 tao
    PrintWriter pw = null;
811
    boolean zip = false;
812 731 bojilova
813
    try {
814
      String[] docs = new String[0];
815
      String docid = "";
816
      String qformat = "";
817
      String abstrpath = null;
818 1292 tao
819 731 bojilova
      // read the params
820
      if (params.containsKey("docid")) {
821
        docs = (String[])params.get("docid");
822 437 berkley
      }
823 731 bojilova
      if (params.containsKey("qformat")) {
824
        qformat = ((String[])params.get("qformat"))[0];
825 437 berkley
      }
826 731 bojilova
      if (params.containsKey("abstractpath")) {
827
        abstrpath = ((String[])params.get("abstractpath"))[0];
828 738 bojilova
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
829
          viewAbstract(response, abstrpath, docs[0]);
830
          return;
831
        }
832 437 berkley
      }
833 731 bojilova
      if ( (docs.length > 1) || qformat.equals("zip") ) {
834
        zip = true;
835
        out = response.getOutputStream();
836
        response.setContentType("application/zip"); //MIME type
837
        zout = new ZipOutputStream(out);
838
      }
839
      // go through the list of docs to read
840
      for (int i=0; i < docs.length; i++ ) {
841
        try {
842
843
          URL murl = new URL(docs[i]);
844
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
845
          // case docid="http://.../?docid=aaa"
846
          // or docid="metacat://.../?docid=bbb"
847
          if (murlQueryStr.containsKey("docid")) {
848
            // get only docid, eliminate the rest
849
            docid = (String)murlQueryStr.get("docid");
850
            if ( zip ) {
851 947 tao
              addDocToZip(docid, zout, user, groups);
852 731 bojilova
            } else {
853
              readFromMetacat(response, docid, qformat, abstrpath,
854 802 bojilova
                              user, groups, zip, zout);
855 731 bojilova
            }
856
857
          // case docid="http://.../filename"
858
          } else {
859
            docid = docs[i];
860
            if ( zip ) {
861 947 tao
              addDocToZip(docid, zout, user, groups);
862 731 bojilova
            } else {
863
              readFromURLConnection(response, docid);
864
            }
865
          }
866
867
        // case docid="ccc"
868
        } catch (MalformedURLException mue) {
869
          docid = docs[i];
870
          if ( zip ) {
871 947 tao
            addDocToZip(docid, zout, user, groups);
872 731 bojilova
          } else {
873
            readFromMetacat(response, docid, qformat, abstrpath,
874 802 bojilova
                            user, groups, zip, zout);
875 731 bojilova
          }
876
        }
877
878
      } /* end for */
879
880
      if ( zip ) {
881
        zout.finish(); //terminate the zip file
882
        zout.close();  //close the zip stream
883
      }
884
885 947 tao
886 1292 tao
    }
887
    // To handle doc not found exception
888
    catch (McdbDocNotFoundException notFoundE)
889
    {
890
      // the docid which didn't be found
891
      String notFoundDocId = notFoundE.getUnfoundDocId();
892
      String notFoundRevision = notFoundE.getUnfoundRevision();
893
      MetaCatUtil.debugMessage("Missed id: "+ notFoundDocId, 30);
894
      MetaCatUtil.debugMessage("Missed rev: "+ notFoundRevision, 30);
895
      try
896
      {
897
        // read docid from remote server
898
        readFromRemoteMetaCat(response, notFoundDocId, notFoundRevision,
899
                                              user, passWord, out, zip, zout);
900
        // Close zout outputstream
901
        if ( zout != null)
902
        {
903
          zout.close();
904
        }
905
        // close output stream
906
        if (out != null)
907
        {
908
          out.close();
909
        }
910
911
      }//try
912
      catch ( Exception exc)
913
      {
914
        MetaCatUtil.debugMessage("Erorr in MetacatServlet.hanldReadAction: "+
915
                                      exc.getMessage(), 30);
916
        try
917
        {
918
          if (out != null)
919
          {
920
            response.setContentType("text/xml");
921
            // Send back error message by printWriter
922
            pw = new PrintWriter(out);
923
            pw.println("<?xml version=\"1.0\"?>");
924
            pw.println("<error>");
925
            pw.println(notFoundE.getMessage());
926
            pw.println("</error>");
927
            pw.close();
928
            out.close();
929
930
          }
931
          else
932
          {
933
           response.setContentType("text/xml"); //MIME type
934
           // Send back error message if out = null
935
           if (pw == null)
936
           {
937
             // If pw is null, open the respnose
938
            pw = response.getWriter();
939
           }
940
           pw.println("<?xml version=\"1.0\"?>");
941
           pw.println("<error>");
942
           pw.println(notFoundE.getMessage());
943
           pw.println("</error>");
944
           pw.close();
945
        }
946
        // close zout
947
        if ( zout != null )
948
        {
949
          zout.close();
950
        }
951
        }//try
952
        catch (IOException ie)
953
        {
954
          MetaCatUtil.debugMessage("Problem with the servlet output " +
955
                           "in MetacatServlet.handleReadAction: " +
956
                           ie.getMessage(), 30);
957
        }//cathch
958
      }//catch
959
    }// catch McdbDocNotFoundException
960
    catch (Exception e)
961
    {
962 731 bojilova
      try {
963 1292 tao
964 845 jones
        if (out != null) {
965 1292 tao
            response.setContentType("text/xml"); //MIME type
966
            pw = new PrintWriter(out);
967 845 jones
            pw.println("<?xml version=\"1.0\"?>");
968
            pw.println("<error>");
969
            pw.println(e.getMessage());
970
            pw.println("</error>");
971
            pw.close();
972 1292 tao
            out.close();
973 845 jones
        }
974 1292 tao
        else
975
        {
976
           response.setContentType("text/xml"); //MIME type
977
           // Send back error message if out = null
978
           if ( pw == null)
979
           {
980
            pw = response.getWriter();
981
           }
982
           pw.println("<?xml version=\"1.0\"?>");
983
           pw.println("<error>");
984
           pw.println(e.getMessage());
985
           pw.println("</error>");
986
           pw.close();
987
988
        }
989
        // Close zip output stream
990 731 bojilova
        if ( zout != null ) { zout.close(); }
991 1292 tao
992 731 bojilova
      } catch (IOException ioe) {
993 1292 tao
        MetaCatUtil.debugMessage("Problem with the servlet output " +
994 731 bojilova
                           "in MetacatServlet.handleReadAction: " +
995 1292 tao
                           ioe.getMessage(), 30);
996 731 bojilova
        ioe.printStackTrace(System.out);
997
998
      }
999
1000
      System.out.println("Error in MetacatServlet.handleReadAction: " +
1001 675 berkley
                         e.getMessage());
1002 731 bojilova
      e.printStackTrace(System.out);
1003 437 berkley
    }
1004
1005
  }
1006 731 bojilova
1007
  // read metadata or data from Metacat
1008
  private void readFromMetacat(HttpServletResponse response, String docid,
1009
                               String qformat, String abstrpath, String user,
1010 943 tao
                             String[] groups, boolean zip, ZipOutputStream zout)
1011 731 bojilova
               throws ClassNotFoundException, IOException, SQLException,
1012
                      McdbException, Exception
1013 453 berkley
  {
1014 1217 tao
1015 731 bojilova
    try {
1016 1217 tao
1017 453 berkley
1018 1217 tao
      DocumentImpl doc = new DocumentImpl(docid);
1019
1020 947 tao
      //check the permission for read
1021 1217 tao
      if (!doc.hasReadPermission(user, groups, docid))
1022 947 tao
      {
1023
        Exception e = new Exception("User " + user + " does not have permission"
1024
                       +" to read the document with the docid " + docid);
1025 1217 tao
1026 947 tao
        throw e;
1027
      }
1028
1029 731 bojilova
      if ( doc.getRootNodeID() == 0 ) {
1030
        // this is data file
1031
        String filepath = util.getOption("datafilepath");
1032
        if(!filepath.endsWith("/")) {
1033
          filepath += "/";
1034
        }
1035 1292 tao
        String filename = filepath + docid;
1036
        FileInputStream fin = null;
1037
        fin = new FileInputStream(filename);
1038
1039
        //MIME type
1040 731 bojilova
        String contentType = getServletContext().getMimeType(filename);
1041
        if (contentType == null) {
1042
          if (filename.endsWith(".xml")) {
1043
            contentType="text/xml";
1044
          } else if (filename.endsWith(".css")) {
1045
            contentType="text/css";
1046
          } else if (filename.endsWith(".dtd")) {
1047
            contentType="text/plain";
1048
          } else if (filename.endsWith(".xsd")) {
1049 733 bojilova
            contentType="text/xml";
1050 731 bojilova
          } else if (filename.endsWith("/")) {
1051 733 bojilova
            contentType="text/html";
1052 731 bojilova
          } else {
1053 733 bojilova
            File f = new File(filename);
1054
            if ( f.isDirectory() ) {
1055
              contentType="text/html";
1056
            } else {
1057
              contentType="application/octet-stream";
1058
            }
1059 453 berkley
          }
1060
        }
1061 731 bojilova
        response.setContentType(contentType);
1062 733 bojilova
        // if we decide to use "application/octet-stream" for all data returns
1063
        // response.setContentType("application/octet-stream");
1064 1292 tao
1065 731 bojilova
        try {
1066 1292 tao
1067
          ServletOutputStream out = response.getOutputStream();
1068 731 bojilova
          byte[] buf = new byte[4 * 1024]; // 4K buffer
1069
          int b = fin.read(buf);
1070
          while (b != -1) {
1071
            out.write(buf, 0, b);
1072
            b = fin.read(buf);
1073 453 berkley
          }
1074 731 bojilova
        } finally {
1075
          if (fin != null) fin.close();
1076 453 berkley
        }
1077 731 bojilova
1078
      } else {
1079
        // this is metadata doc
1080 832 jones
        if ( qformat.equals("xml") ) {
1081 1217 tao
1082 832 jones
          // set content type first
1083
          response.setContentType("text/xml");   //MIME type
1084
          PrintWriter out = response.getWriter();
1085
          doc.toXml(out);
1086
        } else {
1087 731 bojilova
          response.setContentType("text/html");  //MIME type
1088
          PrintWriter out = response.getWriter();
1089
1090
          // Look up the document type
1091
          String doctype = doc.getDoctype();
1092
          // Transform the document to the new doctype
1093 1217 tao
          DBTransform dbt = new DBTransform();
1094 731 bojilova
          dbt.transformXMLDocument(doc.toString(),
1095 832 jones
                                   doctype,"-//W3C//HTML//EN", qformat, out);
1096 731 bojilova
        }
1097
1098 453 berkley
      }
1099 1292 tao
    }
1100
    catch (Exception except)
1101
    {
1102 1217 tao
      throw except;
1103
1104 731 bojilova
    }
1105
1106
  }
1107 453 berkley
1108 731 bojilova
  // read data from URLConnection
1109
  private void readFromURLConnection(HttpServletResponse response, String docid)
1110
               throws IOException, MalformedURLException
1111 566 jones
  {
1112 731 bojilova
    ServletOutputStream out = response.getOutputStream();
1113
    String contentType = getServletContext().getMimeType(docid); //MIME type
1114
    if (contentType == null) {
1115
      if (docid.endsWith(".xml")) {
1116
        contentType="text/xml";
1117
      } else if (docid.endsWith(".css")) {
1118
        contentType="text/css";
1119
      } else if (docid.endsWith(".dtd")) {
1120
        contentType="text/plain";
1121
      } else if (docid.endsWith(".xsd")) {
1122 733 bojilova
        contentType="text/xml";
1123 731 bojilova
      } else if (docid.endsWith("/")) {
1124 733 bojilova
        contentType="text/html";
1125 731 bojilova
      } else {
1126 733 bojilova
        File f = new File(docid);
1127
        if ( f.isDirectory() ) {
1128
          contentType="text/html";
1129
        } else {
1130
          contentType="application/octet-stream";
1131
        }
1132 731 bojilova
      }
1133
    }
1134
    response.setContentType(contentType);
1135 733 bojilova
    // if we decide to use "application/octet-stream" for all data returns
1136
    // response.setContentType("application/octet-stream");
1137 731 bojilova
1138
    // this is http url
1139
    URL url = new URL(docid);
1140
    BufferedInputStream bis = null;
1141 566 jones
    try {
1142 731 bojilova
      bis = new BufferedInputStream(url.openStream());
1143
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1144
      int b = bis.read(buf);
1145
      while (b != -1) {
1146
        out.write(buf, 0, b);
1147
        b = bis.read(buf);
1148 636 berkley
      }
1149 731 bojilova
    } finally {
1150
      if (bis != null) bis.close();
1151 566 jones
    }
1152 731 bojilova
1153 566 jones
  }
1154 636 berkley
1155 731 bojilova
  // read file/doc and write to ZipOutputStream
1156 947 tao
  private void addDocToZip(String docid, ZipOutputStream zout,
1157
                              String user, String[] groups)
1158 731 bojilova
               throws ClassNotFoundException, IOException, SQLException,
1159
                      McdbException, Exception
1160 636 berkley
  {
1161 731 bojilova
    byte[] bytestring = null;
1162
    ZipEntry zentry = null;
1163
1164
    try {
1165
      URL url = new URL(docid);
1166
1167
      // this http url; read from URLConnection; add to zip
1168
      zentry = new ZipEntry(docid);
1169
      zout.putNextEntry(zentry);
1170
      BufferedInputStream bis = null;
1171
      try {
1172
        bis = new BufferedInputStream(url.openStream());
1173
        byte[] buf = new byte[4 * 1024]; // 4K buffer
1174
        int b = bis.read(buf);
1175
        while(b != -1) {
1176
          zout.write(buf, 0, b);
1177
          b = bis.read(buf);
1178
        }
1179
      } finally {
1180
        if (bis != null) bis.close();
1181 636 berkley
      }
1182 731 bojilova
      zout.closeEntry();
1183
1184
    } catch (MalformedURLException mue) {
1185 661 berkley
1186 731 bojilova
      // this is metacat doc (data file or metadata doc)
1187 1217 tao
1188 731 bojilova
      try {
1189 1217 tao
1190
        DocumentImpl doc = new DocumentImpl(docid);
1191 947 tao
1192
        //check the permission for read
1193 1217 tao
        if (!doc.hasReadPermission(user, groups, docid))
1194 947 tao
        {
1195
          Exception e = new Exception("User " + user + " does not have "
1196
                    +"permission to read the document with the docid " + docid);
1197 1217 tao
1198 947 tao
          throw e;
1199
        }
1200
1201 731 bojilova
        if ( doc.getRootNodeID() == 0 ) {
1202
          // this is data file; add file to zip
1203
          String filepath = util.getOption("datafilepath");
1204
          if(!filepath.endsWith("/")) {
1205
            filepath += "/";
1206
          }
1207 1292 tao
          String filename = filepath + docid;
1208 731 bojilova
          FileInputStream fin = null;
1209 1292 tao
          fin = new FileInputStream(filename);
1210 731 bojilova
          try {
1211 1292 tao
1212
            zentry = new ZipEntry(docid);
1213
            zout.putNextEntry(zentry);
1214 731 bojilova
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1215
            int b = fin.read(buf);
1216
            while (b != -1) {
1217
              zout.write(buf, 0, b);
1218
              b = fin.read(buf);
1219
            }
1220
          } finally {
1221
            if (fin != null) fin.close();
1222
          }
1223
          zout.closeEntry();
1224
1225
        } else {
1226
          // this is metadata doc; add doc to zip
1227
          bytestring = doc.toString().getBytes();
1228
          zentry = new ZipEntry(docid + ".xml");
1229
          zentry.setSize(bytestring.length);
1230
          zout.putNextEntry(zentry);
1231
          zout.write(bytestring, 0, bytestring.length);
1232
          zout.closeEntry();
1233 636 berkley
        }
1234 1217 tao
      } catch (Exception except) {
1235
        throw except;
1236
1237 636 berkley
      }
1238
1239
    }
1240 731 bojilova
1241 636 berkley
  }
1242 731 bojilova
1243
  // view abstract within document
1244
  private void viewAbstract(HttpServletResponse response,
1245
                            String abstractpath, String docid)
1246
               throws ClassNotFoundException, IOException, SQLException,
1247
                      McdbException, Exception
1248
  {
1249 1217 tao
1250
    PrintWriter out =null;
1251 102 jones
    try {
1252 1217 tao
1253 731 bojilova
      response.setContentType("text/html");  //MIME type
1254 1217 tao
      out = response.getWriter();
1255
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid);
1256 731 bojilova
      out.println("<html><head><title>Abstract</title></head>");
1257
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
1258
      for (int i=0; i<abstracts.length; i++) {
1259
        out.println("<p>" + (String)abstracts[i] + "</p>");
1260
      }
1261
      out.println("</body></html>");
1262 85 jones
1263 1217 tao
    } catch (Exception e) {
1264
       out.println("<?xml version=\"1.0\"?>");
1265
       out.println("<error>");
1266
       out.println(e.getMessage());
1267
       out.println("</error>");
1268
1269
1270 731 bojilova
    }
1271 49 jones
  }
1272 1292 tao
  /**
1273
   * If metacat couldn't find a data file or document locally, it will read this
1274
   * docid from its home server. This is for the replication feature
1275
   */
1276
  private void readFromRemoteMetaCat(HttpServletResponse response, String docid,
1277
                     String rev, String user, String password,
1278
                     ServletOutputStream out, boolean zip, ZipOutputStream zout)
1279
                        throws Exception
1280
 {
1281
   // Create a object of RemoteDocument, "" is for zipEntryPath
1282
   RemoteDocument remoteDoc =
1283
                        new RemoteDocument (docid, rev,user, password, "");
1284
   // If it is zip format
1285
   if (zip)
1286
   {
1287
     remoteDoc.readDocumentFromRemoteServerByZip(zout);
1288
   }//if
1289
   else
1290
   {
1291
     if (out == null)
1292
     {
1293
       out = response.getOutputStream();
1294
     }//if
1295
     response.setContentType("application/octet-stream");
1296
     remoteDoc.readDocumentFromRemoteServer(out);
1297
   }//else (not zip)
1298
 }//readFromRemoteMetaCat
1299
1300 731 bojilova
  // END OF READ SECTION
1301
1302
  // INSERT/UPDATE SECTION
1303 55 jones
  /**
1304
   * Handle the database putdocument request and write an XML document
1305
   * to the database connection
1306
   */
1307 382 berkley
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1308 802 bojilova
               HttpServletResponse response, String user, String[] groups) {
1309 59 jones
1310 1217 tao
    DBConnection dbConn = null;
1311
    int serialNumber = -1;
1312 309 bojilova
1313 204 jones
    try {
1314
      // Get the document indicated
1315
      String[] doctext = (String[])params.get("doctext");
1316 557 bojilova
1317 680 bojilova
      String pub = null;
1318
      if (params.containsKey("public")) {
1319
        pub = ((String[])params.get("public"))[0];
1320 557 bojilova
      }
1321 680 bojilova
1322 598 bojilova
      StringReader dtd = null;
1323 680 bojilova
      if (params.containsKey("dtdtext")) {
1324 598 bojilova
        String[] dtdtext = (String[])params.get("dtdtext");
1325
        try {
1326 619 bojilova
          if ( !dtdtext[0].equals("") ) {
1327
            dtd = new StringReader(dtdtext[0]);
1328
          }
1329 598 bojilova
        } catch (NullPointerException npe) {}
1330
      }
1331 557 bojilova
1332 204 jones
      StringReader xml = null;
1333 695 bojilova
      boolean validate = false;
1334 204 jones
      try {
1335 695 bojilova
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1336
        // in order to decide whether to use validation parser
1337
        validate = validateXML(doctext[0]);
1338 204 jones
        xml = new StringReader(doctext[0]);
1339 59 jones
1340 204 jones
        String[] action = (String[])params.get("action");
1341
        String[] docid = (String[])params.get("docid");
1342
        String newdocid = null;
1343 203 jones
1344 204 jones
        String doAction = null;
1345
        if (action[0].equals("insert")) {
1346
          doAction = "INSERT";
1347
        } else if (action[0].equals("update")) {
1348
          doAction = "UPDATE";
1349
        }
1350 1217 tao
1351
        try
1352
        {
1353 680 bojilova
          // get a connection from the pool
1354 1217 tao
          dbConn=DBConnectionPool.
1355
                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1356
          serialNumber=dbConn.getCheckOutSerialNumber();
1357
1358 1292 tao
1359 680 bojilova
          // write the document to the database
1360 1217 tao
          try
1361
          {
1362 680 bojilova
            String accNumber = docid[0];
1363 1292 tao
            MetaCatUtil.debugMessage(""+ doAction + " " + accNumber +"...", 10);
1364 1217 tao
            if (accNumber.equals(""))
1365
            {
1366 680 bojilova
              accNumber = null;
1367 1217 tao
            }//if
1368
            newdocid = DocumentImpl.write(dbConn, xml, pub, dtd, doAction,
1369 802 bojilova
                                          accNumber, user, groups, validate);
1370 1217 tao
1371
          }//try
1372
          catch (NullPointerException npe)
1373
          {
1374
            newdocid = DocumentImpl.write(dbConn, xml, pub, dtd, doAction,
1375 802 bojilova
                                          null, user, groups, validate);
1376 1217 tao
          }//catch
1377
        }//try
1378
        finally
1379
        {
1380
          // Return db connection
1381
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1382 309 bojilova
        }
1383
1384 204 jones
        // set content type and other response header fields first
1385
        response.setContentType("text/xml");
1386
        out.println("<?xml version=\"1.0\"?>");
1387
        out.println("<success>");
1388
        out.println("<docid>" + newdocid + "</docid>");
1389
        out.println("</success>");
1390
1391 203 jones
      } catch (NullPointerException npe) {
1392 204 jones
        response.setContentType("text/xml");
1393
        out.println("<?xml version=\"1.0\"?>");
1394
        out.println("<error>");
1395
        out.println(npe.getMessage());
1396
        out.println("</error>");
1397 55 jones
      }
1398 204 jones
    } catch (Exception e) {
1399
      response.setContentType("text/xml");
1400
      out.println("<?xml version=\"1.0\"?>");
1401
      out.println("<error>");
1402
      out.println(e.getMessage());
1403
      if (e instanceof SAXException) {
1404
        Exception e2 = ((SAXException)e).getException();
1405
        out.println("<error>");
1406 780 berkley
        try
1407
        {
1408
          out.println(e2.getMessage());
1409
        }
1410
        catch(NullPointerException npe)
1411
        {
1412
          out.println(e.getMessage());
1413
        }
1414 204 jones
        out.println("</error>");
1415
      }
1416
      //e.printStackTrace(out);
1417
      out.println("</error>");
1418 203 jones
    }
1419 55 jones
  }
1420 203 jones
1421
  /**
1422 695 bojilova
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1423
   * in order to decide whether to use validation parser
1424
   */
1425
  private static boolean validateXML(String xmltext) throws IOException {
1426
1427
    StringReader xmlreader = new StringReader(xmltext);
1428
    StringBuffer cbuff = new StringBuffer();
1429
    java.util.Stack st = new java.util.Stack();
1430
    boolean validate = false;
1431
    int c;
1432
    int inx;
1433
1434
    // read from the stream until find the keywords
1435
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1436
      cbuff.append((char)c);
1437
1438
      // "<!DOCTYPE" keyword is found; put it in the stack
1439
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1440
        cbuff = new StringBuffer();
1441
        st.push("<!DOCTYPE");
1442
      }
1443
      // "PUBLIC" keyword is found; put it in the stack
1444
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1445
        cbuff = new StringBuffer();
1446
        st.push("PUBLIC");
1447
      }
1448
      // "SYSTEM" keyword is found; put it in the stack
1449
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1450
        cbuff = new StringBuffer();
1451
        st.push("SYSTEM");
1452
      }
1453
      // ">" character is found; put it in the stack
1454
      // ">" is found twice: fisrt from <?xml ...?>
1455
      // and second from <!DOCTYPE ... >
1456
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1457
        cbuff = new StringBuffer();
1458
        st.push(">");
1459
      }
1460
    }
1461
1462
    // close the stream
1463
    xmlreader.close();
1464
1465
    // check the stack whether it contains the keywords:
1466
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1467
    if ( st.size() == 4 ) {
1468
      if ( ((String)st.pop()).equals(">") &&
1469
           ( ((String)st.peek()).equals("PUBLIC") |
1470
             ((String)st.pop()).equals("SYSTEM") ) &&
1471
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1472
        validate = true;
1473
      }
1474
    }
1475
1476
System.out.println("Validation is " + validate);
1477
    return validate;
1478
  }
1479 731 bojilova
  // END OF INSERT/UPDATE SECTION
1480 695 bojilova
1481 731 bojilova
  // DELETE SECTION
1482 695 bojilova
  /**
1483 203 jones
   * Handle the database delete request and delete an XML document
1484
   * from the database connection
1485
   */
1486
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1487 802 bojilova
               HttpServletResponse response, String user, String[] groups) {
1488 203 jones
1489
    String[] docid = (String[])params.get("docid");
1490 1217 tao
1491 203 jones
    // delete the document from the database
1492
    try {
1493 1217 tao
1494 203 jones
                                      // NOTE -- NEED TO TEST HERE
1495 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
1496 203 jones
                                      // BEFORE ACCESSING ARRAY
1497 375 berkley
      try {
1498 1217 tao
        DocumentImpl.delete(docid[0], user, groups);
1499 204 jones
        response.setContentType("text/xml");
1500
        out.println("<?xml version=\"1.0\"?>");
1501
        out.println("<success>");
1502 203 jones
        out.println("Document deleted.");
1503 204 jones
        out.println("</success>");
1504 203 jones
      } catch (AccessionNumberException ane) {
1505 204 jones
        response.setContentType("text/xml");
1506
        out.println("<?xml version=\"1.0\"?>");
1507
        out.println("<error>");
1508
        out.println("Error deleting document!!!");
1509 203 jones
        out.println(ane.getMessage());
1510 204 jones
        out.println("</error>");
1511 203 jones
      }
1512 204 jones
    } catch (Exception e) {
1513
      response.setContentType("text/xml");
1514
      out.println("<?xml version=\"1.0\"?>");
1515
      out.println("<error>");
1516
      out.println(e.getMessage());
1517
      out.println("</error>");
1518 1217 tao
    }
1519 203 jones
  }
1520 731 bojilova
  // END OF DELETE SECTION
1521 68 higgins
1522 731 bojilova
  // VALIDATE SECTION
1523 68 higgins
  /**
1524 380 jones
   * Handle the validation request and return the results to the requestor
1525 68 higgins
   */
1526 185 jones
  private void handleValidateAction(PrintWriter out, Hashtable params,
1527
               HttpServletResponse response) {
1528 68 higgins
1529 103 jones
    // Get the document indicated
1530
    String valtext = null;
1531 1217 tao
    DBConnection dbConn = null;
1532
    int serialNumber = -1;
1533 309 bojilova
1534 103 jones
    try {
1535
      valtext = ((String[])params.get("valtext"))[0];
1536
    } catch (Exception nullpe) {
1537 68 higgins
1538 1217 tao
1539 162 bojilova
      String docid = null;
1540 103 jones
      try {
1541
        // Find the document id number
1542 185 jones
        docid = ((String[])params.get("docid"))[0];
1543 309 bojilova
1544 1217 tao
1545 309 bojilova
        // Get the document indicated from the db
1546 1217 tao
        DocumentImpl xmldoc = new DocumentImpl(docid);
1547 393 jones
        valtext = xmldoc.toString();
1548 185 jones
1549 103 jones
      } catch (NullPointerException npe) {
1550 253 jones
        response.setContentType("text/xml");
1551
        out.println("<error>Error getting document ID: " + docid + "</error>");
1552 1217 tao
        //if ( conn != null ) { util.returnConnection(conn); }
1553 380 jones
        return;
1554 309 bojilova
      } catch (Exception e) {
1555
        response.setContentType("text/html");
1556
        out.println(e.getMessage());
1557 1217 tao
      }
1558 103 jones
    }
1559 68 higgins
1560 1217 tao
1561 103 jones
    try {
1562 309 bojilova
      // get a connection from the pool
1563 1217 tao
      dbConn=DBConnectionPool.
1564
                  getDBConnection("MetaCatServlet.handleValidateAction");
1565
      serialNumber=dbConn.getCheckOutSerialNumber();
1566
      DBValidate valobj = new DBValidate(saxparser,dbConn);
1567 185 jones
      boolean valid = valobj.validateString(valtext);
1568 68 higgins
1569
      // set content type and other response header fields first
1570 253 jones
      response.setContentType("text/xml");
1571
      out.println(valobj.returnErrors());
1572
1573 103 jones
    } catch (NullPointerException npe2) {
1574
      // set content type and other response header fields first
1575 253 jones
      response.setContentType("text/xml");
1576
      out.println("<error>Error validating document.</error>");
1577 309 bojilova
    } catch (Exception e) {
1578
      response.setContentType("text/html");
1579
      out.println(e.getMessage());
1580
    } finally {
1581 1217 tao
      // Return db connection
1582
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1583 309 bojilova
    }
1584 103 jones
  }
1585 731 bojilova
  // END OF VALIDATE SECTION
1586
1587
  // OTHER ACTION HANDLERS
1588 302 bojilova
1589 1292 tao
  /**
1590
   * Handle "getrevsionanddoctype" action
1591
   * Given a docid, return it's current revision and doctype from data base
1592
   * The output is String look like "rev;doctype"
1593
   */
1594
  private void handleGetRevisionAndDocTypeAction(PrintWriter out,
1595
                                                              Hashtable params)
1596
  {
1597
    // To store doc parameter
1598
    String [] docs = new String[10];
1599
    // Store a single doc id
1600
    String givenDocId = null;
1601
    // Get docid from parameters
1602
    if (params.containsKey("docid"))
1603
    {
1604
      docs = (String[])params.get("docid");
1605
    }
1606
    // Get first docid form string array
1607
    givenDocId = docs[0];
1608
1609
    try
1610
    {
1611
      // Make sure there is a docid
1612
      if (givenDocId == null || givenDocId.equals(""))
1613
      {
1614
        throw new Exception("User didn't specify docid!");
1615
      }//if
1616
1617
      // Create a DBUtil object
1618
      DBUtil dbutil = new DBUtil();
1619
      // Get a rev and doctype
1620
      String revAndDocType =
1621
                dbutil.getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1622
      out.println(revAndDocType);
1623
1624
    }//try
1625
    catch (Exception e)
1626
    {
1627
      // Handle exception
1628
      out.println("<?xml version=\"1.0\"?>");
1629
      out.println("<error>");
1630
      out.println(e.getMessage());
1631
      out.println("</error>");
1632
    }//catch
1633
1634
  }//handleGetRevisionAndDocTypeAction
1635
1636 302 bojilova
  /**
1637 688 bojilova
   * Handle "getaccesscontrol" action.
1638
   * Read Access Control List from db connection in XML format
1639
   */
1640
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
1641
                                       HttpServletResponse response,
1642 802 bojilova
                                       String username, String[] groupnames) {
1643 688 bojilova
1644 1217 tao
    DBConnection dbConn = null;
1645
    int serialNumber = -1;
1646 688 bojilova
    String docid = ((String[])params.get("docid"))[0];
1647
1648
    try {
1649
1650
        // get connection from the pool
1651 1217 tao
        dbConn=DBConnectionPool.
1652
                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
1653
        serialNumber=dbConn.getCheckOutSerialNumber();
1654
        AccessControlList aclobj = new AccessControlList(dbConn);
1655 802 bojilova
        String acltext = aclobj.getACL(docid, username, groupnames);
1656 688 bojilova
        out.println(acltext);
1657
1658
    } catch (Exception e) {
1659
      out.println("<?xml version=\"1.0\"?>");
1660
      out.println("<error>");
1661
      out.println(e.getMessage());
1662
      out.println("</error>");
1663
    } finally {
1664 1217 tao
      // Retrun db connection to pool
1665
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1666 688 bojilova
    }
1667
1668
  }
1669
1670
  /**
1671 731 bojilova
   * Handle the "getprincipals" action.
1672
   * Read all principals from authentication scheme in XML format
1673
   */
1674
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1675
                                         String password) {
1676
1677 1217 tao
1678 731 bojilova
    try {
1679
1680 1217 tao
1681 731 bojilova
        AuthSession auth = new AuthSession();
1682
        String principals = auth.getPrincipals(user, password);
1683
        out.println(principals);
1684
1685
    } catch (Exception e) {
1686
      out.println("<?xml version=\"1.0\"?>");
1687
      out.println("<error>");
1688
      out.println(e.getMessage());
1689
      out.println("</error>");
1690 1217 tao
    }
1691 731 bojilova
1692
  }
1693
1694
  /**
1695 688 bojilova
   * Handle "getdoctypes" action.
1696 302 bojilova
   * Read all doctypes from db connection in XML format
1697
   */
1698
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1699
                                       HttpServletResponse response) {
1700
1701 1217 tao
1702 302 bojilova
    try {
1703
1704 1217 tao
1705
        DBUtil dbutil = new DBUtil();
1706 302 bojilova
        String doctypes = dbutil.readDoctypes();
1707
        out.println(doctypes);
1708
1709
    } catch (Exception e) {
1710
      out.println("<?xml version=\"1.0\"?>");
1711
      out.println("<error>");
1712
      out.println(e.getMessage());
1713
      out.println("</error>");
1714 1217 tao
    }
1715 302 bojilova
1716
  }
1717
1718
  /**
1719 699 bojilova
   * Handle the "getdtdschema" action.
1720
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1721
   */
1722
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1723
                                        HttpServletResponse response) {
1724
1725 1217 tao
1726 699 bojilova
    String doctype = null;
1727
    String[] doctypeArr = (String[])params.get("doctype");
1728
1729
    // get only the first doctype specified in the list of doctypes
1730
    // it could be done for all doctypes in that list
1731
    if (doctypeArr != null) {
1732
        doctype = ((String[])params.get("doctype"))[0];
1733
    }
1734
1735
    try {
1736
1737 1217 tao
1738
        DBUtil dbutil = new DBUtil();
1739 699 bojilova
        String dtdschema = dbutil.readDTDSchema(doctype);
1740
        out.println(dtdschema);
1741
1742
    } catch (Exception e) {
1743
      out.println("<?xml version=\"1.0\"?>");
1744
      out.println("<error>");
1745
      out.println(e.getMessage());
1746
      out.println("</error>");
1747 1217 tao
    }
1748 699 bojilova
1749
  }
1750
1751
  /**
1752 688 bojilova
   * Handle the "getdataguide" action.
1753 302 bojilova
   * Read Data Guide for a given doctype from db connection in XML format
1754
   */
1755
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
1756
                                        HttpServletResponse response) {
1757
1758 1217 tao
1759 316 bojilova
    String doctype = null;
1760
    String[] doctypeArr = (String[])params.get("doctype");
1761 309 bojilova
1762 316 bojilova
    // get only the first doctype specified in the list of doctypes
1763
    // it could be done for all doctypes in that list
1764
    if (doctypeArr != null) {
1765
        doctype = ((String[])params.get("doctype"))[0];
1766
    }
1767
1768 302 bojilova
    try {
1769
1770 1217 tao
1771
        DBUtil dbutil = new DBUtil();
1772 316 bojilova
        String dataguide = dbutil.readDataGuide(doctype);
1773 302 bojilova
        out.println(dataguide);
1774
1775
    } catch (Exception e) {
1776
      out.println("<?xml version=\"1.0\"?>");
1777
      out.println("<error>");
1778
      out.println(e.getMessage());
1779
      out.println("</error>");
1780 1217 tao
    }
1781 302 bojilova
1782
  }
1783
1784 793 bojilova
  /**
1785
   * Handle the "getlastdocid" action.
1786
   * Get the latest docid with rev number from db connection in XML format
1787
   */
1788 847 jones
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
1789 793 bojilova
                                        HttpServletResponse response) {
1790
1791 1217 tao
1792 847 jones
    String scope = ((String[])params.get("scope"))[0];
1793
    if (scope == null) {
1794
        scope = ((String[])params.get("username"))[0];
1795
    }
1796 793 bojilova
1797
    try {
1798
1799 1217 tao
1800
        DBUtil dbutil = new DBUtil();
1801 847 jones
        String lastDocid = dbutil.getMaxDocid(scope);
1802 793 bojilova
        out.println("<?xml version=\"1.0\"?>");
1803
        out.println("<lastDocid>");
1804 847 jones
        out.println("  <scope>" + scope + "</scope>");
1805 793 bojilova
        out.println("  <docid>" + lastDocid + "</docid>");
1806
        out.println("</lastDocid>");
1807
1808
    } catch (Exception e) {
1809
      out.println("<?xml version=\"1.0\"?>");
1810
      out.println("<error>");
1811
      out.println(e.getMessage());
1812
      out.println("</error>");
1813 1217 tao
    }
1814 793 bojilova
1815
  }
1816
1817 798 jones
  /**
1818
   * Handle documents passed to metacat that are encoded using the
1819
   * "multipart/form-data" mime type.  This is typically used for uploading
1820
   * data files which may be binary and large.
1821
   */
1822
  private void handleMultipartForm(HttpServletRequest request,
1823
                                   HttpServletResponse response)
1824
  {
1825
    PrintWriter out = null;
1826
    String action = null;
1827
1828
    // Parse the multipart form, and save the parameters in a Hashtable and
1829
    // save the FileParts in a hashtable
1830
1831
    Hashtable params = new Hashtable();
1832
    Hashtable fileList = new Hashtable();
1833
1834
    try {
1835
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
1836 943 tao
      MultipartParser mp = new MultipartParser(request, 200*1024*1024); //200MB
1837 798 jones
      Part part;
1838
      while ((part = mp.readNextPart()) != null) {
1839
        String name = part.getName();
1840
1841
        if (part.isParam()) {
1842
          // it's a parameter part
1843
          ParamPart paramPart = (ParamPart) part;
1844
          String value = paramPart.getStringValue();
1845
          params.put(name, value);
1846
          if (name.equals("action")) {
1847
            action = value;
1848
          }
1849
        } else if (part.isFile()) {
1850
          // it's a file part
1851
          FilePart filePart = (FilePart) part;
1852
          fileList.put(name, filePart);
1853
1854
          // Stop once the first file part is found, otherwise going onto the
1855
          // next part prevents access to the file contents.  So...for upload
1856
          // to work, the datafile must be the last part
1857
          break;
1858
        }
1859
      }
1860
    } catch (IOException ioe) {
1861
      try {
1862
        out = response.getWriter();
1863
      } catch (IOException ioe2) {
1864
        System.err.println("Fatal Error: couldn't get response output stream.");
1865
      }
1866
      out.println("<?xml version=\"1.0\"?>");
1867
      out.println("<error>");
1868
      out.println("Error: problem reading multipart data.");
1869
      out.println("</error>");
1870
    }
1871
1872
    // Get the session information
1873
    String username = null;
1874
    String password = null;
1875 802 bojilova
    String[] groupnames = null;
1876 798 jones
    String sess_id = null;
1877
1878
    // be aware of session expiration on every request
1879
    HttpSession sess = request.getSession(true);
1880
    if (sess.isNew()) {
1881
      // session expired or has not been stored b/w user requests
1882
      username = "public";
1883
      sess.setAttribute("username", username);
1884
    } else {
1885
      username = (String)sess.getAttribute("username");
1886
      password = (String)sess.getAttribute("password");
1887 802 bojilova
      groupnames = (String[])sess.getAttribute("groupnames");
1888 798 jones
      try {
1889
        sess_id = (String)sess.getId();
1890
      } catch(IllegalStateException ise) {
1891
        System.out.println("error in  handleMultipartForm: this shouldn't " +
1892
                           "happen: the session should be valid: " +
1893
                           ise.getMessage());
1894
      }
1895
    }
1896 1292 tao
1897
    // Get the out stream
1898
    try {
1899 798 jones
          out = response.getWriter();
1900
        } catch (IOException ioe2) {
1901 943 tao
          util.debugMessage("Fatal Error: couldn't get response "+
1902
                                                              "output stream.");
1903 798 jones
        }
1904 1292 tao
1905
    if ( action.equals("upload")) {
1906
      if (username != null &&  !username.equals("public")) {
1907
        handleUploadAction(request, out, params, fileList,
1908
                           username, groupnames);
1909
      } else {
1910
1911 798 jones
        out.println("<?xml version=\"1.0\"?>");
1912
        out.println("<error>");
1913
        out.println("Permission denied for " + action);
1914
        out.println("</error>");
1915
      }
1916
    } else {
1917 1292 tao
      /*try {
1918 798 jones
        out = response.getWriter();
1919
      } catch (IOException ioe2) {
1920
        System.err.println("Fatal Error: couldn't get response output stream.");
1921 1292 tao
      }*/
1922 798 jones
      out.println("<?xml version=\"1.0\"?>");
1923
      out.println("<error>");
1924
      out.println("Error: action not registered.  Please report this error.");
1925
      out.println("</error>");
1926
    }
1927 1217 tao
    out.close();
1928 798 jones
  }
1929
1930
  /**
1931
   * Handle the upload action by saving the attached file to disk and
1932
   * registering it in the Metacat db
1933
   */
1934
  private void handleUploadAction(HttpServletRequest request,
1935 1292 tao
                                  PrintWriter out,
1936 798 jones
                                  Hashtable params, Hashtable fileList,
1937 802 bojilova
                                  String username, String[] groupnames)
1938 798 jones
  {
1939 1292 tao
    //PrintWriter out = null;
1940 1217 tao
    //Connection conn = null;
1941 798 jones
    String action = null;
1942
    String docid = null;
1943 1041 tao
1944 1292 tao
    /*response.setContentType("text/xml");
1945 1041 tao
    try
1946
    {
1947 798 jones
      out = response.getWriter();
1948 1041 tao
    }
1949
    catch (IOException ioe2)
1950
    {
1951 798 jones
      System.err.println("Fatal Error: couldn't get response output stream.");
1952 1292 tao
    }*/
1953 798 jones
1954 1041 tao
    if (params.containsKey("docid"))
1955
    {
1956 798 jones
      docid = (String)params.get("docid");
1957
    }
1958
1959
    // Make sure we have a docid and datafile
1960
    if (docid != null && fileList.containsKey("datafile")) {
1961
1962
      // Get a reference to the file part of the form
1963
      FilePart filePart = (FilePart)fileList.get("datafile");
1964
      String fileName = filePart.getFileName();
1965 1056 tao
      MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
1966 798 jones
1967
      // Check if the right file existed in the uploaded data
1968
      if (fileName != null) {
1969
1970 1028 tao
        try
1971
        {
1972 1292 tao
           //MetaCatUtil.debugMessage("Upload datafile " + docid +"...", 10);
1973 1028 tao
           //If document get lock data file grant
1974 1070 tao
           if (DocumentImpl.getDataFileLockGrant(docid))
1975
           {
1976 1064 tao
              // register the file in the database (which generates an exception
1977 1028 tao
              //if the docid is not acceptable or other untoward things happen
1978
              DocumentImpl.registerDocument(fileName, "BIN", docid, username);
1979 798 jones
1980 1028 tao
              // Save the data file to disk using "docid" as the name
1981
              dataDirectory.mkdirs();
1982
              File newFile = new File(dataDirectory, docid);
1983
              long size = filePart.writeTo(newFile);
1984 1292 tao
1985
              // Force replication this data file
1986
              // To data file, "insert" and update is same
1987
              // The fourth parameter is null. Because it is notification server
1988
              // and this method is in MetaCatServerlet. It is original command,
1989
              // not get force replication info from another metacat
1990
              ForceReplicationHandler frh = new ForceReplicationHandler
1991
                                                (docid, "insert", false, null);
1992
1993 1028 tao
              // set content type and other response header fields first
1994
              out.println("<?xml version=\"1.0\"?>");
1995
              out.println("<success>");
1996
              out.println("<docid>" + docid + "</docid>");
1997
              out.println("<size>" + size + "</size>");
1998
              out.println("</success>");
1999 1070 tao
          }//if
2000 798 jones
2001 1028 tao
        } //try
2002 1041 tao
        catch (Exception e)
2003
        {
2004 798 jones
          out.println("<?xml version=\"1.0\"?>");
2005
          out.println("<error>");
2006
          out.println(e.getMessage());
2007
          out.println("</error>");
2008
        }
2009 1217 tao
2010 1041 tao
      }
2011
      else
2012
      {
2013 798 jones
        // the field did not contain a file
2014
        out.println("<?xml version=\"1.0\"?>");
2015
        out.println("<error>");
2016
        out.println("The uploaded data did not contain a valid file.");
2017
        out.println("</error>");
2018
      }
2019 1041 tao
    }
2020
    else
2021
    {
2022 798 jones
      // Error bcse docid missing or file missing
2023
      out.println("<?xml version=\"1.0\"?>");
2024
      out.println("<error>");
2025
      out.println("The uploaded data did not contain a valid docid " +
2026
                  "or valid file.");
2027
      out.println("</error>");
2028
    }
2029
  }
2030 46 jones
}