Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: tao $'
10
 *     '$Date: 2002-02-22 15:02:50 -0800 (Fri, 22 Feb 2002) $'
11
 * '$Revision: 943 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import 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
import java.io.File;
36
import java.io.PrintWriter;
37
import java.io.IOException;
38
import java.io.StringReader;
39
import java.io.FileInputStream;
40
import java.io.BufferedInputStream;
41
import java.util.Enumeration;
42
import java.util.Hashtable;
43
import java.util.ResourceBundle; 
44
import java.util.Random;
45
import java.util.PropertyResourceBundle;
46
import java.net.URL;
47
import java.net.MalformedURLException;
48
import java.sql.PreparedStatement;
49
import java.sql.ResultSet;
50
import java.sql.Connection;
51
import java.sql.SQLException;
52
import java.lang.reflect.*;
53
import java.net.*;
54
import java.util.zip.*;
55

    
56
import javax.servlet.ServletConfig;
57
import javax.servlet.ServletContext;
58
import javax.servlet.ServletException;
59
import javax.servlet.ServletInputStream;
60
import javax.servlet.http.HttpServlet;
61
import javax.servlet.http.HttpServletRequest;
62
import javax.servlet.http.HttpServletResponse;
63
import javax.servlet.http.HttpSession;
64
import javax.servlet.http.HttpUtils;
65
import javax.servlet.ServletOutputStream;
66

    
67
import org.xml.sax.SAXException;
68

    
69
/**
70
 * A metadata catalog server implemented as a Java Servlet
71
 *
72
 * <p>Valid parameters are:<br>
73
 * action=query -- query the values of all elements and attributes
74
 *                     and return a result set of nodes<br>
75
 * action=squery -- structured query (see pathquery.dtd)<br> 
76
 * action= -- export a zip format for data packadge<br>
77
 * action=read -- read any metadata/data file from Metacat and from Internet<br>
78
 * 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
 * qformat=xml -- display resultset from query in XML<br>
84
 * qformat=html -- display resultset from query in HTML<br>
85
 * qformat=zip -- zip resultset from query<br>
86
 * docid=34 -- display the document with the document ID number 34<br>
87
 * doctext -- XML text of the document to load into the database<br>
88
 * 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
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
91
 * valtext -- XML text to be validated<br>
92
 * abstractpath -- XPath in metadata document to read from<br>
93
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
94
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
95
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
96
 * action=getdataguide -- retrieve a Data Guide<br>
97
 * action=getprincipals -- retrieve a list of principals in XML<br>
98
 * 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
 */
104
public class MetaCatServlet extends HttpServlet {
105

    
106
  private ServletConfig config = null;
107
  private ServletContext context = null;
108
  private Hashtable connectionPool = new Hashtable();
109
  private String resultStyleURL = null;
110
  private String xmlcatalogfile = null;
111
  private String saxparser = null;
112
  private String datafilepath = null; 
113
  private File dataDirectory = null;
114
  private String servletpath = null; 
115
  private String htmlpath = null; 
116
  private PropertyResourceBundle options = null;
117
  private MetaCatUtil util = null;
118

    
119
  /**
120
   * Initialize the servlet by creating appropriate database connections
121
   */
122
  public void init( ServletConfig config ) throws ServletException {
123
    try {
124
      super.init( config );
125
      this.config = config;
126
      this.context = config.getServletContext(); 
127
      System.out.println("MetaCatServlet Initialize");
128

    
129
      util = new MetaCatUtil();
130

    
131
      // Get the configuration file information
132
      resultStyleURL = util.getOption("resultStyleURL");
133
      xmlcatalogfile = util.getOption("xmlcatalogfile");
134
      saxparser = util.getOption("saxparser");
135
      datafilepath = util.getOption("datafilepath");
136
      dataDirectory = new File(datafilepath);
137
      servletpath = util.getOption("servletpath");
138
      htmlpath = util.getOption("htmlpath");
139

    
140
// MOVED IT TO doGet() & doPost()
141
//      try {
142
//        // Open a pool of db connections
143
//        connectionPool = util.getConnectionPool();
144
//      } catch (Exception e) {
145
//        System.err.println("Error creating pool of database connections");
146
//        System.err.println(e.getMessage());
147
//      }
148
    } catch ( ServletException ex ) {
149
      throw ex;
150
    }
151
  }
152

    
153
  /**
154
   * Close all db connections from the pool
155
   */
156
  public void destroy() {
157
    
158
    if (util != null) {
159
        util.closeConnections();
160
    }
161
  }
162

    
163
  /** Handle "GET" method requests from HTTP clients */
164
  public void doGet (HttpServletRequest request, HttpServletResponse response)
165
    throws ServletException, IOException {
166

    
167
    // Process the data and send back the response
168
    handleGetOrPost(request, response);
169
  }
170

    
171
  /** Handle "POST" method requests from HTTP clients */
172
  public void doPost( HttpServletRequest request, HttpServletResponse response)
173
    throws ServletException, IOException {
174

    
175
    // Process the data and send back the response
176
    handleGetOrPost(request, response);
177
  }
178

    
179
  /**
180
   * Control servlet response depending on the action parameter specified
181
   */
182
  private void handleGetOrPost(HttpServletRequest request, 
183
                               HttpServletResponse response) 
184
                               throws ServletException, IOException 
185
  {
186

    
187
    if ( util == null ) {
188
        util = new MetaCatUtil(); 
189
    }
190
    if ( connectionPool.isEmpty() ) {
191
      try {
192
        // Open a pool of db connections
193
        connectionPool = util.getConnectionPool();
194
      } catch (Exception e) {
195
        System.err.println("Error creating pool of database connections in " +
196
                            " MetaCatServlet.handleGetOrPost");
197
        System.err.println(e.getMessage());
198
      }
199
    }    
200
    // Get a handle to the output stream back to the client
201
    //PrintWriter pwout = response.getWriter();
202
    //response.setContentType("text/html");
203

    
204
    // Deal with forms that are encoded as "multipart/form-data" differently
205
    // this is mainly used for uploading non-xml files using that may be binary
206
    String ctype = request.getContentType();
207
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
208
      handleMultipartForm(request, response);
209
    } else {
210
    
211
  
212
      String name = null;
213
      String[] value = null;
214
      String[] docid = new String[3];
215
      Hashtable params = new Hashtable();
216
      Enumeration paramlist = request.getParameterNames();
217
      while (paramlist.hasMoreElements()) {
218
        name = (String)paramlist.nextElement();
219
        value = request.getParameterValues(name);
220
  
221
        // Decode the docid and mouse click information
222
        if (name.endsWith(".y")) {
223
          docid[0] = name.substring(0,name.length()-2);
224
          params.put("docid", docid);
225
          name = "ypos";
226
        }
227
        if (name.endsWith(".x")) {
228
          name = "xpos";
229
        } 
230
  
231
        params.put(name,value); 
232
      }  
233
      
234
      //if the user clicked on the input images, decode which image
235
      //was clicked then set the action.
236
      String action = ((String[])params.get("action"))[0];  
237
      util.debugMessage("Line 213: Action is: " + action);
238
  
239
      // This block handles session management for the servlet
240
      // by looking up the current session information for all actions
241
      // other than "login" and "logout"
242
      String username = null;
243
      String password = null;
244
      String[] groupnames = null;
245
      String sess_id = null;
246
  
247
      // handle login action
248
      if (action.equals("login")) {
249
  
250
        handleLoginAction(response.getWriter(), params, request, response);
251
  
252
      // handle logout action  
253
      } else if (action.equals("logout")) {
254
  
255
        handleLogoutAction(response.getWriter(), params, request, response);
256
  
257
      // aware of session expiration on every request  
258
      } else {   
259
  
260
        HttpSession sess = request.getSession(true);
261
        if (sess.isNew()) { 
262
          // session expired or has not been stored b/w user requests
263
          username = "public";
264
          sess.setAttribute("username", username);
265
        } else {
266
          username = (String)sess.getAttribute("username");
267
          password = (String)sess.getAttribute("password");
268
          groupnames = (String[])sess.getAttribute("groupnames");
269
          try {
270
            sess_id = (String)sess.getId();
271
          } catch(IllegalStateException ise) {
272
            System.out.println("error in handleGetOrPost: this shouldn't " +
273
                               "happen: the session should be valid: " + 
274
                               ise.getMessage());
275
          }
276
        }  
277
      }    
278
  
279
      // Now that we know the session is valid, we can delegate the request
280
      // to a particular action handler
281
      if(action.equals("query")) {
282
        handleQuery(response.getWriter(),params,response,username,groupnames);
283
      } else if(action.equals("squery")) {
284
        if(params.containsKey("query")) {
285
         handleSQuery(response.getWriter(),params,response,username,groupnames); 
286
        } else {
287
          PrintWriter out = response.getWriter();
288
          out.println("Illegal action squery without \"query\" parameter");
289
        }
290
      } else if (action.equals("export")) {
291
        //username and groupname have to continue using though they are 
292
        //not standard
293
        handleExportAction(params, response, username, groupnames);
294
      } else if (action.equals("read")) {
295
        handleReadAction(params, response, username, groupnames);
296
      } else if (action.equals("insert") || action.equals("update")) {
297
        PrintWriter out = response.getWriter();
298
        if ( (username != null) &&  !username.equals("public") ) {
299
          handleInsertOrUpdateAction(out,params,response,username,groupnames);
300
        } 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
          handleDeleteAction(out, params, response, username, groupnames);
307
        } 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
        handleGetAccessControlAction(out,params,response,username,groupnames);
316
      } 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
        handleGetMaxDocidAction(out, params, response);  
331
      } 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
          }
364
          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
        }
373
      } 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
      }
380
      
381
      util.closeConnections();
382
      // Close the stream to the client
383
      // out.close();
384
    }
385
  }
386
  
387
  // LOGIN & LOGOUT SECTION
388
  /** 
389
   * Handle the login request. Create a new session object.
390
   * Do user authentication through the session.
391
   */
392
  private void handleLoginAction(PrintWriter out, Hashtable params, 
393
               HttpServletRequest request, HttpServletResponse response) {
394

    
395
    AuthSession sess = null;
396
    String un = ((String[])params.get("username"))[0];
397
    String pw = ((String[])params.get("password"))[0];
398
    String action = ((String[])params.get("action"))[0];
399
    String qformat = ((String[])params.get("qformat"))[0];
400
    
401
    try {
402
      sess = new AuthSession();
403
    } catch (Exception e) {
404
      System.out.println("error in MetacatServlet.handleLoginAction: " +
405
                          e.getMessage());
406
      out.println(e.getMessage());
407
      return;
408
    }
409
    boolean isValid = sess.authenticate(request, un, pw);
410
    // format and transform the output
411
    if (qformat.equals("xml")) {
412
      response.setContentType("text/xml");
413
      out.println(sess.getMessage()); 
414
    } else {
415
      Connection conn = null;
416
      try {
417
        conn = util.getConnection();
418
        DBTransform trans = new DBTransform(conn);
419
        response.setContentType("text/html");
420
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
421
                                   "-//W3C//HTML//EN", qformat, out);
422
        util.returnConnection(conn); 
423
      } catch(Exception e) {
424
        util.returnConnection(conn); 
425
      } 
426
      
427
    // any output is returned  
428
    }
429
  }    
430

    
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
    output.append("<logout>");
447
    output.append("User logged out");
448
    output.append("</logout>");
449

    
450
    //format and transform the output
451
    if (qformat.equals("xml")) {
452
      response.setContentType("text/xml");
453
      out.println(output.toString()); 
454
    } else {
455
      Connection conn = null;
456
      try {
457
        conn = util.getConnection();
458
        DBTransform trans = new DBTransform(conn);
459
        response.setContentType("text/html");
460
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN", 
461
                                   "-//W3C//HTML//EN", qformat, out);
462
        util.returnConnection(conn); 
463
      } catch(Exception e) {
464
        util.returnConnection(conn); 
465
      } 
466
    }
467
  }
468
  // END OF LOGIN & LOGOUT SECTION
469
  
470
  // SQUERY & QUERY SECTION
471
  /**      
472
   * 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
                 HttpServletResponse response, String user, String[] groups)
482
  { 
483
    String xmlquery = ((String[])params.get("query"))[0];
484
    String qformat = ((String[])params.get("qformat"))[0];
485
    String resultdoc = null;
486
    
487
    Hashtable doclist = runQuery(xmlquery, user, groups);
488

    
489
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
490
    
491
    //format and transform the results                                        
492
    if(qformat.equals("xml")) {
493
      response.setContentType("text/xml");
494
      out.println(resultdoc);
495
    } else {
496
      transformResultset(resultdoc, response, out, qformat);
497
    }
498
  }
499
  
500
   /**
501
    * 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
    * in the squery.
506
    * @param response the response object linked to the client
507
    */ 
508
  protected void handleQuery(PrintWriter out, Hashtable params, 
509
                 HttpServletResponse response, String user, String[] groups)
510
  {
511
    //create the query and run it
512
    String xmlquery = DBQuery.createSQuery(params);
513
    Hashtable doclist = runQuery(xmlquery, user, groups);
514
    String qformat = ((String[])params.get("qformat"))[0];
515
    String resultdoc = null;
516
    
517
    resultdoc = createResultDocument(doclist, transformQuery(params));
518

    
519
    //format and transform the results                                        
520
    if(qformat.equals("xml")) {
521
      response.setContentType("text/xml");
522
      out.println(resultdoc);
523
    } else { 
524
      transformResultset(resultdoc, response, out, qformat);
525
    }
526
  }
527
  
528
  /**
529
   * 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
   * 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
   * Run the query and return a hashtable of results.
563
   *
564
   * @param xmlquery the query to run
565
   */
566
  private Hashtable runQuery(String xmlquery, String user, String[] groups)
567
  {
568
    Hashtable doclist=null;
569
    Connection conn = null;
570
    try
571
    {
572
      conn = util.getConnection();
573
      DBQuery queryobj = new DBQuery(conn, saxparser);
574
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,groups);
575
      util.returnConnection(conn);
576
      return doclist;
577
    } 
578
    catch (Exception e) 
579
    {
580
      util.returnConnection(conn); 
581
      util.debugMessage("Error in MetacatServlet.runQuery: " + e.getMessage());
582
      doclist = null;
583
      return doclist;
584
    }    
585
  }
586
  
587
  /**
588
   * Transorms an xml resultset document to html and sends it to the browser
589
   *
590
   * @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
   * @param qformat the name of the style-set to use for transformations
595
   */ 
596
  protected void transformResultset(String resultdoc, 
597
                                    HttpServletResponse response,
598
                                    PrintWriter out, String qformat)
599
  {
600
    Connection conn = null;
601
    try {
602
      conn = util.getConnection();
603
      DBTransform trans = new DBTransform(conn);
604
      response.setContentType("text/html");
605
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
606
                                 "-//W3C//HTML//EN", qformat, out);
607
      util.returnConnection(conn); 
608
    }
609
    catch(Exception e)
610
    {
611
      util.returnConnection(conn); 
612
    } 
613
  }
614
  
615
  /**
616
   * Transforms a hashtable of documents to an xml or html result.
617
   *
618
   * @param doclist- the hashtable to transform
619
   * @param xmlquery- the query that returned the doclist result
620
   */
621
  protected String createResultDocument(Hashtable doclist, String xmlquery)
622
  {
623
    // Create a buffer to hold the xml result
624
    StringBuffer resultset = new StringBuffer();
625
 
626
    // Print the resulting root nodes 
627
    String docid = null;
628
    String document = null;
629
    resultset.append("<?xml version=\"1.0\"?>\n");
630
    resultset.append("<resultset>\n");
631
      
632
    resultset.append("  <query>" + xmlquery + "</query>");   
633

    
634
    if(doclist != null)
635
    {
636
      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
    resultset.append("</resultset>");
646
    return resultset.toString();
647
  }
648
  // END OF SQUERY & QUERY SECTION
649
  
650
 //Exoport section
651
 /**
652
   * Handle the "export" request of data package from Metacat in zip format
653
   * @param params the Hashtable of HTTP request parameters
654
   * @param response the HTTP response object linked to the client
655
   * @param user the username sent the request
656
   * @param groups the user's groupnames
657
   */
658
  private void handleExportAction(Hashtable params,
659
                    HttpServletResponse response, String user, String[] groups)
660
  {
661
    ServletOutputStream out = null;
662
    ZipOutputStream zOut = null;
663
    DocumentImpl docImpls=null;
664
    DBQuery queryObj=null;
665
    Connection conn = null;
666
    String[] docs = new String[10];
667
    String docId = "";
668

    
669
    try
670
    {
671
      // read the params
672
      if (params.containsKey("docid")) {
673
        docs = (String[])params.get("docid");
674
      }
675

    
676
      //get the connection to database
677
      conn = util.getConnection();
678
      queryObj = new DBQuery(conn, saxparser);//"saxparser" have to use though
679
                                              //it is not standard
680
      docId=docs[0];
681
      out = response.getOutputStream();
682
      response.setContentType("application/zip"); //MIME type
683
      zOut = new ZipOutputStream(out);
684
      zOut =queryObj.getZippedPackage(docId, out, user, groups);
685
      zOut.finish(); //terminate the zip file
686
      zOut.close();  //close the zip stream
687
    } 
688
    catch (Exception e)
689
    {
690
      try
691
      {
692
        response.setContentType("text/xml"); //MIME type
693
        if (out != null)
694
        {
695
            PrintWriter pw = new PrintWriter(out);
696
            pw.println("<?xml version=\"1.0\"?>");
697
            pw.println("<error>");
698
            pw.println(e.getMessage());
699
            pw.println("</error>");
700
            pw.close();
701
        }
702

    
703
        if ( zOut != null )
704
        {
705
          zOut.close();
706
        }
707
      }
708
      catch (IOException ioe)
709
      {
710
        util.debugMessage("Problem with the servlet output " +
711
                           "in MetacatServlet.handleReadAction: " +
712
                           ioe.getMessage());
713
        
714

    
715
      }
716

    
717
      util.debugMessage("Error in MetacatServlet.handleReadAction: " +
718
                         e.getMessage());
719
      
720
    }//catch
721

    
722
  }//handleExportAction
723
  
724
  // READ SECTION
725
  /** 
726
   * Handle the "read" request of metadata/data files from Metacat
727
   * or any files from Internet;
728
   * transformed metadata XML document into HTML presentation if requested;
729
   * zip files when more than one were requested.
730
   *
731
   * @param params the Hashtable of HTTP request parameters
732
   * @param response the HTTP response object linked to the client
733
   * @param user the username sent the request
734
   * @param groups the user's groupnames
735
   */
736
  private void handleReadAction(Hashtable params, HttpServletResponse response,
737
                                String user, String[] groups) 
738
  {
739
    ServletOutputStream out = null;
740
    ZipOutputStream zout = null;
741
    
742
    try {
743
      String[] docs = new String[0];
744
      String docid = "";
745
      String qformat = "";
746
      String abstrpath = null;
747
      boolean zip = false;
748
      // read the params
749
      if (params.containsKey("docid")) {
750
        docs = (String[])params.get("docid");
751
      }
752
      if (params.containsKey("qformat")) {
753
        qformat = ((String[])params.get("qformat"))[0];
754
      }
755
      if (params.containsKey("abstractpath")) {
756
        abstrpath = ((String[])params.get("abstractpath"))[0];
757
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
758
          viewAbstract(response, abstrpath, docs[0]);
759
          return;
760
        }
761
      }
762
      if ( (docs.length > 1) || qformat.equals("zip") ) {
763
        zip = true;
764
        out = response.getOutputStream();
765
        response.setContentType("application/zip"); //MIME type
766
        zout = new ZipOutputStream(out);
767
      }
768
      // go through the list of docs to read
769
      for (int i=0; i < docs.length; i++ ) {
770
        try {
771

    
772
          URL murl = new URL(docs[i]);
773
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
774
          // case docid="http://.../?docid=aaa" 
775
          // or docid="metacat://.../?docid=bbb"
776
          if (murlQueryStr.containsKey("docid")) {
777
            // get only docid, eliminate the rest
778
            docid = (String)murlQueryStr.get("docid");
779
            if ( zip ) {
780
              addDocToZip(docid, zout);
781
            } else {
782
              readFromMetacat(response, docid, qformat, abstrpath,
783
                              user, groups, zip, zout);
784
            }
785

    
786
          // case docid="http://.../filename"
787
          } else {
788
            docid = docs[i];
789
            if ( zip ) {
790
              addDocToZip(docid, zout);
791
            } else {
792
              readFromURLConnection(response, docid);
793
            }
794
          }
795

    
796
        // case docid="ccc"
797
        } catch (MalformedURLException mue) {
798
          docid = docs[i];
799
          if ( zip ) {
800
            addDocToZip(docid, zout);
801
          } else {
802
            readFromMetacat(response, docid, qformat, abstrpath,
803
                            user, groups, zip, zout);
804
          }
805
        }
806
        
807
      } /* end for */
808
      
809
      if ( zip ) {
810
        zout.finish(); //terminate the zip file
811
        zout.close();  //close the zip stream
812
      }
813
      
814
        /*
815
    } catch (ClassNotFoundException cnfe) {
816
    } catch (IOException ioe1) {
817
    } catch (SQLException se) {
818
    } catch (McdbException mcdbe) {
819
    } catch (Exception e) {
820
      */
821
    } catch (Exception e) {
822
      try {
823
        response.setContentType("text/xml"); //MIME type
824
        //PrintWriter pw = response.getWriter();
825
        if (out != null) {
826
            PrintWriter pw = new PrintWriter(out);
827
            pw.println("<?xml version=\"1.0\"?>");
828
            pw.println("<error>");
829
            pw.println(e.getMessage());
830
            pw.println("</error>");
831
            pw.close();
832
        }
833
        //if ( out != null ) { out.close(); }
834
        if ( zout != null ) { zout.close(); }
835
      } catch (IOException ioe) {
836
        System.out.println("Problem with the servlet output " +
837
                           "in MetacatServlet.handleReadAction: " +
838
                           ioe.getMessage());
839
        ioe.printStackTrace(System.out);
840
        
841
      }
842

    
843
      System.out.println("Error in MetacatServlet.handleReadAction: " +
844
                         e.getMessage());
845
      e.printStackTrace(System.out);
846
    }
847
    
848
  }
849
  
850
  // read metadata or data from Metacat
851
  private void readFromMetacat(HttpServletResponse response, String docid,
852
                               String qformat, String abstrpath, String user,
853
                             String[] groups, boolean zip, ZipOutputStream zout)
854
               throws ClassNotFoundException, IOException, SQLException, 
855
                      McdbException, Exception
856
  {
857
    Connection conn = null;
858
    try {
859
      conn = util.getConnection();
860
      DocumentImpl doc = new DocumentImpl(conn, docid);
861
      
862
      if ( doc.getRootNodeID() == 0 ) {
863
        // this is data file
864
        ServletOutputStream out = response.getOutputStream(); 
865
        String filepath = util.getOption("datafilepath");
866
        if(!filepath.endsWith("/")) {
867
          filepath += "/";
868
        }
869
        String filename = filepath + docid;      //MIME type
870
        String contentType = getServletContext().getMimeType(filename);
871
        if (contentType == null) {
872
          if (filename.endsWith(".xml")) {
873
            contentType="text/xml";
874
          } else if (filename.endsWith(".css")) {
875
            contentType="text/css";
876
          } else if (filename.endsWith(".dtd")) {
877
            contentType="text/plain";
878
          } else if (filename.endsWith(".xsd")) {
879
            contentType="text/xml";
880
          } else if (filename.endsWith("/")) {
881
            contentType="text/html";
882
          } else {
883
            File f = new File(filename);
884
            if ( f.isDirectory() ) {
885
              contentType="text/html";
886
            } else {
887
              contentType="application/octet-stream";
888
            }
889
          }
890
        }
891
        response.setContentType(contentType);
892
        // if we decide to use "application/octet-stream" for all data returns
893
        // response.setContentType("application/octet-stream");
894
        FileInputStream fin = null;
895
        try {
896
          fin = new FileInputStream(filename);
897
          byte[] buf = new byte[4 * 1024]; // 4K buffer
898
          int b = fin.read(buf);
899
          while (b != -1) {
900
            out.write(buf, 0, b);
901
            b = fin.read(buf);
902
          }
903
        } finally {
904
          if (fin != null) fin.close();
905
        }
906

    
907
      } else {
908
        // this is metadata doc
909
        if ( qformat.equals("xml") ) { 
910
          // set content type first
911
          response.setContentType("text/xml");   //MIME type
912
          PrintWriter out = response.getWriter();
913
          doc.toXml(out);
914
        } else {
915
          response.setContentType("text/html");  //MIME type
916
          PrintWriter out = response.getWriter();
917
    
918
          // Look up the document type
919
          String doctype = doc.getDoctype();
920
          // Transform the document to the new doctype
921
          DBTransform dbt = new DBTransform(conn);
922
          dbt.transformXMLDocument(doc.toString(),
923
                                   doctype,"-//W3C//HTML//EN", qformat, out);
924
        }
925
      
926
      }
927
    } finally {
928
      util.returnConnection(conn);
929
    }
930
    
931
  }
932
  
933
  // read data from URLConnection
934
  private void readFromURLConnection(HttpServletResponse response, String docid)
935
               throws IOException, MalformedURLException
936
  {
937
    ServletOutputStream out = response.getOutputStream(); 
938
    String contentType = getServletContext().getMimeType(docid); //MIME type
939
    if (contentType == null) {
940
      if (docid.endsWith(".xml")) {
941
        contentType="text/xml";
942
      } else if (docid.endsWith(".css")) {
943
        contentType="text/css";
944
      } else if (docid.endsWith(".dtd")) {
945
        contentType="text/plain";
946
      } else if (docid.endsWith(".xsd")) {
947
        contentType="text/xml";
948
      } else if (docid.endsWith("/")) {
949
        contentType="text/html";
950
      } else {
951
        File f = new File(docid);
952
        if ( f.isDirectory() ) {
953
          contentType="text/html";
954
        } else {
955
          contentType="application/octet-stream";
956
        }
957
      }
958
    }
959
    response.setContentType(contentType);
960
    // if we decide to use "application/octet-stream" for all data returns
961
    // response.setContentType("application/octet-stream");
962

    
963
    // this is http url
964
    URL url = new URL(docid);
965
    BufferedInputStream bis = null;
966
    try {
967
      bis = new BufferedInputStream(url.openStream());
968
      byte[] buf = new byte[4 * 1024]; // 4K buffer
969
      int b = bis.read(buf);
970
      while (b != -1) {
971
        out.write(buf, 0, b);
972
        b = bis.read(buf);
973
      }
974
    } finally {
975
      if (bis != null) bis.close();
976
    }
977
    
978
  }
979
  
980
  // read file/doc and write to ZipOutputStream
981
  private void addDocToZip(String docid, ZipOutputStream zout)
982
               throws ClassNotFoundException, IOException, SQLException, 
983
                      McdbException, Exception
984
  {
985
    byte[] bytestring = null;
986
    ZipEntry zentry = null;
987

    
988
    try {
989
      URL url = new URL(docid);
990

    
991
      // this http url; read from URLConnection; add to zip
992
      zentry = new ZipEntry(docid);
993
      zout.putNextEntry(zentry);
994
      BufferedInputStream bis = null;
995
      try {
996
        bis = new BufferedInputStream(url.openStream());
997
        byte[] buf = new byte[4 * 1024]; // 4K buffer
998
        int b = bis.read(buf);
999
        while(b != -1) {
1000
          zout.write(buf, 0, b);
1001
          b = bis.read(buf);
1002
        }
1003
      } finally {
1004
        if (bis != null) bis.close();
1005
      }
1006
      zout.closeEntry();
1007

    
1008
    } catch (MalformedURLException mue) {
1009
      
1010
      // this is metacat doc (data file or metadata doc)
1011
      Connection conn = null;
1012
      try {
1013
        conn = util.getConnection();
1014
        DocumentImpl doc = new DocumentImpl(conn, docid);
1015
      
1016
        if ( doc.getRootNodeID() == 0 ) {
1017
          // this is data file; add file to zip
1018
          String filepath = util.getOption("datafilepath");
1019
          if(!filepath.endsWith("/")) {
1020
            filepath += "/";
1021
          }
1022
          String filename = filepath + doc.getDocname();
1023
          zentry = new ZipEntry(filename);
1024
          zout.putNextEntry(zentry);
1025
          FileInputStream fin = null;
1026
          try {
1027
            fin = new FileInputStream(filename);
1028
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1029
            int b = fin.read(buf);
1030
            while (b != -1) {
1031
              zout.write(buf, 0, b);
1032
              b = fin.read(buf);
1033
            }
1034
          } finally {
1035
            if (fin != null) fin.close();
1036
          }
1037
          zout.closeEntry();
1038

    
1039
        } else {
1040
          // this is metadata doc; add doc to zip
1041
          bytestring = doc.toString().getBytes();
1042
          zentry = new ZipEntry(docid + ".xml");
1043
          zentry.setSize(bytestring.length);
1044
          zout.putNextEntry(zentry);
1045
          zout.write(bytestring, 0, bytestring.length);
1046
          zout.closeEntry();
1047
        }
1048
      } finally {
1049
        util.returnConnection(conn);
1050
      }
1051
      
1052
    }
1053
      
1054
  }
1055
  
1056
  // view abstract within document
1057
  private void viewAbstract(HttpServletResponse response,
1058
                            String abstractpath, String docid)
1059
               throws ClassNotFoundException, IOException, SQLException,
1060
                      McdbException, Exception
1061
  {
1062
    Connection conn = null;
1063
    try {
1064
      conn = util.getConnection();
1065
    
1066
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
1067
    
1068
      response.setContentType("text/html");  //MIME type
1069
      PrintWriter out = response.getWriter();
1070
      out.println("<html><head><title>Abstract</title></head>");
1071
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
1072
      for (int i=0; i<abstracts.length; i++) {
1073
        out.println("<p>" + (String)abstracts[i] + "</p>");
1074
      }
1075
      out.println("</body></html>");
1076

    
1077
    } finally {
1078
      util.returnConnection(conn);
1079
    }
1080
  }
1081
  // END OF READ SECTION
1082
    
1083
  // INSERT/UPDATE SECTION
1084
  /** 
1085
   * Handle the database putdocument request and write an XML document 
1086
   * to the database connection
1087
   */
1088
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
1089
               HttpServletResponse response, String user, String[] groups) {
1090

    
1091
    Connection conn = null;
1092

    
1093
    try {
1094
      // Get the document indicated
1095
      String[] doctext = (String[])params.get("doctext");
1096

    
1097
      String pub = null;
1098
      if (params.containsKey("public")) {
1099
        pub = ((String[])params.get("public"))[0];
1100
      }
1101

    
1102
      StringReader dtd = null;
1103
      if (params.containsKey("dtdtext")) {
1104
        String[] dtdtext = (String[])params.get("dtdtext");
1105
        try {
1106
          if ( !dtdtext[0].equals("") ) {
1107
            dtd = new StringReader(dtdtext[0]);
1108
          }
1109
        } catch (NullPointerException npe) {}
1110
      }
1111
      
1112
      StringReader xml = null;
1113
      boolean validate = false;
1114
      try {
1115
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... > 
1116
        // in order to decide whether to use validation parser
1117
        validate = validateXML(doctext[0]);
1118
        xml = new StringReader(doctext[0]);
1119

    
1120
        String[] action = (String[])params.get("action");
1121
        String[] docid = (String[])params.get("docid");
1122
        String newdocid = null;
1123

    
1124
        String doAction = null;
1125
        if (action[0].equals("insert")) {
1126
          doAction = "INSERT";
1127
        } else if (action[0].equals("update")) {
1128
          doAction = "UPDATE";
1129
        }
1130

    
1131
        try {
1132
          // get a connection from the pool
1133
          conn = util.getConnection();
1134

    
1135
          // write the document to the database
1136
          try {
1137
            String accNumber = docid[0];
1138
            if (accNumber.equals("")) {
1139
              accNumber = null;
1140
            }
1141
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1142
                                          accNumber, user, groups, validate);
1143
          } catch (NullPointerException npe) {
1144
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1145
                                          null, user, groups, validate);
1146
          }
1147
        } finally {
1148
          util.returnConnection(conn);
1149
        }    
1150

    
1151
        // set content type and other response header fields first
1152
        response.setContentType("text/xml");
1153
        out.println("<?xml version=\"1.0\"?>");
1154
        out.println("<success>");
1155
        out.println("<docid>" + newdocid + "</docid>"); 
1156
        out.println("</success>");
1157

    
1158
      } catch (NullPointerException npe) {
1159
        response.setContentType("text/xml");
1160
        out.println("<?xml version=\"1.0\"?>");
1161
        out.println("<error>");
1162
        out.println(npe.getMessage()); 
1163
        out.println("</error>");
1164
      }
1165
    } catch (Exception e) {
1166
      response.setContentType("text/xml");
1167
      out.println("<?xml version=\"1.0\"?>");
1168
      out.println("<error>");
1169
      out.println(e.getMessage()); 
1170
      if (e instanceof SAXException) {
1171
        Exception e2 = ((SAXException)e).getException();
1172
        out.println("<error>");
1173
        try
1174
        {
1175
          out.println(e2.getMessage());
1176
        }
1177
        catch(NullPointerException npe)
1178
        {
1179
          out.println(e.getMessage());
1180
        }
1181
        out.println("</error>");
1182
      }
1183
      //e.printStackTrace(out);
1184
      out.println("</error>");
1185
    }
1186
  }
1187

    
1188
  /** 
1189
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > 
1190
   * in order to decide whether to use validation parser
1191
   */
1192
  private static boolean validateXML(String xmltext) throws IOException {
1193
    
1194
    StringReader xmlreader = new StringReader(xmltext);
1195
    StringBuffer cbuff = new StringBuffer();
1196
    java.util.Stack st = new java.util.Stack();
1197
    boolean validate = false;
1198
    int c;
1199
    int inx;
1200
    
1201
    // read from the stream until find the keywords
1202
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1203
      cbuff.append((char)c);
1204

    
1205
      // "<!DOCTYPE" keyword is found; put it in the stack
1206
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1207
        cbuff = new StringBuffer();
1208
        st.push("<!DOCTYPE");
1209
      }
1210
      // "PUBLIC" keyword is found; put it in the stack
1211
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1212
        cbuff = new StringBuffer();
1213
        st.push("PUBLIC");
1214
      }
1215
      // "SYSTEM" keyword is found; put it in the stack
1216
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1217
        cbuff = new StringBuffer();
1218
        st.push("SYSTEM");
1219
      }
1220
      // ">" character is found; put it in the stack
1221
      // ">" is found twice: fisrt from <?xml ...?> 
1222
      // and second from <!DOCTYPE ... >
1223
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1224
        cbuff = new StringBuffer();
1225
        st.push(">");
1226
      }
1227
    }
1228

    
1229
    // close the stream
1230
    xmlreader.close();
1231

    
1232
    // check the stack whether it contains the keywords:
1233
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1234
    if ( st.size() == 4 ) {
1235
      if ( ((String)st.pop()).equals(">") &&
1236
           ( ((String)st.peek()).equals("PUBLIC") |
1237
             ((String)st.pop()).equals("SYSTEM") ) &&
1238
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1239
        validate = true;
1240
      }
1241
    }
1242

    
1243
System.out.println("Validation is " + validate);
1244
    return validate;
1245
  }
1246
  // END OF INSERT/UPDATE SECTION
1247

    
1248
  // DELETE SECTION
1249
  /** 
1250
   * Handle the database delete request and delete an XML document 
1251
   * from the database connection
1252
   */
1253
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1254
               HttpServletResponse response, String user, String[] groups) {
1255

    
1256
    String[] docid = (String[])params.get("docid");
1257
    Connection conn = null;
1258

    
1259
    // delete the document from the database
1260
    try {
1261
      // get a connection from the pool
1262
      conn = util.getConnection();
1263
                                      // NOTE -- NEED TO TEST HERE
1264
                                      // FOR EXISTENCE OF DOCID PARAM
1265
                                      // BEFORE ACCESSING ARRAY
1266
      try { 
1267
        DocumentImpl.delete(conn, docid[0], user, groups);
1268
        response.setContentType("text/xml");
1269
        out.println("<?xml version=\"1.0\"?>");
1270
        out.println("<success>");
1271
        out.println("Document deleted."); 
1272
        out.println("</success>");
1273
      } catch (AccessionNumberException ane) {
1274
        response.setContentType("text/xml");
1275
        out.println("<?xml version=\"1.0\"?>");
1276
        out.println("<error>");
1277
        out.println("Error deleting document!!!");
1278
        out.println(ane.getMessage()); 
1279
        out.println("</error>");
1280
      }
1281
    } catch (Exception e) {
1282
      response.setContentType("text/xml");
1283
      out.println("<?xml version=\"1.0\"?>");
1284
      out.println("<error>");
1285
      out.println(e.getMessage()); 
1286
      out.println("</error>");
1287
    } finally {
1288
      util.returnConnection(conn);
1289
    }  
1290
  }
1291
  // END OF DELETE SECTION
1292
  
1293
  // VALIDATE SECTION
1294
  /** 
1295
   * Handle the validation request and return the results to the requestor
1296
   */
1297
  private void handleValidateAction(PrintWriter out, Hashtable params, 
1298
               HttpServletResponse response) {
1299

    
1300
    // Get the document indicated
1301
    String valtext = null;
1302
    
1303
    try {
1304
      valtext = ((String[])params.get("valtext"))[0];
1305
    } catch (Exception nullpe) {
1306

    
1307
      Connection conn = null;
1308
      String docid = null;
1309
      try {
1310
        // Find the document id number
1311
        docid = ((String[])params.get("docid"))[0]; 
1312

    
1313
        // get a connection from the pool
1314
        conn = util.getConnection();
1315

    
1316
        // Get the document indicated from the db
1317
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1318
        valtext = xmldoc.toString();
1319

    
1320
      } catch (NullPointerException npe) {
1321
        response.setContentType("text/xml");
1322
        out.println("<error>Error getting document ID: " + docid + "</error>");
1323
        if ( conn != null ) { util.returnConnection(conn); }
1324
        return;
1325
      } catch (Exception e) {
1326
        response.setContentType("text/html");
1327
        out.println(e.getMessage()); 
1328
      } finally {
1329
        util.returnConnection(conn);
1330
      }  
1331
    }
1332

    
1333
    Connection conn = null;
1334
    try {
1335
      // get a connection from the pool
1336
      conn = util.getConnection();
1337
      DBValidate valobj = new DBValidate(saxparser,conn);
1338
      boolean valid = valobj.validateString(valtext);
1339

    
1340
      // set content type and other response header fields first
1341
      response.setContentType("text/xml");
1342
      out.println(valobj.returnErrors());
1343

    
1344
    } catch (NullPointerException npe2) {
1345
      // set content type and other response header fields first
1346
      response.setContentType("text/xml");
1347
      out.println("<error>Error validating document.</error>"); 
1348
    } catch (Exception e) {
1349
      response.setContentType("text/html");
1350
      out.println(e.getMessage()); 
1351
    } finally {
1352
      util.returnConnection(conn);
1353
    }  
1354
  }
1355
  // END OF VALIDATE SECTION
1356
 
1357
  // OTHER ACTION HANDLERS
1358
  
1359
  /** 
1360
   * Handle "getaccesscontrol" action.
1361
   * Read Access Control List from db connection in XML format
1362
   */
1363
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params, 
1364
                                       HttpServletResponse response, 
1365
                                       String username, String[] groupnames) {
1366

    
1367
    Connection conn = null;
1368
    String docid = ((String[])params.get("docid"))[0];
1369
    
1370
    try {
1371

    
1372
        // get connection from the pool
1373
        conn = util.getConnection();
1374
        AccessControlList aclobj = new AccessControlList(conn);
1375
        String acltext = aclobj.getACL(docid, username, groupnames);
1376
        out.println(acltext);
1377

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

    
1389
  /** 
1390
   * Handle the "getprincipals" action.
1391
   * Read all principals from authentication scheme in XML format
1392
   */
1393
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1394
                                         String password) {
1395

    
1396
    Connection conn = null;
1397

    
1398
    try {
1399

    
1400
        // get connection from the pool
1401
        AuthSession auth = new AuthSession();
1402
        String principals = auth.getPrincipals(user, password);
1403
        out.println(principals);
1404

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

    
1416
  /** 
1417
   * Handle "getdoctypes" action.
1418
   * Read all doctypes from db connection in XML format
1419
   */
1420
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1421
                                       HttpServletResponse response) {
1422

    
1423
    Connection conn = null;
1424
    
1425
    try {
1426

    
1427
        // get connection from the pool
1428
        conn = util.getConnection();
1429
        DBUtil dbutil = new DBUtil(conn);
1430
        String doctypes = dbutil.readDoctypes();
1431
        out.println(doctypes);
1432

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

    
1444
  /** 
1445
   * Handle the "getdtdschema" action.
1446
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1447
   */
1448
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1449
                                        HttpServletResponse response) {
1450

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

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

    
1461
    try {
1462

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

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

    
1480
  /** 
1481
   * Handle the "getdataguide" action.
1482
   * Read Data Guide for a given doctype from db connection in XML format
1483
   */
1484
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1485
                                        HttpServletResponse response) {
1486

    
1487
    Connection conn = null;
1488
    String doctype = null;
1489
    String[] doctypeArr = (String[])params.get("doctype");
1490

    
1491
    // get only the first doctype specified in the list of doctypes
1492
    // it could be done for all doctypes in that list
1493
    if (doctypeArr != null) {
1494
        doctype = ((String[])params.get("doctype"))[0]; 
1495
    }
1496

    
1497
    try {
1498

    
1499
        // get connection from the pool
1500
        conn = util.getConnection();
1501
        DBUtil dbutil = new DBUtil(conn);
1502
        String dataguide = dbutil.readDataGuide(doctype);
1503
        out.println(dataguide);
1504

    
1505
    } catch (Exception e) {
1506
      out.println("<?xml version=\"1.0\"?>");
1507
      out.println("<error>");
1508
      out.println(e.getMessage());
1509
      out.println("</error>");
1510
    } finally {
1511
      util.returnConnection(conn);
1512
    }  
1513
    
1514
  }
1515

    
1516
  /** 
1517
   * Handle the "getlastdocid" action.
1518
   * Get the latest docid with rev number from db connection in XML format
1519
   */
1520
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params, 
1521
                                        HttpServletResponse response) {
1522

    
1523
    Connection conn = null;
1524
    String scope = ((String[])params.get("scope"))[0];
1525
    if (scope == null) {
1526
        scope = ((String[])params.get("username"))[0];
1527
    }
1528

    
1529
    try {
1530

    
1531
        // get connection from the pool
1532
        conn = util.getConnection();
1533
        DBUtil dbutil = new DBUtil(conn);
1534
        String lastDocid = dbutil.getMaxDocid(scope);
1535
        out.println("<?xml version=\"1.0\"?>");
1536
        out.println("<lastDocid>");
1537
        out.println("  <scope>" + scope + "</scope>");
1538
        out.println("  <docid>" + lastDocid + "</docid>");
1539
        out.println("</lastDocid>");
1540

    
1541
    } catch (Exception e) {
1542
      out.println("<?xml version=\"1.0\"?>");
1543
      out.println("<error>");
1544
      out.println(e.getMessage());
1545
      out.println("</error>");
1546
    } finally {
1547
      util.returnConnection(conn);
1548
    }  
1549
    
1550
  }
1551

    
1552
  /** 
1553
   * Handle documents passed to metacat that are encoded using the 
1554
   * "multipart/form-data" mime type.  This is typically used for uploading
1555
   * data files which may be binary and large.
1556
   */
1557
  private void handleMultipartForm(HttpServletRequest request,
1558
                                   HttpServletResponse response) 
1559
  {
1560
    PrintWriter out = null;
1561
    String action = null;
1562

    
1563
    // Parse the multipart form, and save the parameters in a Hashtable and
1564
    // save the FileParts in a hashtable
1565

    
1566
    Hashtable params = new Hashtable();
1567
    Hashtable fileList = new Hashtable();
1568

    
1569
    try {
1570
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
1571
      MultipartParser mp = new MultipartParser(request, 200*1024*1024); //200MB
1572
      Part part;
1573
      while ((part = mp.readNextPart()) != null) {
1574
        String name = part.getName();
1575

    
1576
        if (part.isParam()) {
1577
          // it's a parameter part
1578
          ParamPart paramPart = (ParamPart) part;
1579
          String value = paramPart.getStringValue();
1580
          params.put(name, value);
1581
          if (name.equals("action")) {
1582
            action = value;
1583
          }
1584
        } else if (part.isFile()) {
1585
          // it's a file part
1586
          FilePart filePart = (FilePart) part;
1587
          fileList.put(name, filePart);
1588

    
1589
          // Stop once the first file part is found, otherwise going onto the
1590
          // next part prevents access to the file contents.  So...for upload
1591
          // to work, the datafile must be the last part
1592
          break;
1593
        }
1594
      }
1595
    } catch (IOException ioe) {
1596
      try {
1597
        out = response.getWriter();
1598
      } catch (IOException ioe2) {
1599
        System.err.println("Fatal Error: couldn't get response output stream.");
1600
      }
1601
      out.println("<?xml version=\"1.0\"?>");
1602
      out.println("<error>");
1603
      out.println("Error: problem reading multipart data.");
1604
      out.println("</error>");
1605
    }
1606

    
1607
    // Get the session information
1608
    String username = null;
1609
    String password = null;
1610
    String[] groupnames = null;
1611
    String sess_id = null;
1612

    
1613
    // be aware of session expiration on every request  
1614
    HttpSession sess = request.getSession(true);
1615
    if (sess.isNew()) {
1616
      // session expired or has not been stored b/w user requests
1617
      username = "public";
1618
      sess.setAttribute("username", username);
1619
    } else {
1620
      username = (String)sess.getAttribute("username");
1621
      password = (String)sess.getAttribute("password");
1622
      groupnames = (String[])sess.getAttribute("groupnames");
1623
      try {
1624
        sess_id = (String)sess.getId();
1625
      } catch(IllegalStateException ise) {
1626
        System.out.println("error in  handleMultipartForm: this shouldn't " +
1627
                           "happen: the session should be valid: " + 
1628
                           ise.getMessage());
1629
      }
1630
    }  
1631

    
1632
    if ( action.equals("upload")) {
1633
      if (username != null &&  !username.equals("public")) {
1634
        handleUploadAction(request, response, params, fileList, 
1635
                           username, groupnames);
1636
      } else {
1637
        try {
1638
          out = response.getWriter();
1639
        } catch (IOException ioe2) {
1640
          util.debugMessage("Fatal Error: couldn't get response "+
1641
                                                              "output stream.");
1642
        }
1643
        out.println("<?xml version=\"1.0\"?>");
1644
        out.println("<error>");
1645
        out.println("Permission denied for " + action);
1646
        out.println("</error>");
1647
      }
1648
    } else {
1649
      try {
1650
        out = response.getWriter();
1651
      } catch (IOException ioe2) {
1652
        System.err.println("Fatal Error: couldn't get response output stream.");
1653
      }
1654
      out.println("<?xml version=\"1.0\"?>");
1655
      out.println("<error>");
1656
      out.println("Error: action not registered.  Please report this error.");
1657
      out.println("</error>");
1658
    }
1659
  }
1660

    
1661
  /** 
1662
   * Handle the upload action by saving the attached file to disk and 
1663
   * registering it in the Metacat db
1664
   */
1665
  private void handleUploadAction(HttpServletRequest request,
1666
                                  HttpServletResponse response, 
1667
                                  Hashtable params, Hashtable fileList, 
1668
                                  String username, String[] groupnames)
1669
  {
1670
    PrintWriter out = null;
1671
    Connection conn = null;
1672
    String action = null;
1673
    String docid = null;
1674

    
1675
    response.setContentType("text/xml");
1676
    try {
1677
      out = response.getWriter();
1678
    } catch (IOException ioe2) {
1679
      System.err.println("Fatal Error: couldn't get response output stream.");
1680
    }
1681

    
1682
    if (params.containsKey("docid")) {
1683
      docid = (String)params.get("docid");
1684
    }
1685

    
1686
    // Make sure we have a docid and datafile
1687
    if (docid != null && fileList.containsKey("datafile")) {
1688

    
1689
      // Get a reference to the file part of the form
1690
      FilePart filePart = (FilePart)fileList.get("datafile");
1691
      String fileName = filePart.getFileName();
1692
      MetaCatUtil.debugMessage("Uploading filename: " + fileName);
1693

    
1694
      // Check if the right file existed in the uploaded data
1695
      if (fileName != null) {
1696
  
1697
        try {
1698
          // register the file in the database (which generates an exception if
1699
          // the docid is not acceptable or other untoward things happen
1700
          DocumentImpl.registerDocument(fileName, "BIN", docid, username, 1);
1701
    
1702
          // Save the data file to disk using "docid" as the name
1703
          dataDirectory.mkdirs();
1704
          File newFile = new File(dataDirectory, docid);
1705
          long size = filePart.writeTo(newFile);
1706

    
1707
          // set content type and other response header fields first
1708
          out.println("<?xml version=\"1.0\"?>");
1709
          out.println("<success>");
1710
          out.println("<docid>" + docid + "</docid>"); 
1711
          out.println("<size>" + size + "</size>"); 
1712
          out.println("</success>");
1713
    
1714
        } catch (Exception e) {
1715
          out.println("<?xml version=\"1.0\"?>");
1716
          out.println("<error>");
1717
          out.println(e.getMessage()); 
1718
          out.println("</error>");
1719
        }
1720
      } else {
1721
        // the field did not contain a file
1722
        out.println("<?xml version=\"1.0\"?>");
1723
        out.println("<error>");
1724
        out.println("The uploaded data did not contain a valid file."); 
1725
        out.println("</error>");
1726
      }
1727
    } else {
1728
      // Error bcse docid missing or file missing
1729
      out.println("<?xml version=\"1.0\"?>");
1730
      out.println("<error>");
1731
      out.println("The uploaded data did not contain a valid docid " +
1732
                  "or valid file."); 
1733
      out.println("</error>");
1734
    }
1735
  }
1736
}
(29-29/40)