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: berkley $'
10
 *     '$Date: 2001-11-01 14:29:05 -0800 (Thu, 01 Nov 2001) $'
11
 * '$Revision: 867 $'
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 oracle.xml.parser.v2.XSLStylesheet;
68
import oracle.xml.parser.v2.XSLException;
69
import oracle.xml.parser.v2.XMLDocumentFragment;
70
import oracle.xml.parser.v2.XSLProcessor;
71

    
72
import org.xml.sax.SAXException;
73

    
74
/**
75
 * A metadata catalog server implemented as a Java Servlet
76
 *
77
 * <p>Valid parameters are:<br>
78
 * action=query -- query the values of all elements and attributes
79
 *                     and return a result set of nodes<br>
80
 * action=squery -- structured query (see pathquery.dtd)<br>
81
 * action=read -- read any metadata/data file from Metacat and from Internet<br>
82
 * action=insert -- insert an XML document into the database store<br>
83
 * action=update -- update an XML document that is in the database store<br>
84
 * action=delete --  delete an XML document from the database store<br>
85
 * action=validate -- vallidate the xml contained in valtext<br>
86
 * doctype -- document type list returned by the query (publicID)<br>
87
 * qformat=xml -- display resultset from query in XML<br>
88
 * qformat=html -- display resultset from query in HTML<br>
89
 * qformat=zip -- zip resultset from query<br>
90
 * docid=34 -- display the document with the document ID number 34<br>
91
 * doctext -- XML text of the document to load into the database<br>
92
 * acltext -- XML access text for a document to load into the database<br>
93
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog<br>
94
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
95
 * valtext -- XML text to be validated<br>
96
 * abstractpath -- XPath in metadata document to read from<br>
97
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
98
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
99
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
100
 * action=getdataguide -- retrieve a Data Guide<br>
101
 * action=getprincipals -- retrieve a list of principals in XML<br>
102
 * datadoc -- data document name (id)<br>
103
 * <p>
104
 * The particular combination of parameters that are valid for each 
105
 * particular action value is quite specific.  This documentation
106
 * will be reorganized to reflect this information.
107
 */
108
public class MetaCatServlet extends HttpServlet {
109

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

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

    
133
      util = new MetaCatUtil();
134

    
135
      // Get the configuration file information
136
      resultStyleURL = util.getOption("resultStyleURL");
137
      xmlcatalogfile = util.getOption("xmlcatalogfile");
138
      saxparser = util.getOption("saxparser");
139
      datafilepath = util.getOption("datafilepath");
140
      dataDirectory = new File(datafilepath);
141
      servletpath = util.getOption("servletpath");
142
      htmlpath = util.getOption("htmlpath");
143

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

    
157
  /**
158
   * Close all db connections from the pool
159
   */
160
  public void destroy() {
161
    
162
    if (util != null) {
163
        util.closeConnections();
164
    }
165
  }
166

    
167
  /** Handle "GET" method requests from HTTP clients */
168
  public void doGet (HttpServletRequest request, HttpServletResponse response)
169
    throws ServletException, IOException {
170

    
171
    // Process the data and send back the response
172
    handleGetOrPost(request, response);
173
  }
174

    
175
  /** Handle "POST" method requests from HTTP clients */
176
  public void doPost( HttpServletRequest request, HttpServletResponse response)
177
    throws ServletException, IOException {
178

    
179
    // Process the data and send back the response
180
    handleGetOrPost(request, response);
181
  }
182

    
183
  /**
184
   * Control servlet response depending on the action parameter specified
185
   */
186
  private void handleGetOrPost(HttpServletRequest request, 
187
                               HttpServletResponse response) 
188
                               throws ServletException, IOException 
189
  {
190

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

    
208
    // Deal with forms that are encoded as "multipart/form-data" differently
209
    // this is mainly used for uploading non-xml files using that may be binary
210
    String ctype = request.getContentType();
211
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
212
      handleMultipartForm(request, response);
213
    } else {
214
      // This probably means the data is "application/x-www-url-encoded", we hope :-)
215
  
216
      String name = null;
217
      String[] value = null;
218
      String[] docid = new String[3];
219
      Hashtable params = new Hashtable();
220
      Enumeration paramlist = request.getParameterNames();
221
      while (paramlist.hasMoreElements()) {
222
        name = (String)paramlist.nextElement();
223
        value = request.getParameterValues(name);
224
  
225
        // Decode the docid and mouse click information
226
        if (name.endsWith(".y")) {
227
          docid[0] = name.substring(0,name.length()-2);
228
          params.put("docid", docid);
229
          name = "ypos";
230
        }
231
        if (name.endsWith(".x")) {
232
          name = "xpos";
233
        } 
234
  
235
        params.put(name,value); 
236
      }  
237
      
238
      //if the user clicked on the input images, decode which image
239
      //was clicked then set the action.
240
      String action = ((String[])params.get("action"))[0];  
241
      util.debugMessage("Line 213: Action is: " + action);
242
  
243
      // This block handles session management for the servlet
244
      // by looking up the current session information for all actions
245
      // other than "login" and "logout"
246
      String username = null;
247
      String password = null;
248
      String[] groupnames = null;
249
      String sess_id = null;
250
  
251
      // handle login action
252
      if (action.equals("login")) {
253
  
254
        handleLoginAction(response.getWriter(), params, request, response);
255
  
256
      // handle logout action  
257
      } else if (action.equals("logout")) {
258
  
259
        handleLogoutAction(response.getWriter(), params, request, response);
260
  
261
      // aware of session expiration on every request  
262
      } else {   
263
  
264
        HttpSession sess = request.getSession(true);
265
        if (sess.isNew()) { 
266
          // session expired or has not been stored b/w user requests
267
          username = "public";
268
          sess.setAttribute("username", username);
269
        } else {
270
          username = (String)sess.getAttribute("username");
271
          password = (String)sess.getAttribute("password");
272
          groupnames = (String[])sess.getAttribute("groupnames");
273
          try {
274
            sess_id = (String)sess.getId();
275
          } catch(IllegalStateException ise) {
276
            System.out.println("error in handleGetOrPost: this shouldn't " +
277
                               "happen: the session should be valid: " + 
278
                               ise.getMessage());
279
          }
280
        }  
281
      }    
282
  
283
      // Now that we know the session is valid, we can delegate the request
284
      // to a particular action handler
285
      if(action.equals("query")) {
286
        handleQuery(response.getWriter(),params,response,username,groupnames);
287
      } else if(action.equals("squery")) {
288
        if(params.containsKey("query")) {
289
          handleSQuery(response.getWriter(),params,response,username,groupnames); 
290
        } else {
291
          PrintWriter out = response.getWriter();
292
          out.println("Illegal action squery without \"query\" parameter");
293
        }
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
  // READ SECTION
651
  /** 
652
   * Handle the "read" request of metadata/data files from Metacat
653
   * or any files from Internet;
654
   * transformed metadata XML document into HTML presentation if requested;
655
   * zip files when more than one were requested.
656
   *
657
   * @param params the Hashtable of HTTP request parameters
658
   * @param response the HTTP response object linked to the client
659
   * @param user the username sent the request
660
   * @param groups the user's groupnames
661
   */
662
  private void handleReadAction(Hashtable params, HttpServletResponse response,
663
                                String user, String[] groups) 
664
  {
665
    ServletOutputStream out = null;
666
    ZipOutputStream zout = null;
667
    
668
    try {
669
      String[] docs = new String[0];
670
      String docid = "";
671
      String qformat = "";
672
      String abstrpath = null;
673
      boolean zip = false;
674
      // read the params
675
      if (params.containsKey("docid")) {
676
        docs = (String[])params.get("docid");
677
      }
678
      if (params.containsKey("qformat")) {
679
        qformat = ((String[])params.get("qformat"))[0];
680
      }
681
      if (params.containsKey("abstractpath")) {
682
        abstrpath = ((String[])params.get("abstractpath"))[0];
683
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
684
          viewAbstract(response, abstrpath, docs[0]);
685
          return;
686
        }
687
      }
688
      if ( (docs.length > 1) || qformat.equals("zip") ) {
689
        zip = true;
690
        out = response.getOutputStream();
691
        response.setContentType("application/zip"); //MIME type
692
        zout = new ZipOutputStream(out);
693
      }
694
      // go through the list of docs to read
695
      for (int i=0; i < docs.length; i++ ) {
696
        try {
697

    
698
          URL murl = new URL(docs[i]);
699
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
700
          // case docid="http://.../?docid=aaa" 
701
          // or docid="metacat://.../?docid=bbb"
702
          if (murlQueryStr.containsKey("docid")) {
703
            // get only docid, eliminate the rest
704
            docid = (String)murlQueryStr.get("docid");
705
            if ( zip ) {
706
              addDocToZip(docid, zout);
707
            } else {
708
              readFromMetacat(response, docid, qformat, abstrpath,
709
                              user, groups, zip, zout);
710
            }
711

    
712
          // case docid="http://.../filename"
713
          } else {
714
            docid = docs[i];
715
            if ( zip ) {
716
              addDocToZip(docid, zout);
717
            } else {
718
              readFromURLConnection(response, docid);
719
            }
720
          }
721

    
722
        // case docid="ccc"
723
        } catch (MalformedURLException mue) {
724
          docid = docs[i];
725
          if ( zip ) {
726
            addDocToZip(docid, zout);
727
          } else {
728
            readFromMetacat(response, docid, qformat, abstrpath,
729
                            user, groups, zip, zout);
730
          }
731
        }
732
        
733
      } /* end for */
734
      
735
      if ( zip ) {
736
        zout.finish(); //terminate the zip file
737
        zout.close();  //close the zip stream
738
      }
739
      
740
        /*
741
    } catch (ClassNotFoundException cnfe) {
742
    } catch (IOException ioe1) {
743
    } catch (SQLException se) {
744
    } catch (McdbException mcdbe) {
745
    } catch (Exception e) {
746
      */
747
    } catch (Exception e) {
748
      try {
749
        response.setContentType("text/xml"); //MIME type
750
        //PrintWriter pw = response.getWriter();
751
        if (out != null) {
752
            PrintWriter pw = new PrintWriter(out);
753
            pw.println("<?xml version=\"1.0\"?>");
754
            pw.println("<error>");
755
            pw.println(e.getMessage());
756
            pw.println("</error>");
757
            pw.close();
758
        }
759
        //if ( out != null ) { out.close(); }
760
        if ( zout != null ) { zout.close(); }
761
      } catch (IOException ioe) {
762
        System.out.println("Problem with the servlet output " +
763
                           "in MetacatServlet.handleReadAction: " +
764
                           ioe.getMessage());
765
        ioe.printStackTrace(System.out);
766
        
767
      }
768

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

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

    
889
    // this is http url
890
    URL url = new URL(docid);
891
    BufferedInputStream bis = null;
892
    try {
893
      bis = new BufferedInputStream(url.openStream());
894
      byte[] buf = new byte[4 * 1024]; // 4K buffer
895
      int b = bis.read(buf);
896
      while (b != -1) {
897
        out.write(buf, 0, b);
898
        b = bis.read(buf);
899
      }
900
    } finally {
901
      if (bis != null) bis.close();
902
    }
903
    
904
  }
905
  
906
  // read file/doc and write to ZipOutputStream
907
  private void addDocToZip(String docid, ZipOutputStream zout)
908
               throws ClassNotFoundException, IOException, SQLException, 
909
                      McdbException, Exception
910
  {
911
    byte[] bytestring = null;
912
    ZipEntry zentry = null;
913

    
914
    try {
915
      URL url = new URL(docid);
916

    
917
      // this http url; read from URLConnection; add to zip
918
      zentry = new ZipEntry(docid);
919
      zout.putNextEntry(zentry);
920
      BufferedInputStream bis = null;
921
      try {
922
        bis = new BufferedInputStream(url.openStream());
923
        byte[] buf = new byte[4 * 1024]; // 4K buffer
924
        int b = bis.read(buf);
925
        while(b != -1) {
926
          zout.write(buf, 0, b);
927
          b = bis.read(buf);
928
        }
929
      } finally {
930
        if (bis != null) bis.close();
931
      }
932
      zout.closeEntry();
933

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

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

    
1003
    } finally {
1004
      util.returnConnection(conn);
1005
    }
1006
  }
1007
  // END OF READ SECTION
1008
    
1009
  // INSERT/UPDATE SECTION
1010
  /** 
1011
   * Handle the database putdocument request and write an XML document 
1012
   * to the database connection
1013
   */
1014
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
1015
               HttpServletResponse response, String user, String[] groups) {
1016

    
1017
    Connection conn = null;
1018

    
1019
    try {
1020
      // Get the document indicated
1021
      String[] doctext = (String[])params.get("doctext");
1022

    
1023
      String pub = null;
1024
      if (params.containsKey("public")) {
1025
        pub = ((String[])params.get("public"))[0];
1026
      }
1027

    
1028
      StringReader dtd = null;
1029
      if (params.containsKey("dtdtext")) {
1030
        String[] dtdtext = (String[])params.get("dtdtext");
1031
        try {
1032
          if ( !dtdtext[0].equals("") ) {
1033
            dtd = new StringReader(dtdtext[0]);
1034
          }
1035
        } catch (NullPointerException npe) {}
1036
      }
1037
      
1038
      StringReader xml = null;
1039
      boolean validate = false;
1040
      try {
1041
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... > 
1042
        // in order to decide whether to use validation parser
1043
        validate = validateXML(doctext[0]);
1044
        xml = new StringReader(doctext[0]);
1045

    
1046
        String[] action = (String[])params.get("action");
1047
        String[] docid = (String[])params.get("docid");
1048
        String newdocid = null;
1049

    
1050
        String doAction = null;
1051
        if (action[0].equals("insert")) {
1052
          doAction = "INSERT";
1053
        } else if (action[0].equals("update")) {
1054
          doAction = "UPDATE";
1055
        }
1056

    
1057
        try {
1058
          // get a connection from the pool
1059
          conn = util.getConnection();
1060

    
1061
          // write the document to the database
1062
          try {
1063
            String accNumber = docid[0];
1064
            if (accNumber.equals("")) {
1065
              accNumber = null;
1066
            }
1067
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1068
                                          accNumber, user, groups, validate);
1069
          } catch (NullPointerException npe) {
1070
            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
1071
                                          null, user, groups, validate);
1072
          }
1073
        } finally {
1074
          util.returnConnection(conn);
1075
        }    
1076

    
1077
        // set content type and other response header fields first
1078
        response.setContentType("text/xml");
1079
        out.println("<?xml version=\"1.0\"?>");
1080
        out.println("<success>");
1081
        out.println("<docid>" + newdocid + "</docid>"); 
1082
        out.println("</success>");
1083

    
1084
      } catch (NullPointerException npe) {
1085
        response.setContentType("text/xml");
1086
        out.println("<?xml version=\"1.0\"?>");
1087
        out.println("<error>");
1088
        out.println(npe.getMessage()); 
1089
        out.println("</error>");
1090
      }
1091
    } catch (Exception e) {
1092
      response.setContentType("text/xml");
1093
      out.println("<?xml version=\"1.0\"?>");
1094
      out.println("<error>");
1095
      out.println(e.getMessage()); 
1096
      if (e instanceof SAXException) {
1097
        Exception e2 = ((SAXException)e).getException();
1098
        out.println("<error>");
1099
        try
1100
        {
1101
          out.println(e2.getMessage());
1102
        }
1103
        catch(NullPointerException npe)
1104
        {
1105
          out.println(e.getMessage());
1106
        }
1107
        out.println("</error>");
1108
      }
1109
      //e.printStackTrace(out);
1110
      out.println("</error>");
1111
    }
1112
  }
1113

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

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

    
1155
    // close the stream
1156
    xmlreader.close();
1157

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

    
1169
System.out.println("Validation is " + validate);
1170
    return validate;
1171
  }
1172
  // END OF INSERT/UPDATE SECTION
1173

    
1174
  // DELETE SECTION
1175
  /** 
1176
   * Handle the database delete request and delete an XML document 
1177
   * from the database connection
1178
   */
1179
  private void handleDeleteAction(PrintWriter out, Hashtable params, 
1180
               HttpServletResponse response, String user, String[] groups) {
1181

    
1182
    String[] docid = (String[])params.get("docid");
1183
    Connection conn = null;
1184

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

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

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

    
1239
        // get a connection from the pool
1240
        conn = util.getConnection();
1241

    
1242
        // Get the document indicated from the db
1243
        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
1244
        valtext = xmldoc.toString();
1245

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

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

    
1266
      // set content type and other response header fields first
1267
      response.setContentType("text/xml");
1268
      out.println(valobj.returnErrors());
1269

    
1270
    } catch (NullPointerException npe2) {
1271
      // set content type and other response header fields first
1272
      response.setContentType("text/xml");
1273
      out.println("<error>Error validating document.</error>"); 
1274
    } catch (Exception e) {
1275
      response.setContentType("text/html");
1276
      out.println(e.getMessage()); 
1277
    } finally {
1278
      util.returnConnection(conn);
1279
    }  
1280
  }
1281
  // END OF VALIDATE SECTION
1282
 
1283
  // OTHER ACTION HANDLERS
1284
  
1285
  /** 
1286
   * Handle "getaccesscontrol" action.
1287
   * Read Access Control List from db connection in XML format
1288
   */
1289
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params, 
1290
                                       HttpServletResponse response, 
1291
                                       String username, String[] groupnames) {
1292

    
1293
    Connection conn = null;
1294
    String docid = ((String[])params.get("docid"))[0];
1295
    
1296
    try {
1297

    
1298
        // get connection from the pool
1299
        conn = util.getConnection();
1300
        AccessControlList aclobj = new AccessControlList(conn);
1301
        String acltext = aclobj.getACL(docid, username, groupnames);
1302
        out.println(acltext);
1303

    
1304
    } catch (Exception e) {
1305
      out.println("<?xml version=\"1.0\"?>");
1306
      out.println("<error>");
1307
      out.println(e.getMessage());
1308
      out.println("</error>");
1309
    } finally {
1310
      util.returnConnection(conn);
1311
    }  
1312
    
1313
  }
1314

    
1315
  /** 
1316
   * Handle the "getprincipals" action.
1317
   * Read all principals from authentication scheme in XML format
1318
   */
1319
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1320
                                         String password) {
1321

    
1322
    Connection conn = null;
1323

    
1324
    try {
1325

    
1326
        // get connection from the pool
1327
        AuthSession auth = new AuthSession();
1328
        String principals = auth.getPrincipals(user, password);
1329
        out.println(principals);
1330

    
1331
    } catch (Exception e) {
1332
      out.println("<?xml version=\"1.0\"?>");
1333
      out.println("<error>");
1334
      out.println(e.getMessage());
1335
      out.println("</error>");
1336
    } finally {
1337
      util.returnConnection(conn);
1338
    }  
1339
    
1340
  }
1341

    
1342
  /** 
1343
   * Handle "getdoctypes" action.
1344
   * Read all doctypes from db connection in XML format
1345
   */
1346
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
1347
                                       HttpServletResponse response) {
1348

    
1349
    Connection conn = null;
1350
    
1351
    try {
1352

    
1353
        // get connection from the pool
1354
        conn = util.getConnection();
1355
        DBUtil dbutil = new DBUtil(conn);
1356
        String doctypes = dbutil.readDoctypes();
1357
        out.println(doctypes);
1358

    
1359
    } catch (Exception e) {
1360
      out.println("<?xml version=\"1.0\"?>");
1361
      out.println("<error>");
1362
      out.println(e.getMessage());
1363
      out.println("</error>");
1364
    } finally {
1365
      util.returnConnection(conn);
1366
    }  
1367
    
1368
  }
1369

    
1370
  /** 
1371
   * Handle the "getdtdschema" action.
1372
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1373
   */
1374
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1375
                                        HttpServletResponse response) {
1376

    
1377
    Connection conn = null;
1378
    String doctype = null;
1379
    String[] doctypeArr = (String[])params.get("doctype");
1380

    
1381
    // get only the first doctype specified in the list of doctypes
1382
    // it could be done for all doctypes in that list
1383
    if (doctypeArr != null) {
1384
        doctype = ((String[])params.get("doctype"))[0]; 
1385
    }
1386

    
1387
    try {
1388

    
1389
        // get connection from the pool
1390
        conn = util.getConnection();
1391
        DBUtil dbutil = new DBUtil(conn);
1392
        String dtdschema = dbutil.readDTDSchema(doctype);
1393
        out.println(dtdschema);
1394

    
1395
    } catch (Exception e) {
1396
      out.println("<?xml version=\"1.0\"?>");
1397
      out.println("<error>");
1398
      out.println(e.getMessage());
1399
      out.println("</error>");
1400
    } finally {
1401
      util.returnConnection(conn);
1402
    }  
1403
    
1404
  }
1405

    
1406
  /** 
1407
   * Handle the "getdataguide" action.
1408
   * Read Data Guide for a given doctype from db connection in XML format
1409
   */
1410
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
1411
                                        HttpServletResponse response) {
1412

    
1413
    Connection conn = null;
1414
    String doctype = null;
1415
    String[] doctypeArr = (String[])params.get("doctype");
1416

    
1417
    // get only the first doctype specified in the list of doctypes
1418
    // it could be done for all doctypes in that list
1419
    if (doctypeArr != null) {
1420
        doctype = ((String[])params.get("doctype"))[0]; 
1421
    }
1422

    
1423
    try {
1424

    
1425
        // get connection from the pool
1426
        conn = util.getConnection();
1427
        DBUtil dbutil = new DBUtil(conn);
1428
        String dataguide = dbutil.readDataGuide(doctype);
1429
        out.println(dataguide);
1430

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

    
1442
  /** 
1443
   * Handle the "getlastdocid" action.
1444
   * Get the latest docid with rev number from db connection in XML format
1445
   */
1446
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params, 
1447
                                        HttpServletResponse response) {
1448

    
1449
    Connection conn = null;
1450
    String scope = ((String[])params.get("scope"))[0];
1451
    if (scope == null) {
1452
        scope = ((String[])params.get("username"))[0];
1453
    }
1454

    
1455
    try {
1456

    
1457
        // get connection from the pool
1458
        conn = util.getConnection();
1459
        DBUtil dbutil = new DBUtil(conn);
1460
        String lastDocid = dbutil.getMaxDocid(scope);
1461
        out.println("<?xml version=\"1.0\"?>");
1462
        out.println("<lastDocid>");
1463
        out.println("  <scope>" + scope + "</scope>");
1464
        out.println("  <docid>" + lastDocid + "</docid>");
1465
        out.println("</lastDocid>");
1466

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

    
1478
  /** 
1479
   * Handle documents passed to metacat that are encoded using the 
1480
   * "multipart/form-data" mime type.  This is typically used for uploading
1481
   * data files which may be binary and large.
1482
   */
1483
  private void handleMultipartForm(HttpServletRequest request,
1484
                                   HttpServletResponse response) 
1485
  {
1486
    PrintWriter out = null;
1487
    String action = null;
1488

    
1489
    // Parse the multipart form, and save the parameters in a Hashtable and
1490
    // save the FileParts in a hashtable
1491

    
1492
    Hashtable params = new Hashtable();
1493
    Hashtable fileList = new Hashtable();
1494

    
1495
    try {
1496
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
1497
      MultipartParser mp = new MultipartParser(request, 200*1024*1024); // 200MB
1498
      Part part;
1499
      while ((part = mp.readNextPart()) != null) {
1500
        String name = part.getName();
1501

    
1502
        if (part.isParam()) {
1503
          // it's a parameter part
1504
          ParamPart paramPart = (ParamPart) part;
1505
          String value = paramPart.getStringValue();
1506
          params.put(name, value);
1507
          if (name.equals("action")) {
1508
            action = value;
1509
          }
1510
        } else if (part.isFile()) {
1511
          // it's a file part
1512
          FilePart filePart = (FilePart) part;
1513
          fileList.put(name, filePart);
1514

    
1515
          // Stop once the first file part is found, otherwise going onto the
1516
          // next part prevents access to the file contents.  So...for upload
1517
          // to work, the datafile must be the last part
1518
          break;
1519
        }
1520
      }
1521
    } catch (IOException ioe) {
1522
      try {
1523
        out = response.getWriter();
1524
      } catch (IOException ioe2) {
1525
        System.err.println("Fatal Error: couldn't get response output stream.");
1526
      }
1527
      out.println("<?xml version=\"1.0\"?>");
1528
      out.println("<error>");
1529
      out.println("Error: problem reading multipart data.");
1530
      out.println("</error>");
1531
    }
1532

    
1533
    // Get the session information
1534
    String username = null;
1535
    String password = null;
1536
    String[] groupnames = null;
1537
    String sess_id = null;
1538

    
1539
    // be aware of session expiration on every request  
1540
    HttpSession sess = request.getSession(true);
1541
    if (sess.isNew()) {
1542
      // session expired or has not been stored b/w user requests
1543
      username = "public";
1544
      sess.setAttribute("username", username);
1545
    } else {
1546
      username = (String)sess.getAttribute("username");
1547
      password = (String)sess.getAttribute("password");
1548
      groupnames = (String[])sess.getAttribute("groupnames");
1549
      try {
1550
        sess_id = (String)sess.getId();
1551
      } catch(IllegalStateException ise) {
1552
        System.out.println("error in  handleMultipartForm: this shouldn't " +
1553
                           "happen: the session should be valid: " + 
1554
                           ise.getMessage());
1555
      }
1556
    }  
1557

    
1558
    if ( action.equals("upload")) {
1559
      if (username != null &&  !username.equals("public")) {
1560
        handleUploadAction(request, response, params, fileList, 
1561
                           username, groupnames);
1562
      } else {
1563
        try {
1564
          out = response.getWriter();
1565
        } catch (IOException ioe2) {
1566
          System.err.println("Fatal Error: couldn't get response output stream.");
1567
        }
1568
        out.println("<?xml version=\"1.0\"?>");
1569
        out.println("<error>");
1570
        out.println("Permission denied for " + action);
1571
        out.println("</error>");
1572
      }
1573
    } else {
1574
      try {
1575
        out = response.getWriter();
1576
      } catch (IOException ioe2) {
1577
        System.err.println("Fatal Error: couldn't get response output stream.");
1578
      }
1579
      out.println("<?xml version=\"1.0\"?>");
1580
      out.println("<error>");
1581
      out.println("Error: action not registered.  Please report this error.");
1582
      out.println("</error>");
1583
    }
1584
  }
1585

    
1586
  /** 
1587
   * Handle the upload action by saving the attached file to disk and 
1588
   * registering it in the Metacat db
1589
   */
1590
  private void handleUploadAction(HttpServletRequest request,
1591
                                  HttpServletResponse response, 
1592
                                  Hashtable params, Hashtable fileList, 
1593
                                  String username, String[] groupnames)
1594
  {
1595
    PrintWriter out = null;
1596
    Connection conn = null;
1597
    String action = null;
1598
    String docid = null;
1599

    
1600
    response.setContentType("text/xml");
1601
    try {
1602
      out = response.getWriter();
1603
    } catch (IOException ioe2) {
1604
      System.err.println("Fatal Error: couldn't get response output stream.");
1605
    }
1606

    
1607
    if (params.containsKey("docid")) {
1608
      docid = (String)params.get("docid");
1609
    }
1610

    
1611
    // Make sure we have a docid and datafile
1612
    if (docid != null && fileList.containsKey("datafile")) {
1613

    
1614
      // Get a reference to the file part of the form
1615
      FilePart filePart = (FilePart)fileList.get("datafile");
1616
      String fileName = filePart.getFileName();
1617
      MetaCatUtil.debugMessage("Uploading filename: " + fileName);
1618

    
1619
      // Check if the right file existed in the uploaded data
1620
      if (fileName != null) {
1621
  
1622
        try {
1623
          // register the file in the database (which generates an exception if
1624
          // the docid is not acceptable or other untoward things happen
1625
          DocumentImpl.registerDocument(fileName, "BIN", docid, username, 1);
1626
    
1627
          // Save the data file to disk using "docid" as the name
1628
          dataDirectory.mkdirs();
1629
          File newFile = new File(dataDirectory, docid);
1630
          long size = filePart.writeTo(newFile);
1631

    
1632
          // set content type and other response header fields first
1633
          out.println("<?xml version=\"1.0\"?>");
1634
          out.println("<success>");
1635
          out.println("<docid>" + docid + "</docid>"); 
1636
          out.println("<size>" + size + "</size>"); 
1637
          out.println("</success>");
1638
    
1639
        } catch (Exception e) {
1640
          out.println("<?xml version=\"1.0\"?>");
1641
          out.println("<error>");
1642
          out.println(e.getMessage()); 
1643
          out.println("</error>");
1644
        }
1645
      } else {
1646
        // the field did not contain a file
1647
        out.println("<?xml version=\"1.0\"?>");
1648
        out.println("<error>");
1649
        out.println("The uploaded data did not contain a valid file."); 
1650
        out.println("</error>");
1651
      }
1652
    } else {
1653
      // Error bcse docid missing or file missing
1654
      out.println("<?xml version=\"1.0\"?>");
1655
      out.println("<error>");
1656
      out.println("The uploaded data did not contain a valid docid " +
1657
                  "or valid file."); 
1658
      out.println("</error>");
1659
    }
1660
  }
1661
}
(29-29/40)