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: 2003-03-19 14:58:05 -0800 (Wed, 19 Mar 2003) $'
11
 * '$Revision: 1490 $'
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.util.Vector;
47
import java.net.URL;
48
import java.net.MalformedURLException;
49
import java.sql.PreparedStatement;
50
import java.sql.ResultSet;
51
import java.sql.Connection;
52
import java.sql.SQLException;
53
import java.lang.reflect.*;
54
import java.net.*;
55
import java.util.zip.*;
56

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

    
68
import org.ecoinformatics.eml.EMLParser;
69

    
70
import org.xml.sax.SAXException;
71

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

    
109
  private ServletConfig config = null;
110
  private ServletContext context = null;
111
  private String resultStyleURL = null;
112
  private String xmlcatalogfile = null;
113
  private String saxparser = null;
114
  private String datafilepath = null;
115
  private File dataDirectory = null;
116
  private String servletpath = null;
117
  private String htmlpath = null;
118
  private PropertyResourceBundle options = null;
119
  private MetaCatUtil util = null;
120
  private DBConnectionPool connPool = null;
121
  private static final String PROLOG = "<?xml version=\"1.0\"?>";
122
  private static final String SUCCESS = "<success>";
123
  private static final String SUCCESSCLOSE = "</success>";
124
  private static final String ERROR = "<error>";
125
  private static final String ERRORCLOSE = "</error>";
126
  public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
127
  public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
128
  public static final String EML2KEYWORD ="<eml:eml";
129

    
130
  /**
131
   * Initialize the servlet by creating appropriate database connections
132
   */
133
  public void init( ServletConfig config ) throws ServletException {
134
    try {
135
      super.init( config );
136
      this.config = config;
137
      this.context = config.getServletContext();
138
      System.out.println("MetaCatServlet Initialize");
139

    
140
      util = new MetaCatUtil();
141

    
142
      //initial DBConnection pool
143
      connPool = DBConnectionPool.getInstance();
144

    
145
      // Get the configuration file information
146
      resultStyleURL = util.getOption("resultStyleURL");
147
      xmlcatalogfile = util.getOption("xmlcatalogfile");
148
      saxparser = util.getOption("saxparser");
149
      datafilepath = util.getOption("datafilepath");
150
      dataDirectory = new File(datafilepath);
151
      servletpath = util.getOption("servletpath");
152
      htmlpath = util.getOption("htmlpath");
153

    
154

    
155
    } catch ( ServletException ex ) {
156
      throw ex;
157
    } catch (SQLException e) {
158
      MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
159
                                          +e.getMessage(), 20);
160
    }
161
  }
162

    
163
  /**
164
   * Close all db connections from the pool
165
   */
166
  public void destroy() {
167
      // Close all db connection
168
      System.out.println("Destroying MetacatServlet");
169
      connPool.release();
170
  }
171

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

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

    
180
  /** Handle "POST" method requests from HTTP clients */
181
  public void doPost( HttpServletRequest request, HttpServletResponse response)
182
    throws ServletException, IOException {
183

    
184
    // Process the data and send back the response
185
    handleGetOrPost(request, response);
186
  }
187

    
188
  /**
189
   * Control servlet response depending on the action parameter specified
190
   */
191
  private void handleGetOrPost(HttpServletRequest request,
192
                               HttpServletResponse response)
193
                               throws ServletException, IOException
194
  {
195

    
196
    if ( util == null ) {
197
        util = new MetaCatUtil();
198
    }
199
    /*MetaCatUtil.debugMessage("Connection pool size: "
200
                                     +connPool.getSizeOfDBConnectionPool(),10);
201
    MetaCatUtil.debugMessage("Free DBConnection number: "
202
                                  +connPool.getFreeDBConnectionNumber(), 10);*/
203
    //If all DBConnection in the pool are free and DBConnection pool
204
    //size is greater than initial value, shrink the connection pool
205
    //size to initial value
206
    DBConnectionPool.shrinkDBConnectionPoolSize();
207

    
208
    //Debug message to print out the method which have a busy DBConnection
209
    connPool.printMethodNameHavingBusyDBConnection();
210

    
211
    String ctype = request.getContentType();
212
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
213
      handleMultipartForm(request, response);
214
    } else {
215

    
216

    
217
      String name = null;
218
      String[] value = null;
219
      String[] docid = new String[3];
220
      Hashtable params = new Hashtable();
221
      Enumeration paramlist = request.getParameterNames();
222

    
223

    
224
      while (paramlist.hasMoreElements()) {
225

    
226
        name = (String)paramlist.nextElement();
227
        value = request.getParameterValues(name);
228

    
229
        // Decode the docid and mouse click information
230
        if (name.endsWith(".y")) {
231
          docid[0] = name.substring(0,name.length()-2);
232
          params.put("docid", docid);
233
          name = "ypos";
234
        }
235
        if (name.endsWith(".x")) {
236
          name = "xpos";
237
        }
238

    
239
        params.put(name,value);
240
      }
241

    
242

    
243
      //handle param is emptpy
244
      if (params.isEmpty() || params == null)
245
      {
246
        return;
247
      }
248
      //if the user clicked on the input images, decode which image
249
      //was clicked then set the action.
250
      String action = ((String[])params.get("action"))[0];
251
      util.debugMessage("Line 230: Action is: " + action, 1);
252

    
253
      // This block handles session management for the servlet
254
      // by looking up the current session information for all actions
255
      // other than "login" and "logout"
256
      String username = null;
257
      String password = null;
258
      String[] groupnames = null;
259
      String sess_id = null;
260

    
261
      // handle login action
262
      if (action.equals("login")) {
263
        PrintWriter out = response.getWriter();
264
        handleLoginAction(out, params, request, response);
265
        out.close();
266

    
267
      // handle logout action
268
      } else if (action.equals("logout")) {
269
        PrintWriter out = response.getWriter();
270
        handleLogoutAction(out, params, request, response);
271
        out.close();
272

    
273
      // handle shrink DBConnection request
274
      } else if (action.equals("shrink")) {
275
        PrintWriter out = response.getWriter();
276
        boolean success = false;
277
        //If all DBConnection in the pool are free and DBConnection pool
278
        //size is greater than initial value, shrink the connection pool
279
        //size to initial value
280
        success = DBConnectionPool.shrinkConnectionPoolSize();
281
        if (success)
282
        {
283
          //if successfully shrink the pool size to initial value
284
          out.println("DBConnection Pool shrink successfully");
285
        }//if
286
        else
287
        {
288
          out.println("DBConnection pool couldn't shrink successfully");
289
        }
290
       //close out put
291
        out.close();
292

    
293
      // aware of session expiration on every request
294
      } else {
295

    
296
        HttpSession sess = request.getSession(true);
297
        if (sess.isNew()) {
298
          // session expired or has not been stored b/w user requests
299
          username = "public";
300
          sess.setAttribute("username", username);
301
        } else {
302
          username = (String)sess.getAttribute("username");
303
          password = (String)sess.getAttribute("password");
304
          groupnames = (String[])sess.getAttribute("groupnames");
305
          try {
306
            sess_id = (String)sess.getId();
307
          } catch(IllegalStateException ise) {
308
            System.out.println("error in handleGetOrPost: this shouldn't " +
309
                               "happen: the session should be valid: " +
310
                               ise.getMessage());
311
          }
312
        }
313
      }
314

    
315
       // Now that we know the session is valid, we can delegate the request
316
      // to a particular action handler
317
      if(action.equals("query")) {
318
        PrintWriter out = response.getWriter();
319
        handleQuery(out,params,response,username,groupnames);
320
        out.close();
321
      } else if(action.equals("squery")) {
322
        PrintWriter out = response.getWriter();
323
        if(params.containsKey("query")) {
324
         handleSQuery(out, params,response,username,groupnames);
325
         out.close();
326
        } else {
327
          out.println("Illegal action squery without \"query\" parameter");
328
          out.close();
329
        }
330
      } else if (action.equals("export")) {
331

    
332
        handleExportAction(params, response, username, groupnames, password);
333
      } else if (action.equals("read")) {
334
        handleReadAction(params, response, username,password, groupnames);
335
      } else if (action.equals("readinlinedata")) {
336
        handleReadInlineDataAction(params, response, username, 
337
                                   password, groupnames);
338
      } else if (action.equals("insert") || action.equals("update")) {
339
        PrintWriter out = response.getWriter();
340
        if ( (username != null) &&  !username.equals("public") ) {
341
          handleInsertOrUpdateAction(out,params,username,groupnames);
342
        } else {
343
          out.println("Permission denied for user"+username +" " + action);
344
        }
345
        out.close();
346
      } else if (action.equals("delete")) {
347
        PrintWriter out = response.getWriter();
348
        if ( (username != null) &&  !username.equals("public") ) {
349
          handleDeleteAction(out, params, response, username, groupnames);
350
        } else {
351
          out.println("Permission denied for " + action);
352
        }
353
        out.close();
354
      } else if (action.equals("validate")) {
355
        PrintWriter out = response.getWriter();
356
        handleValidateAction(out, params);
357
        out.close();
358
      } else if (action.equals("setaccess")) {
359
         PrintWriter out = response.getWriter();
360
         handleSetAccessAction(out, params, username);
361
        out.close();
362
      } else if (action.equals("getaccesscontrol")) {
363
        PrintWriter out = response.getWriter();
364
        handleGetAccessControlAction(out,params,response,username,groupnames);
365
        out.close();
366
      } else if (action.equals("getprincipals")) {
367
        PrintWriter out = response.getWriter();
368
        handleGetPrincipalsAction(out, username, password);
369
        out.close();
370
      } else if (action.equals("getdoctypes")) {
371
        PrintWriter out = response.getWriter();
372
        handleGetDoctypesAction(out, params, response);
373
        out.close();
374
      } else if (action.equals("getdtdschema")) {
375
        PrintWriter out = response.getWriter();
376
        handleGetDTDSchemaAction(out, params, response);
377
        out.close();
378
      } else if (action.equals("getdataguide")) {
379
        PrintWriter out = response.getWriter();
380
        handleGetDataGuideAction(out, params, response);
381
        out.close();
382
      } else if (action.equals("getlastdocid")) {
383
        PrintWriter out = response.getWriter();
384
        handleGetMaxDocidAction(out, params, response);
385
        out.close();
386
      } else if (action.equals("getrevisionanddoctype")) {
387
        PrintWriter out = response.getWriter();
388
        handleGetRevisionAndDocTypeAction(out, params);
389
        out.close();
390
      } else if (action.equals("login") || action.equals("logout")) {
391
      } else if (action.equals("protocoltest")) {
392
        String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
393
        try {
394
          testURL = ((String[])params.get("url"))[0];
395
        } catch (Throwable t) {
396
        }
397
        String phandler = System.getProperty("java.protocol.handler.pkgs");
398
        response.setContentType("text/html");
399
        PrintWriter out = response.getWriter();
400
        out.println("<body bgcolor=\"white\">");
401
        out.println("<p>Handler property: <code>" + phandler + "</code></p>");
402
        out.println("<p>Starting test for:<br>");
403
        out.println("    " + testURL + "</p>");
404
        try {
405
          URL u = new URL(testURL);
406
          out.println("<pre>");
407
          out.println("Protocol: " + u.getProtocol());
408
          out.println("    Host: " + u.getHost());
409
          out.println("    Port: " + u.getPort());
410
          out.println("    Path: " + u.getPath());
411
          out.println("     Ref: " + u.getRef());
412
          String pquery = u.getQuery();
413
          out.println("   Query: " + pquery);
414
          out.println("  Params: ");
415
          if (pquery != null) {
416
            Hashtable qparams = util.parseQuery(u.getQuery());
417
            for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
418
              String pname = (String)en.nextElement();
419
              String pvalue = (String)qparams.get(pname);
420
              out.println("    " + pname + ": " + pvalue);
421
            }
422
          }
423
          out.println("</pre>");
424
          out.println("</body>");
425
          out.close();
426
        } catch (MalformedURLException mue) {
427
          System.out.println("bad url from MetacatServlet.handleGetOrPost");
428
          out.println(mue.getMessage());
429
          mue.printStackTrace(out);
430
          out.close();
431
        }
432
      } else {
433
        PrintWriter out = response.getWriter();
434
        out.println("<?xml version=\"1.0\"?>");
435
        out.println("<error>");
436
        out.println("Error: action not registered.  Please report this error.");
437
        out.println("</error>");
438
        out.close();
439
      }
440

    
441
      //util.closeConnections();
442
      // Close the stream to the client
443
      //out.close();
444
    }
445
  }
446

    
447
  // LOGIN & LOGOUT SECTION
448
  /**
449
   * Handle the login request. Create a new session object.
450
   * Do user authentication through the session.
451
   */
452
  private void handleLoginAction(PrintWriter out, Hashtable params,
453
               HttpServletRequest request, HttpServletResponse response) {
454

    
455
    AuthSession sess = null;
456
    String un = ((String[])params.get("username"))[0];
457
    String pw = ((String[])params.get("password"))[0];
458
    String action = ((String[])params.get("action"))[0];
459
    String qformat = ((String[])params.get("qformat"))[0];
460

    
461
    try {
462
      sess = new AuthSession();
463
    } catch (Exception e) {
464
      System.out.println("error in MetacatServlet.handleLoginAction: " +
465
                          e.getMessage());
466
      out.println(e.getMessage());
467
      return;
468
    }
469
    boolean isValid = sess.authenticate(request, un, pw);
470
    // format and transform the output
471
    if (qformat.equals("xml")) {
472
      response.setContentType("text/xml");
473
      out.println(sess.getMessage());
474
    } else {
475

    
476
      try {
477

    
478
        DBTransform trans = new DBTransform();
479
        response.setContentType("text/html");
480
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
481
                                   "-//W3C//HTML//EN", qformat, out);
482

    
483
      } catch(Exception e) {
484

    
485
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
486
                                +e.getMessage(), 30);
487
      }
488

    
489
    // any output is returned
490
    }
491
  }
492

    
493
  /**
494
   * Handle the logout request. Close the connection.
495
   */
496
  private void handleLogoutAction(PrintWriter out, Hashtable params,
497
               HttpServletRequest request, HttpServletResponse response) {
498

    
499
    String qformat = ((String[])params.get("qformat"))[0];
500

    
501
    // close the connection
502
    HttpSession sess = request.getSession(false);
503
    if (sess != null) { sess.invalidate();  }
504

    
505
    // produce output
506
    StringBuffer output = new StringBuffer();
507
    output.append("<?xml version=\"1.0\"?>");
508
    output.append("<logout>");
509
    output.append("User logged out");
510
    output.append("</logout>");
511

    
512
    //format and transform the output
513
    if (qformat.equals("xml")) {
514
      response.setContentType("text/xml");
515
      out.println(output.toString());
516
    } else {
517

    
518
      try {
519

    
520
        DBTransform trans = new DBTransform();
521
        response.setContentType("text/html");
522
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
523
                                   "-//W3C//HTML//EN", qformat, out);
524

    
525
      } catch(Exception e) {
526

    
527
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
528
                                  +e.getMessage(), 30);
529
      }
530
    }
531
  }
532
  // END OF LOGIN & LOGOUT SECTION
533

    
534
  // SQUERY & QUERY SECTION
535
  /**
536
   * Retreive the squery xml, execute it and display it
537
   *
538
   * @param out the output stream to the client
539
   * @param params the Hashtable of parameters that should be included
540
   * in the squery.
541
   * @param response the response object linked to the client
542
   * @param conn the database connection
543
   */
544
  protected void handleSQuery(PrintWriter out, Hashtable params,
545
                 HttpServletResponse response, String user, String[] groups)
546
  {
547
    String xmlquery = ((String[])params.get("query"))[0];
548
    String qformat = ((String[])params.get("qformat"))[0];
549
    String resultdoc = null;
550
    MetaCatUtil.debugMessage("xmlquery: "+xmlquery, 30);
551
    double startTime = System.currentTimeMillis()/1000;
552
    Hashtable doclist = runQuery(xmlquery, user, groups);
553
    double docListTime = System.currentTimeMillis()/1000;
554
    MetaCatUtil.debugMessage("Time for getting doc list: "
555
                                            +(docListTime-startTime), 30);
556

    
557
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
558
    double toStringTime = System.currentTimeMillis()/1000;
559
    MetaCatUtil.debugMessage("Time to create xml string: "
560
                              +(toStringTime-docListTime), 30);
561
    //format and transform the results
562
    double outPutTime = 0;
563
    if(qformat.equals("xml")) {
564
      response.setContentType("text/xml");
565
      out.println(resultdoc);
566
      outPutTime = System.currentTimeMillis()/1000;
567
      MetaCatUtil.debugMessage("Output time: "+(outPutTime-toStringTime), 30);
568
    } else {
569
      transformResultset(resultdoc, response, out, qformat);
570
      outPutTime = System.currentTimeMillis()/1000;
571
      MetaCatUtil.debugMessage("Output time: "+(outPutTime-toStringTime), 30);
572
    }
573
  }
574

    
575
   /**
576
    * Create the xml query, execute it and display the results.
577
    *
578
    * @param out the output stream to the client
579
    * @param params the Hashtable of parameters that should be included
580
    * in the squery.
581
    * @param response the response object linked to the client
582
    */
583
  protected void handleQuery(PrintWriter out, Hashtable params,
584
                 HttpServletResponse response, String user, String[] groups)
585
  {
586
    //create the query and run it
587
    String xmlquery = DBQuery.createSQuery(params);
588
    Hashtable doclist = runQuery(xmlquery, user, groups);
589
    String qformat = ((String[])params.get("qformat"))[0];
590
    String resultdoc = null;
591

    
592
    resultdoc = createResultDocument(doclist, transformQuery(params));
593

    
594
    //format and transform the results
595
    if(qformat.equals("xml")) {
596
      response.setContentType("text/xml");
597
      out.println(resultdoc);
598
    } else {
599
      transformResultset(resultdoc, response, out, qformat);
600
    }
601
  }
602

    
603
  /**
604
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
605
   * so it can properly be placed in the <query> tag of the resultset.
606
   * This method is overwritable so that other applications can customize
607
   * the structure of what is in the <query> tag.
608
   *
609
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
610
   */
611
  protected String transformQuery(Hashtable params)
612
  {
613
    //DBQuery.createSQuery is a re-calling of a previously called
614
    //function but it is necessary
615
    //so that overriding methods have access to the params hashtable
616
    String xmlquery = DBQuery.createSQuery(params);
617
    //the <?xml version="1.0"?> tag is the first 22 characters of the
618
    xmlquery = xmlquery.trim();
619
    int index = xmlquery.indexOf("?>");
620
    return xmlquery.substring(index + 2, xmlquery.length());
621
  }
622

    
623
  /**
624
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
625
   * string as a param instead of a hashtable.
626
   *
627
   * @param xmlquery a string representing a query.
628
   */
629
  protected String transformQuery(String xmlquery)
630
  {
631
    xmlquery = xmlquery.trim();
632
    int index = xmlquery.indexOf("?>");
633
    return xmlquery.substring(index + 2, xmlquery.length());
634
  }
635

    
636
  /**
637
   * Run the query and return a hashtable of results.
638
   *
639
   * @param xmlquery the query to run
640
   */
641
  private Hashtable runQuery(String xmlquery, String user, String[] groups)
642
  {
643
    Hashtable doclist=null;
644

    
645
    try
646
    {
647

    
648
      DBQuery queryobj = new DBQuery(saxparser);
649
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,groups);
650

    
651
      return doclist;
652
    }
653
    catch (Exception e)
654
    {
655

    
656
      MetaCatUtil.debugMessage("Error in MetacatServlet.runQuery: "
657
                                                      + e.getMessage(), 30);
658
      doclist = null;
659
      return doclist;
660
    }
661
  }
662

    
663
  /**
664
   * Transorms an xml resultset document to html and sends it to the browser
665
   *
666
   * @param resultdoc the string representation of the document that needs
667
   * to be transformed.
668
   * @param response the HttpServletResponse object bound to the client.
669
   * @param out the output stream to the client
670
   * @param qformat the name of the style-set to use for transformations
671
   */
672
  protected void transformResultset(String resultdoc,
673
                                    HttpServletResponse response,
674
                                    PrintWriter out, String qformat)
675
  {
676

    
677
    try {
678

    
679
      DBTransform trans = new DBTransform();
680
      response.setContentType("text/html");
681
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
682
                                 "-//W3C//HTML//EN", qformat, out);
683

    
684
    }
685
    catch(Exception e)
686
    {
687

    
688
      MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
689
                                +e.getMessage(), 30);
690
    }
691
  }
692

    
693
  /**
694
   * Transforms a hashtable of documents to an xml or html result.
695
   *
696
   * @param doclist- the hashtable to transform
697
   * @param xmlquery- the query that returned the doclist result
698
   */
699
  protected String createResultDocument(Hashtable doclist, String xmlquery)
700
  {
701
    // Create a buffer to hold the xml result
702
    StringBuffer resultset = new StringBuffer();
703

    
704
    // Print the resulting root nodes
705
    String docid = null;
706
    String document = null;
707
    resultset.append("<?xml version=\"1.0\"?>\n");
708
    resultset.append("<resultset>\n");
709

    
710
    resultset.append("  <query>" + xmlquery + "</query>");
711

    
712
    if(doclist != null)
713
    {
714
      Enumeration doclistkeys = doclist.keys();
715
      while (doclistkeys.hasMoreElements())
716
      {
717
        docid = (String)doclistkeys.nextElement();
718
        document = (String)doclist.get(docid);
719
        resultset.append("  <document>" + document + "</document>");
720
      }
721
    }
722

    
723
    resultset.append("</resultset>");
724
    return resultset.toString();
725
  }
726
  // END OF SQUERY & QUERY SECTION
727

    
728
 //Exoport section
729
 /**
730
   * Handle the "export" request of data package from Metacat in zip format
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 handleExportAction(Hashtable params,
737
    HttpServletResponse response, String user, String[] groups, String passWord)
738
  {
739
    // Output stream
740
    ServletOutputStream out = null;
741
    // Zip output stream
742
    ZipOutputStream zOut = null;
743
    DocumentImpl docImpls=null;
744
    DBQuery queryObj=null;
745

    
746
    String[] docs = new String[10];
747
    String docId = "";
748

    
749
    try
750
    {
751
      // read the params
752
      if (params.containsKey("docid"))
753
      {
754
        docs = (String[])params.get("docid");
755
      }//if
756
      // Create a DBuery to handle export
757
      queryObj = new DBQuery(saxparser);
758
      // Get the docid
759
      docId=docs[0];
760
      // Make sure the client specify docid
761
      if (docId == null || docId.equals(""))
762
      {
763
        response.setContentType("text/xml"); //MIME type
764
        // Get a printwriter
765
        PrintWriter pw = response.getWriter();
766
        // Send back message
767
        pw.println("<?xml version=\"1.0\"?>");
768
        pw.println("<error>");
769
        pw.println("You didn't specify requested docid");
770
        pw.println("</error>");
771
        // Close printwriter
772
        pw.close();
773
        return;
774
      }//if
775
      // Get output stream
776
      out = response.getOutputStream();
777
      response.setContentType("application/zip"); //MIME type
778
      zOut = new ZipOutputStream(out);
779
      zOut =queryObj.getZippedPackage(docId, out, user, groups, passWord);
780
      zOut.finish(); //terminate the zip file
781
      zOut.close();  //close the zip stream
782

    
783
    }//try
784
    catch (Exception e)
785
    {
786
      try
787
      {
788
        response.setContentType("text/xml"); //MIME type
789
        // Send error message back
790
        if (out != null)
791
        {
792
            PrintWriter pw = new PrintWriter(out);
793
            pw.println("<?xml version=\"1.0\"?>");
794
            pw.println("<error>");
795
            pw.println(e.getMessage());
796
            pw.println("</error>");
797
            // Close printwriter
798
            pw.close();
799
            // Close output stream
800
            out.close();
801
        }//if
802
        // Close zip output stream
803
        if ( zOut != null )
804
        {
805
          zOut.close();
806
        }//if
807
      }//try
808
      catch (IOException ioe)
809
      {
810
        MetaCatUtil.debugMessage("Problem with the servlet output " +
811
                           "in MetacatServlet.handleExportAction: " +
812
                           ioe.getMessage(), 30);
813
      }//catch
814

    
815
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleExportAction: " +
816
                         e.getMessage(), 30);
817
      e.printStackTrace(System.out);
818

    
819
    }//catch
820

    
821
  }//handleExportAction
822

    
823
  
824
   //read inline data section
825
 /**
826
   * In eml2 document, the xml can have inline data and data was stripped off 
827
   * and store in file system. This action can be used to read inline data only
828
   * @param params the Hashtable of HTTP request parameters
829
   * @param response the HTTP response object linked to the client
830
   * @param user the username sent the request
831
   * @param groups the user's groupnames
832
   */
833
  private void handleReadInlineDataAction(Hashtable params,
834
                                          HttpServletResponse response,
835
                                          String user, String passWord,
836
                                          String[] groups)
837
  {
838
    String[] docs = new String[10];
839
    String inlineDataId = null;
840
    String docId = "";
841
    ServletOutputStream out = null;
842

    
843
    try
844
    {
845
      // read the params
846
      if (params.containsKey("inlinedataid"))
847
      {
848
        docs = (String[])params.get("inlinedataid");
849
      }//if
850
      // Get the docid
851
      inlineDataId=docs[0];
852
      // Make sure the client specify docid
853
      if (inlineDataId == null || inlineDataId.equals(""))
854
      {
855
        throw new Exception("You didn't specify requested inlinedataid");
856
      }//if
857
      
858
      // check for permission
859
      docId = MetaCatUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
860
      PermissionController controller = new PermissionController(docId);
861
      // check top level read permission
862
      if (!controller.hasPermission(user, groups, 
863
                                    AccessControlInterface.READSTRING))
864
      {
865
          throw new Exception("User "+ user + " doesn't have permission "+
866
                              " to read document " + docId);
867
      }//if
868
      // if the document has subtree control, we need to check subtree control
869
      else if(controller.hasSubTreeAccessControl())
870
      {
871
        // get node id for inlinedata
872
        long nodeId=getInlineDataNodeId(inlineDataId, docId);
873
        if (!controller.hasPermissionForSubTreeNode(user, groups,
874
                                     AccessControlInterface.READSTRING, nodeId))
875
        {
876
           throw new Exception("User "+ user + " doesn't have permission "+
877
                              " to read inlinedata " + inlineDataId);
878
        }//if
879
        
880
      }//else
881
      
882
      // Get output stream
883
      out = response.getOutputStream();
884
      // read the inline data from the file
885
      String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
886
      File lineData = new File(inlinePath, inlineDataId);
887
      FileInputStream input = new FileInputStream(lineData);
888
      byte [] buffer = new byte[4*1024];
889
      int bytes = input.read(buffer);
890
      while (bytes != -1)
891
      {
892
        out.write(buffer, 0, bytes);
893
        bytes = input.read(buffer);
894
      }
895
      out.close();
896

    
897
    }//try
898
    catch (Exception e)
899
    {
900
      try
901
      { 
902
        PrintWriter pw = null;
903
        // Send error message back
904
        if (out != null)
905
        {
906
            pw = new PrintWriter(out);
907
        }//if
908
        else
909
        {
910
          pw = response.getWriter();
911
        } 
912
         pw.println("<?xml version=\"1.0\"?>");
913
         pw.println("<error>");
914
         pw.println(e.getMessage());
915
         pw.println("</error>");
916
         // Close printwriter
917
         pw.close();
918
         // Close output stream if out is not null
919
         if (out != null)
920
         {
921
           out.close();
922
         }
923
     }//try
924
     catch (IOException ioe)
925
     {
926
        MetaCatUtil.debugMessage("Problem with the servlet output " +
927
                           "in MetacatServlet.handleExportAction: " +
928
                           ioe.getMessage(), 30);
929
     }//catch
930

    
931
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadInlineDataAction: " 
932
                                + e.getMessage(), 30);
933
   
934
    }//catch
935

    
936
  }//handleReadInlineDataAction
937
  
938
  /*
939
   * Get the nodeid from xml_nodes for the inlinedataid
940
   */
941
  private long getInlineDataNodeId(String inLineDataId, String docId) 
942
                                   throws SQLException
943
  {
944
    long nodeId = 0;
945
    String INLINE = "inline";
946
    boolean hasRow;
947
    PreparedStatement pStmt = null;
948
    DBConnection conn = null;
949
    int serialNumber = -1;
950
    String sql ="SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? " +
951
                "AND nodetype='TEXT' AND parentnodeid IN " +
952
                "(SELECT nodeid FROM xml_nodes WHERE docid=? AND " + 
953
                "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
954
  
955
    try
956
    {
957
      //check out DBConnection
958
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
959
      serialNumber=conn.getCheckOutSerialNumber();
960
    
961
      pStmt = conn.prepareStatement(sql);
962
      //bind value
963
      pStmt.setString(1, docId);//docid
964
      pStmt.setString(2, inLineDataId);//inlinedataid
965
      pStmt.setString(3, docId);
966
      // excute query 
967
      pStmt.execute();
968
      ResultSet rs = pStmt.getResultSet();
969
      hasRow=rs.next();
970
      // get result
971
      if (hasRow)
972
      {
973
        nodeId = rs.getLong(1);  
974
      }//if
975
     
976
    }//try
977
    catch (SQLException e)
978
    {
979
      throw e;
980
    }
981
    finally
982
    {
983
      try
984
      {
985
        pStmt.close();
986
      }
987
      finally
988
      {
989
        DBConnectionPool.returnDBConnection(conn, serialNumber);
990
      }
991
    }
992
    MetaCatUtil.debugMessage("The nodeid for inlinedataid " + inLineDataId +
993
                             " is: "+nodeId, 35);
994
    return nodeId;
995
  }
996
  
997
  
998
  
999
  // READ SECTION
1000
  /**
1001
   * Handle the "read" request of metadata/data files from Metacat
1002
   * or any files from Internet;
1003
   * transformed metadata XML document into HTML presentation if requested;
1004
   * zip files when more than one were requested.
1005
   *
1006
   * @param params the Hashtable of HTTP request parameters
1007
   * @param response the HTTP response object linked to the client
1008
   * @param user the username sent the request
1009
   * @param groups the user's groupnames
1010
   */
1011
  private void handleReadAction(Hashtable params, HttpServletResponse response,
1012
                                String user, String passWord, String[] groups)
1013
  {
1014
    ServletOutputStream out = null;
1015
    ZipOutputStream zout = null;
1016
    PrintWriter pw = null;
1017
    boolean zip = false;
1018
    boolean withInlineData = true;
1019

    
1020
    try {
1021
      String[] docs = new String[0];
1022
      String docid = "";
1023
      String qformat = "";
1024
      String abstrpath = null;
1025

    
1026
      // read the params
1027
      if (params.containsKey("docid")) {
1028
        docs = (String[])params.get("docid");
1029
      }
1030
      if (params.containsKey("qformat")) {
1031
        qformat = ((String[])params.get("qformat"))[0];
1032
      }
1033
      // the param for only metadata (eml)
1034
      if (params.containsKey("inlinedata"))
1035
      {
1036
        
1037
        String inlineData = ((String[])params.get("inlinedata"))[0];
1038
        if (inlineData.equalsIgnoreCase("false"))
1039
        {
1040
          withInlineData = false;
1041
        }
1042
      } 
1043
      if (params.containsKey("abstractpath")) {
1044
        abstrpath = ((String[])params.get("abstractpath"))[0];
1045
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
1046
          viewAbstract(response, abstrpath, docs[0]);
1047
          return;
1048
        }
1049
      }
1050
      if ( (docs.length > 1) || qformat.equals("zip") ) {
1051
        zip = true;
1052
        out = response.getOutputStream();
1053
        response.setContentType("application/zip"); //MIME type
1054
        zout = new ZipOutputStream(out);
1055
      }
1056
      // go through the list of docs to read
1057
      for (int i=0; i < docs.length; i++ ) {
1058
        try {
1059

    
1060
          URL murl = new URL(docs[i]);
1061
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
1062
          // case docid="http://.../?docid=aaa"
1063
          // or docid="metacat://.../?docid=bbb"
1064
          if (murlQueryStr.containsKey("docid")) {
1065
            // get only docid, eliminate the rest
1066
            docid = (String)murlQueryStr.get("docid");
1067
            if ( zip ) {
1068
              addDocToZip(docid, zout, user, groups);
1069
            } else {
1070
              readFromMetacat(response, docid, qformat, abstrpath,
1071
                              user, groups, zip, zout, withInlineData);
1072
            }
1073

    
1074
          // case docid="http://.../filename"
1075
          } else {
1076
            docid = docs[i];
1077
            if ( zip ) {
1078
              addDocToZip(docid, zout, user, groups);
1079
            } else {
1080
              readFromURLConnection(response, docid);
1081
            }
1082
          }
1083

    
1084
        // case docid="ccc"
1085
        } catch (MalformedURLException mue) {
1086
          docid = docs[i];
1087
          if ( zip ) {
1088
            addDocToZip(docid, zout, user, groups);
1089
          } else {
1090
            readFromMetacat(response, docid, qformat, abstrpath,
1091
                            user, groups, zip, zout, withInlineData);
1092
          }
1093
        }
1094

    
1095
      } /* end for */
1096

    
1097
      if ( zip ) {
1098
        zout.finish(); //terminate the zip file
1099
        zout.close();  //close the zip stream
1100
      }
1101

    
1102

    
1103
    }
1104
    // To handle doc not found exception
1105
    catch (McdbDocNotFoundException notFoundE)
1106
    {
1107
      // the docid which didn't be found
1108
      String notFoundDocId = notFoundE.getUnfoundDocId();
1109
      String notFoundRevision = notFoundE.getUnfoundRevision();
1110
      MetaCatUtil.debugMessage("Missed id: "+ notFoundDocId, 30);
1111
      MetaCatUtil.debugMessage("Missed rev: "+ notFoundRevision, 30);
1112
      try
1113
      {
1114
        // read docid from remote server
1115
        readFromRemoteMetaCat(response, notFoundDocId, notFoundRevision,
1116
                                              user, passWord, out, zip, zout);
1117
        // Close zout outputstream
1118
        if ( zout != null)
1119
        {
1120
          zout.close();
1121
        }
1122
        // close output stream
1123
        if (out != null)
1124
        {
1125
          out.close();
1126
        }
1127

    
1128
      }//try
1129
      catch ( Exception exc)
1130
      {
1131
        MetaCatUtil.debugMessage("Erorr in MetacatServlet.hanldReadAction: "+
1132
                                      exc.getMessage(), 30);
1133
        try
1134
        {
1135
          if (out != null)
1136
          {
1137
            response.setContentType("text/xml");
1138
            // Send back error message by printWriter
1139
            pw = new PrintWriter(out);
1140
            pw.println("<?xml version=\"1.0\"?>");
1141
            pw.println("<error>");
1142
            pw.println(notFoundE.getMessage());
1143
            pw.println("</error>");
1144
            pw.close();
1145
            out.close();
1146

    
1147
          }
1148
          else
1149
          {
1150
           response.setContentType("text/xml"); //MIME type
1151
           // Send back error message if out = null
1152
           if (pw == null)
1153
           {
1154
             // If pw is null, open the respnose
1155
            pw = response.getWriter();
1156
           }
1157
           pw.println("<?xml version=\"1.0\"?>");
1158
           pw.println("<error>");
1159
           pw.println(notFoundE.getMessage());
1160
           pw.println("</error>");
1161
           pw.close();
1162
        }
1163
        // close zout
1164
        if ( zout != null )
1165
        {
1166
          zout.close();
1167
        }
1168
        }//try
1169
        catch (IOException ie)
1170
        {
1171
          MetaCatUtil.debugMessage("Problem with the servlet output " +
1172
                           "in MetacatServlet.handleReadAction: " +
1173
                           ie.getMessage(), 30);
1174
        }//cathch
1175
      }//catch
1176
    }// catch McdbDocNotFoundException
1177
    catch (Exception e)
1178
    {
1179
      try {
1180

    
1181
        if (out != null) {
1182
            response.setContentType("text/xml"); //MIME type
1183
            pw = new PrintWriter(out);
1184
            pw.println("<?xml version=\"1.0\"?>");
1185
            pw.println("<error>");
1186
            pw.println(e.getMessage());
1187
            pw.println("</error>");
1188
            pw.close();
1189
            out.close();
1190
        }
1191
        else
1192
        {
1193
           response.setContentType("text/xml"); //MIME type
1194
           // Send back error message if out = null
1195
           if ( pw == null)
1196
           {
1197
            pw = response.getWriter();
1198
           }
1199
           pw.println("<?xml version=\"1.0\"?>");
1200
           pw.println("<error>");
1201
           pw.println(e.getMessage());
1202
           pw.println("</error>");
1203
           pw.close();
1204

    
1205
        }
1206
        // Close zip output stream
1207
        if ( zout != null ) { zout.close(); }
1208

    
1209
      } catch (IOException ioe) {
1210
        MetaCatUtil.debugMessage("Problem with the servlet output " +
1211
                           "in MetacatServlet.handleReadAction: " +
1212
                           ioe.getMessage(), 30);
1213
        ioe.printStackTrace(System.out);
1214

    
1215
      }
1216

    
1217
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadAction: " +
1218
                               e.getMessage(), 30);
1219
      //e.printStackTrace(System.out);
1220
    }
1221

    
1222
  }
1223

    
1224
  // read metadata or data from Metacat
1225
  private void readFromMetacat(HttpServletResponse response, String docid,
1226
                               String qformat, String abstrpath, String user,
1227
                               String[] groups, boolean zip, 
1228
                               ZipOutputStream zout, boolean withInlineData)
1229
               throws ClassNotFoundException, IOException, SQLException,
1230
                      McdbException, Exception
1231
  {
1232

    
1233
    try {
1234

    
1235

    
1236
      DocumentImpl doc = new DocumentImpl(docid);
1237

    
1238
      //check the permission for read
1239
      if (!doc.hasReadPermission(user, groups, docid))
1240
      {
1241
        Exception e = new Exception("User " + user + " does not have permission"
1242
                       +" to read the document with the docid " + docid);
1243

    
1244
        throw e;
1245
      }
1246

    
1247
      if ( doc.getRootNodeID() == 0 ) {
1248
        // this is data file
1249
        String filepath = util.getOption("datafilepath");
1250
        if(!filepath.endsWith("/")) {
1251
          filepath += "/";
1252
        }
1253
        String filename = filepath + docid;
1254
        FileInputStream fin = null;
1255
        fin = new FileInputStream(filename);
1256

    
1257
        //MIME type
1258
        String contentType = getServletContext().getMimeType(filename);
1259
        if (contentType == null) {
1260
          if (filename.endsWith(".xml")) {
1261
            contentType="text/xml";
1262
          } else if (filename.endsWith(".css")) {
1263
            contentType="text/css";
1264
          } else if (filename.endsWith(".dtd")) {
1265
            contentType="text/plain";
1266
          } else if (filename.endsWith(".xsd")) {
1267
            contentType="text/xml";
1268
          } else if (filename.endsWith("/")) {
1269
            contentType="text/html";
1270
          } else {
1271
            File f = new File(filename);
1272
            if ( f.isDirectory() ) {
1273
              contentType="text/html";
1274
            } else {
1275
              // Use the content type set in the metacat.properties file
1276
              contentType= util.getOption("defaultcontenttype");
1277
              System.out.println(" default content type: "+ contentType);
1278
              if ( contentType == null ) {
1279
              contentType="application/octet-stream";
1280
              }
1281
            }
1282
          }
1283
        }
1284
        System.out.println("final content type: "+contentType);
1285
        response.setContentType(contentType);
1286
        // if we decide to use "application/octet-stream" for all data returns
1287
        // response.setContentType("application/octet-stream");
1288

    
1289
        try {
1290

    
1291
          ServletOutputStream out = response.getOutputStream();
1292
          byte[] buf = new byte[4 * 1024]; // 4K buffer
1293
          int b = fin.read(buf);
1294
          while (b != -1) {
1295
            out.write(buf, 0, b);
1296
            b = fin.read(buf);
1297
          }
1298
        } finally {
1299
          if (fin != null) fin.close();
1300
        }
1301

    
1302
      } else {
1303
        // this is metadata doc
1304
        if ( qformat.equals("xml") ) {
1305

    
1306
          // set content type first
1307
          response.setContentType("text/xml");   //MIME type
1308
          PrintWriter out = response.getWriter();
1309
          doc.toXml(out, user, groups, withInlineData);
1310
        } else {
1311
          response.setContentType("text/html");  //MIME type
1312
          PrintWriter out = response.getWriter();
1313

    
1314
          // Look up the document type
1315
          String doctype = doc.getDoctype();
1316
          // Transform the document to the new doctype
1317
          DBTransform dbt = new DBTransform();
1318
          dbt.transformXMLDocument(doc.toString(user, groups, withInlineData),
1319
                                   doctype,"-//W3C//HTML//EN", qformat, out);
1320
        }
1321

    
1322
      }
1323
    }
1324
    catch (Exception except)
1325
    {
1326
      throw except;
1327

    
1328
    }
1329

    
1330
  }
1331

    
1332
  // read data from URLConnection
1333
  private void readFromURLConnection(HttpServletResponse response, String docid)
1334
               throws IOException, MalformedURLException
1335
  {
1336
    ServletOutputStream out = response.getOutputStream();
1337
    String contentType = getServletContext().getMimeType(docid); //MIME type
1338
    if (contentType == null) {
1339
      if (docid.endsWith(".xml")) {
1340
        contentType="text/xml";
1341
      } else if (docid.endsWith(".css")) {
1342
        contentType="text/css";
1343
      } else if (docid.endsWith(".dtd")) {
1344
        contentType="text/plain";
1345
      } else if (docid.endsWith(".xsd")) {
1346
        contentType="text/xml";
1347
      } else if (docid.endsWith("/")) {
1348
        contentType="text/html";
1349
      } else {
1350
        File f = new File(docid);
1351
        if ( f.isDirectory() ) {
1352
          contentType="text/html";
1353
        } else {
1354
          contentType="application/octet-stream";
1355
        }
1356
      }
1357
    }
1358
    response.setContentType(contentType);
1359
    // if we decide to use "application/octet-stream" for all data returns
1360
    // response.setContentType("application/octet-stream");
1361

    
1362
    // this is http url
1363
    URL url = new URL(docid);
1364
    BufferedInputStream bis = null;
1365
    try {
1366
      bis = new BufferedInputStream(url.openStream());
1367
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1368
      int b = bis.read(buf);
1369
      while (b != -1) {
1370
        out.write(buf, 0, b);
1371
        b = bis.read(buf);
1372
      }
1373
    } finally {
1374
      if (bis != null) bis.close();
1375
    }
1376

    
1377
  }
1378

    
1379
  // read file/doc and write to ZipOutputStream
1380
  private void addDocToZip(String docid, ZipOutputStream zout,
1381
                              String user, String[] groups)
1382
               throws ClassNotFoundException, IOException, SQLException,
1383
                      McdbException, Exception
1384
  {
1385
    byte[] bytestring = null;
1386
    ZipEntry zentry = null;
1387

    
1388
    try {
1389
      URL url = new URL(docid);
1390

    
1391
      // this http url; read from URLConnection; add to zip
1392
      zentry = new ZipEntry(docid);
1393
      zout.putNextEntry(zentry);
1394
      BufferedInputStream bis = null;
1395
      try {
1396
        bis = new BufferedInputStream(url.openStream());
1397
        byte[] buf = new byte[4 * 1024]; // 4K buffer
1398
        int b = bis.read(buf);
1399
        while(b != -1) {
1400
          zout.write(buf, 0, b);
1401
          b = bis.read(buf);
1402
        }
1403
      } finally {
1404
        if (bis != null) bis.close();
1405
      }
1406
      zout.closeEntry();
1407

    
1408
    } catch (MalformedURLException mue) {
1409

    
1410
      // this is metacat doc (data file or metadata doc)
1411

    
1412
      try {
1413

    
1414
        DocumentImpl doc = new DocumentImpl(docid);
1415

    
1416
        //check the permission for read
1417
        if (!doc.hasReadPermission(user, groups, docid))
1418
        {
1419
          Exception e = new Exception("User " + user + " does not have "
1420
                    +"permission to read the document with the docid " + docid);
1421

    
1422
          throw e;
1423
        }
1424

    
1425
        if ( doc.getRootNodeID() == 0 ) {
1426
          // this is data file; add file to zip
1427
          String filepath = util.getOption("datafilepath");
1428
          if(!filepath.endsWith("/")) {
1429
            filepath += "/";
1430
          }
1431
          String filename = filepath + docid;
1432
          FileInputStream fin = null;
1433
          fin = new FileInputStream(filename);
1434
          try {
1435

    
1436
            zentry = new ZipEntry(docid);
1437
            zout.putNextEntry(zentry);
1438
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1439
            int b = fin.read(buf);
1440
            while (b != -1) {
1441
              zout.write(buf, 0, b);
1442
              b = fin.read(buf);
1443
            }
1444
          } finally {
1445
            if (fin != null) fin.close();
1446
          }
1447
          zout.closeEntry();
1448

    
1449
        } else {
1450
          // this is metadata doc; add doc to zip
1451
          bytestring = doc.toString().getBytes();
1452
          zentry = new ZipEntry(docid + ".xml");
1453
          zentry.setSize(bytestring.length);
1454
          zout.putNextEntry(zentry);
1455
          zout.write(bytestring, 0, bytestring.length);
1456
          zout.closeEntry();
1457
        }
1458
      } catch (Exception except) {
1459
        throw except;
1460

    
1461
      }
1462

    
1463
    }
1464

    
1465
  }
1466

    
1467
  // view abstract within document
1468
  private void viewAbstract(HttpServletResponse response,
1469
                            String abstractpath, String docid)
1470
               throws ClassNotFoundException, IOException, SQLException,
1471
                      McdbException, Exception
1472
  {
1473

    
1474
    PrintWriter out =null;
1475
    try {
1476

    
1477
      response.setContentType("text/html");  //MIME type
1478
      out = response.getWriter();
1479
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid);
1480
      out.println("<html><head><title>Abstract</title></head>");
1481
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
1482
      for (int i=0; i<abstracts.length; i++) {
1483
        out.println("<p>" + (String)abstracts[i] + "</p>");
1484
      }
1485
      out.println("</body></html>");
1486

    
1487
    } catch (Exception e) {
1488
       out.println("<?xml version=\"1.0\"?>");
1489
       out.println("<error>");
1490
       out.println(e.getMessage());
1491
       out.println("</error>");
1492

    
1493

    
1494
    }
1495
  }
1496
  /**
1497
   * If metacat couldn't find a data file or document locally, it will read this
1498
   * docid from its home server. This is for the replication feature
1499
   */
1500
  private void readFromRemoteMetaCat(HttpServletResponse response, String docid,
1501
                     String rev, String user, String password,
1502
                     ServletOutputStream out, boolean zip, ZipOutputStream zout)
1503
                        throws Exception
1504
 {
1505
   // Create a object of RemoteDocument, "" is for zipEntryPath
1506
   RemoteDocument remoteDoc =
1507
                        new RemoteDocument (docid, rev,user, password, "");
1508
   String docType = remoteDoc.getDocType();
1509
   // Only read data file
1510
   if (docType.equals("BIN"))
1511
   {
1512
    // If it is zip format
1513
    if (zip)
1514
    {
1515
      remoteDoc.readDocumentFromRemoteServerByZip(zout);
1516
    }//if
1517
    else
1518
    {
1519
      if (out == null)
1520
      {
1521
        out = response.getOutputStream();
1522
      }//if
1523
      response.setContentType("application/octet-stream");
1524
      remoteDoc.readDocumentFromRemoteServer(out);
1525
    }//else (not zip)
1526
   }//if doctype=bin
1527
   else
1528
   {
1529
     throw new Exception("Docid: "+docid+"."+rev+" couldn't find");
1530
   }//else
1531
 }//readFromRemoteMetaCat
1532

    
1533
  // END OF READ SECTION
1534
  
1535
 
1536
  
1537
  // INSERT/UPDATE SECTION
1538
  /**
1539
   * Handle the database putdocument request and write an XML document
1540
   * to the database connection
1541
   */
1542
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1543
               String user, String[] groups) {
1544

    
1545
    DBConnection dbConn = null;
1546
    int serialNumber = -1;
1547

    
1548
    try {
1549
      // Get the document indicated
1550
      String[] doctext = (String[])params.get("doctext");
1551

    
1552
      String pub = null;
1553
      if (params.containsKey("public")) {
1554
        pub = ((String[])params.get("public"))[0];
1555
      }
1556

    
1557
      StringReader dtd = null;
1558
      if (params.containsKey("dtdtext")) {
1559
        String[] dtdtext = (String[])params.get("dtdtext");
1560
        try {
1561
          if ( !dtdtext[0].equals("") ) {
1562
            dtd = new StringReader(dtdtext[0]);
1563
          }
1564
        } catch (NullPointerException npe) {}
1565
      }
1566

    
1567
      StringReader xml = null;
1568
      boolean validate = false;
1569
      DocumentImplWrapper documentWrapper = null;
1570
      try {
1571
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1572
        // in order to decide whether to use validation parser
1573
        validate = needDTDValidation(doctext[0]);
1574
        if (validate)
1575
        {
1576
          // set a dtd base validation parser
1577
          String rule = DocumentImpl.DTD;
1578
          documentWrapper = new DocumentImplWrapper(rule, validate);
1579
        }
1580
        else if (needSchemaValidation(doctext[0]))
1581
        {
1582
          // for eml2
1583
          if (needEml2Validation(doctext[0]))
1584
          {
1585
             // set eml2 base validation parser
1586
            String rule = DocumentImpl.EML2;
1587
            // using emlparser to check id validation
1588
            EMLParser parser = new EMLParser(doctext[0]);
1589
            documentWrapper = new DocumentImplWrapper(rule, true);
1590
          }
1591
          else
1592
          {
1593
            // set schema base validation parser
1594
            String rule = DocumentImpl.SCHEMA;
1595
            documentWrapper = new DocumentImplWrapper(rule, true);
1596
          }
1597
        }
1598
        else
1599
        {
1600
          documentWrapper = new DocumentImplWrapper("", false);
1601
        }
1602
        
1603
        xml = new StringReader(doctext[0]);
1604

    
1605
        String[] action = (String[])params.get("action");
1606
        String[] docid = (String[])params.get("docid");
1607
        String newdocid = null;
1608

    
1609
        String doAction = null;
1610
        if (action[0].equals("insert")) {
1611
          doAction = "INSERT";
1612
        } else if (action[0].equals("update")) {
1613
          doAction = "UPDATE";
1614
        }
1615

    
1616
        try
1617
        {
1618
          // get a connection from the pool
1619
          dbConn=DBConnectionPool.
1620
                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1621
          serialNumber=dbConn.getCheckOutSerialNumber();
1622

    
1623

    
1624
          // write the document to the database
1625
          try
1626
          {
1627
            String accNumber = docid[0];
1628
            MetaCatUtil.debugMessage(""+ doAction + " " + accNumber +"...", 10);
1629
            if (accNumber.equals(""))
1630
            {
1631
              accNumber = null;
1632
            }//if
1633
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1634
                                          accNumber, user, groups);
1635

    
1636
          }//try
1637
          catch (NullPointerException npe)
1638
          {
1639
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1640
                                          null, user, groups);
1641
          }//catch
1642
        
1643
        }//try
1644
        finally
1645
        {
1646
          // Return db connection
1647
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1648
        }
1649

    
1650
        // set content type and other response header fields first
1651
        //response.setContentType("text/xml");
1652
        out.println("<?xml version=\"1.0\"?>");
1653
        out.println("<success>");
1654
        out.println("<docid>" + newdocid + "</docid>");
1655
        out.println("</success>");
1656

    
1657
      } 
1658
      catch (NullPointerException npe) 
1659
      {
1660
        //response.setContentType("text/xml");
1661
        out.println("<?xml version=\"1.0\"?>");
1662
        out.println("<error>");
1663
        out.println(npe.getMessage());
1664
        out.println("</error>");
1665
      }
1666
    } 
1667
    catch (Exception e) 
1668
    {
1669
      //response.setContentType("text/xml");
1670
      out.println("<?xml version=\"1.0\"?>");
1671
      out.println("<error>");
1672
      out.println(e.getMessage());
1673
      out.println("</error>");
1674
    }
1675
  }
1676

    
1677
  /**
1678
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1679
   * in order to decide whether to use validation parser
1680
   */
1681
  private static boolean needDTDValidation(String xmltext) throws IOException {
1682

    
1683
    StringReader xmlreader = new StringReader(xmltext);
1684
    StringBuffer cbuff = new StringBuffer();
1685
    java.util.Stack st = new java.util.Stack();
1686
    boolean validate = false;
1687
    int c;
1688
    int inx;
1689

    
1690
    // read from the stream until find the keywords
1691
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1692
      cbuff.append((char)c);
1693

    
1694
      // "<!DOCTYPE" keyword is found; put it in the stack
1695
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1696
        cbuff = new StringBuffer();
1697
        st.push("<!DOCTYPE");
1698
      }
1699
      // "PUBLIC" keyword is found; put it in the stack
1700
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1701
        cbuff = new StringBuffer();
1702
        st.push("PUBLIC");
1703
      }
1704
      // "SYSTEM" keyword is found; put it in the stack
1705
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1706
        cbuff = new StringBuffer();
1707
        st.push("SYSTEM");
1708
      }
1709
      // ">" character is found; put it in the stack
1710
      // ">" is found twice: fisrt from <?xml ...?>
1711
      // and second from <!DOCTYPE ... >
1712
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1713
        cbuff = new StringBuffer();
1714
        st.push(">");
1715
      }
1716
    }
1717

    
1718
    // close the stream
1719
    xmlreader.close();
1720

    
1721
    // check the stack whether it contains the keywords:
1722
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1723
    if ( st.size() == 4 ) {
1724
      if ( ((String)st.pop()).equals(">") &&
1725
           ( ((String)st.peek()).equals("PUBLIC") |
1726
             ((String)st.pop()).equals("SYSTEM") ) &&
1727
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1728
        validate = true;
1729
      }
1730
    }
1731

    
1732
    MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1733
    return validate;
1734
  }
1735
  // END OF INSERT/UPDATE SECTION
1736
  
1737
  /* check if the xml string contains key words to specify schema loocation*/
1738
  private boolean needSchemaValidation(String xml)
1739
  {
1740
    boolean needSchemaValidate =false;
1741
    if (xml == null)
1742
    {
1743
      MetaCatUtil.debugMessage("Validation for schema is " +
1744
                               needSchemaValidate, 10);
1745
      return needSchemaValidate;
1746
    }
1747
    else if (xml.indexOf(SCHEMALOCATIONKEYWORD) != -1 ||
1748
             xml.indexOf(NONAMESPACELOCATION) != -1 )
1749
    {
1750
      // if contains schema location key word, should be validate
1751
      needSchemaValidate = true;
1752
    }
1753
    
1754
    MetaCatUtil.debugMessage("Validation for schema is " + 
1755
                             needSchemaValidate, 10);
1756
    return needSchemaValidate;
1757
   
1758
  }
1759
  
1760
   /* check if the xml string contains key words to specify schema loocation*/
1761
  private boolean needEml2Validation(String xml)
1762
  {
1763
    boolean needEml2Validate =false;
1764
    if (xml == null)
1765
    {
1766
      MetaCatUtil.debugMessage("Validation for schema is " +
1767
                               needEml2Validate, 10);
1768
      return needEml2Validate;
1769
    }
1770
    else if (xml.indexOf(EML2KEYWORD) != -1)
1771
    {
1772
      // if contains schema location key word, should be validate
1773
      needEml2Validate = true;
1774
    }
1775
    
1776
    MetaCatUtil.debugMessage("Validation for eml is " + 
1777
                             needEml2Validate, 10);
1778
    return needEml2Validate;
1779
   
1780
  }
1781
  
1782
  // DELETE SECTION
1783
  /**
1784
   * Handle the database delete request and delete an XML document
1785
   * from the database connection
1786
   */
1787
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1788
               HttpServletResponse response, String user, String[] groups) {
1789

    
1790
    String[] docid = (String[])params.get("docid");
1791

    
1792
    // delete the document from the database
1793
    try {
1794

    
1795
                                      // NOTE -- NEED TO TEST HERE
1796
                                      // FOR EXISTENCE OF DOCID PARAM
1797
                                      // BEFORE ACCESSING ARRAY
1798
      try {
1799
        DocumentImpl.delete(docid[0], user, groups);
1800
        response.setContentType("text/xml");
1801
        out.println("<?xml version=\"1.0\"?>");
1802
        out.println("<success>");
1803
        out.println("Document deleted.");
1804
        out.println("</success>");
1805
      } catch (AccessionNumberException ane) {
1806
        response.setContentType("text/xml");
1807
        out.println("<?xml version=\"1.0\"?>");
1808
        out.println("<error>");
1809
        out.println("Error deleting document!!!");
1810
        out.println(ane.getMessage());
1811
        out.println("</error>");
1812
      }
1813
    } catch (Exception e) {
1814
      response.setContentType("text/xml");
1815
      out.println("<?xml version=\"1.0\"?>");
1816
      out.println("<error>");
1817
      out.println(e.getMessage());
1818
      out.println("</error>");
1819
    }
1820
  }
1821
  // END OF DELETE SECTION
1822

    
1823
  // VALIDATE SECTION
1824
  /**
1825
   * Handle the validation request and return the results to the requestor
1826
   */
1827
  private void handleValidateAction(PrintWriter out, Hashtable params) {
1828

    
1829
    // Get the document indicated
1830
    String valtext = null;
1831
    DBConnection dbConn = null;
1832
    int serialNumber = -1;
1833

    
1834
    try {
1835
      valtext = ((String[])params.get("valtext"))[0];
1836
    } catch (Exception nullpe) {
1837

    
1838

    
1839
      String docid = null;
1840
      try {
1841
        // Find the document id number
1842
        docid = ((String[])params.get("docid"))[0];
1843

    
1844

    
1845
        // Get the document indicated from the db
1846
        DocumentImpl xmldoc = new DocumentImpl(docid);
1847
        valtext = xmldoc.toString();
1848

    
1849
      } catch (NullPointerException npe) {
1850

    
1851
        out.println("<error>Error getting document ID: " + docid + "</error>");
1852
        //if ( conn != null ) { util.returnConnection(conn); }
1853
        return;
1854
      } catch (Exception e) {
1855

    
1856
        out.println(e.getMessage());
1857
      }
1858
    }
1859

    
1860

    
1861
    try {
1862
      // get a connection from the pool
1863
      dbConn=DBConnectionPool.
1864
                  getDBConnection("MetaCatServlet.handleValidateAction");
1865
      serialNumber=dbConn.getCheckOutSerialNumber();
1866
      DBValidate valobj = new DBValidate(saxparser,dbConn);
1867
      boolean valid = valobj.validateString(valtext);
1868

    
1869
      // set content type and other response header fields first
1870

    
1871
      out.println(valobj.returnErrors());
1872

    
1873
    } catch (NullPointerException npe2) {
1874
      // set content type and other response header fields first
1875

    
1876
      out.println("<error>Error validating document.</error>");
1877
    } catch (Exception e) {
1878

    
1879
      out.println(e.getMessage());
1880
    } finally {
1881
      // Return db connection
1882
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1883
    }
1884
  }
1885
  // END OF VALIDATE SECTION
1886

    
1887
  // OTHER ACTION HANDLERS
1888

    
1889
  /**
1890
   * Handle "getrevsionanddoctype" action
1891
   * Given a docid, return it's current revision and doctype from data base
1892
   * The output is String look like "rev;doctype"
1893
   */
1894
  private void handleGetRevisionAndDocTypeAction(PrintWriter out,
1895
                                                              Hashtable params)
1896
  {
1897
    // To store doc parameter
1898
    String [] docs = new String[10];
1899
    // Store a single doc id
1900
    String givenDocId = null;
1901
    // Get docid from parameters
1902
    if (params.containsKey("docid"))
1903
    {
1904
      docs = (String[])params.get("docid");
1905
    }
1906
    // Get first docid form string array
1907
    givenDocId = docs[0];
1908

    
1909
    try
1910
    {
1911
      // Make sure there is a docid
1912
      if (givenDocId == null || givenDocId.equals(""))
1913
      {
1914
        throw new Exception("User didn't specify docid!");
1915
      }//if
1916

    
1917
      // Create a DBUtil object
1918
      DBUtil dbutil = new DBUtil();
1919
      // Get a rev and doctype
1920
      String revAndDocType =
1921
                dbutil.getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1922
      out.println(revAndDocType);
1923

    
1924
    }//try
1925
    catch (Exception e)
1926
    {
1927
      // Handle exception
1928
      out.println("<?xml version=\"1.0\"?>");
1929
      out.println("<error>");
1930
      out.println(e.getMessage());
1931
      out.println("</error>");
1932
    }//catch
1933

    
1934
  }//handleGetRevisionAndDocTypeAction
1935

    
1936
  /**
1937
   * Handle "getaccesscontrol" action.
1938
   * Read Access Control List from db connection in XML format
1939
   */
1940
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
1941
                                       HttpServletResponse response,
1942
                                       String username, String[] groupnames) {
1943

    
1944
    DBConnection dbConn = null;
1945
    int serialNumber = -1;
1946
    String docid = ((String[])params.get("docid"))[0];
1947

    
1948
    try {
1949

    
1950
        // get connection from the pool
1951
        dbConn=DBConnectionPool.
1952
                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
1953
        serialNumber=dbConn.getCheckOutSerialNumber();
1954
        AccessControlList aclobj = new AccessControlList(dbConn);
1955
        String acltext = aclobj.getACL(docid, username, groupnames);
1956
        out.println(acltext);
1957

    
1958
    } catch (Exception e) {
1959
      out.println("<?xml version=\"1.0\"?>");
1960
      out.println("<error>");
1961
      out.println(e.getMessage());
1962
      out.println("</error>");
1963
    } finally {
1964
      // Retrun db connection to pool
1965
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1966
    }
1967

    
1968
  }
1969

    
1970
  /**
1971
   * Handle the "getprincipals" action.
1972
   * Read all principals from authentication scheme in XML format
1973
   */
1974
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1975
                                         String password) {
1976

    
1977

    
1978
    try {
1979

    
1980

    
1981
        AuthSession auth = new AuthSession();
1982
        String principals = auth.getPrincipals(user, password);
1983
        out.println(principals);
1984

    
1985
    } catch (Exception e) {
1986
      out.println("<?xml version=\"1.0\"?>");
1987
      out.println("<error>");
1988
      out.println(e.getMessage());
1989
      out.println("</error>");
1990
    }
1991

    
1992
  }
1993

    
1994
  /**
1995
   * Handle "getdoctypes" action.
1996
   * Read all doctypes from db connection in XML format
1997
   */
1998
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1999
                                       HttpServletResponse response) {
2000

    
2001

    
2002
    try {
2003

    
2004

    
2005
        DBUtil dbutil = new DBUtil();
2006
        String doctypes = dbutil.readDoctypes();
2007
        out.println(doctypes);
2008

    
2009
    } catch (Exception e) {
2010
      out.println("<?xml version=\"1.0\"?>");
2011
      out.println("<error>");
2012
      out.println(e.getMessage());
2013
      out.println("</error>");
2014
    }
2015

    
2016
  }
2017

    
2018
  /**
2019
   * Handle the "getdtdschema" action.
2020
   * Read DTD or Schema file for a given doctype from Metacat catalog system
2021
   */
2022
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2023
                                        HttpServletResponse response) {
2024

    
2025

    
2026
    String doctype = null;
2027
    String[] doctypeArr = (String[])params.get("doctype");
2028

    
2029
    // get only the first doctype specified in the list of doctypes
2030
    // it could be done for all doctypes in that list
2031
    if (doctypeArr != null) {
2032
        doctype = ((String[])params.get("doctype"))[0];
2033
    }
2034

    
2035
    try {
2036

    
2037

    
2038
        DBUtil dbutil = new DBUtil();
2039
        String dtdschema = dbutil.readDTDSchema(doctype);
2040
        out.println(dtdschema);
2041

    
2042
    } catch (Exception e) {
2043
      out.println("<?xml version=\"1.0\"?>");
2044
      out.println("<error>");
2045
      out.println(e.getMessage());
2046
      out.println("</error>");
2047
    }
2048

    
2049
  }
2050

    
2051
  /**
2052
   * Handle the "getdataguide" action.
2053
   * Read Data Guide for a given doctype from db connection in XML format
2054
   */
2055
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
2056
                                        HttpServletResponse response) {
2057

    
2058

    
2059
    String doctype = null;
2060
    String[] doctypeArr = (String[])params.get("doctype");
2061

    
2062
    // get only the first doctype specified in the list of doctypes
2063
    // it could be done for all doctypes in that list
2064
    if (doctypeArr != null) {
2065
        doctype = ((String[])params.get("doctype"))[0];
2066
    }
2067

    
2068
    try {
2069

    
2070

    
2071
        DBUtil dbutil = new DBUtil();
2072
        String dataguide = dbutil.readDataGuide(doctype);
2073
        out.println(dataguide);
2074

    
2075
    } catch (Exception e) {
2076
      out.println("<?xml version=\"1.0\"?>");
2077
      out.println("<error>");
2078
      out.println(e.getMessage());
2079
      out.println("</error>");
2080
    }
2081

    
2082
  }
2083

    
2084
  /**
2085
   * Handle the "getlastdocid" action.
2086
   * Get the latest docid with rev number from db connection in XML format
2087
   */
2088
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2089
                                        HttpServletResponse response) {
2090

    
2091

    
2092
    String scope = ((String[])params.get("scope"))[0];
2093
    if (scope == null) {
2094
        scope = ((String[])params.get("username"))[0];
2095
    }
2096

    
2097
    try {
2098

    
2099

    
2100
        DBUtil dbutil = new DBUtil();
2101
        String lastDocid = dbutil.getMaxDocid(scope);
2102
        out.println("<?xml version=\"1.0\"?>");
2103
        out.println("<lastDocid>");
2104
        out.println("  <scope>" + scope + "</scope>");
2105
        out.println("  <docid>" + lastDocid + "</docid>");
2106
        out.println("</lastDocid>");
2107

    
2108
    } catch (Exception e) {
2109
      out.println("<?xml version=\"1.0\"?>");
2110
      out.println("<error>");
2111
      out.println(e.getMessage());
2112
      out.println("</error>");
2113
    }
2114

    
2115
  }
2116

    
2117
  /**
2118
   * Handle documents passed to metacat that are encoded using the
2119
   * "multipart/form-data" mime type.  This is typically used for uploading
2120
   * data files which may be binary and large.
2121
   */
2122
  private void handleMultipartForm(HttpServletRequest request,
2123
                                   HttpServletResponse response)
2124
  {
2125
    PrintWriter out = null;
2126
    String action = null;
2127

    
2128
    // Parse the multipart form, and save the parameters in a Hashtable and
2129
    // save the FileParts in a hashtable
2130

    
2131
    Hashtable params = new Hashtable();
2132
    Hashtable fileList = new Hashtable();
2133

    
2134
    try {
2135
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
2136
      MultipartParser mp = new MultipartParser(request, 200*1024*1024); //200MB
2137
      Part part;
2138
      while ((part = mp.readNextPart()) != null) {
2139
        String name = part.getName();
2140

    
2141
        if (part.isParam()) {
2142
          // it's a parameter part
2143
          ParamPart paramPart = (ParamPart) part;
2144
          String value = paramPart.getStringValue();
2145
          params.put(name, value);
2146
          if (name.equals("action")) {
2147
            action = value;
2148
          }
2149
        } else if (part.isFile()) {
2150
          // it's a file part
2151
          FilePart filePart = (FilePart) part;
2152
          fileList.put(name, filePart);
2153

    
2154
          // Stop once the first file part is found, otherwise going onto the
2155
          // next part prevents access to the file contents.  So...for upload
2156
          // to work, the datafile must be the last part
2157
          break;
2158
        }
2159
      }
2160
    } catch (IOException ioe) {
2161
      try {
2162
        out = response.getWriter();
2163
      } catch (IOException ioe2) {
2164
        System.err.println("Fatal Error: couldn't get response output stream.");
2165
      }
2166
      out.println("<?xml version=\"1.0\"?>");
2167
      out.println("<error>");
2168
      out.println("Error: problem reading multipart data.");
2169
      out.println("</error>");
2170
    }
2171

    
2172
    // Get the session information
2173
    String username = null;
2174
    String password = null;
2175
    String[] groupnames = null;
2176
    String sess_id = null;
2177

    
2178
    // be aware of session expiration on every request
2179
    HttpSession sess = request.getSession(true);
2180
    if (sess.isNew()) {
2181
      // session expired or has not been stored b/w user requests
2182
      username = "public";
2183
      sess.setAttribute("username", username);
2184
    } else {
2185
      username = (String)sess.getAttribute("username");
2186
      password = (String)sess.getAttribute("password");
2187
      groupnames = (String[])sess.getAttribute("groupnames");
2188
      try {
2189
        sess_id = (String)sess.getId();
2190
      } catch(IllegalStateException ise) {
2191
        System.out.println("error in  handleMultipartForm: this shouldn't " +
2192
                           "happen: the session should be valid: " +
2193
                           ise.getMessage());
2194
      }
2195
    }
2196

    
2197
    // Get the out stream
2198
    try {
2199
          out = response.getWriter();
2200
        } catch (IOException ioe2) {
2201
          util.debugMessage("Fatal Error: couldn't get response "+
2202
                             "output stream.", 30);
2203
        }
2204

    
2205
    if ( action.equals("upload")) {
2206
      if (username != null &&  !username.equals("public")) {
2207
        handleUploadAction(request, out, params, fileList,
2208
                           username, groupnames);
2209
      } else {
2210

    
2211
        out.println("<?xml version=\"1.0\"?>");
2212
        out.println("<error>");
2213
        out.println("Permission denied for " + action);
2214
        out.println("</error>");
2215
      }
2216
    } else {
2217
      /*try {
2218
        out = response.getWriter();
2219
      } catch (IOException ioe2) {
2220
        System.err.println("Fatal Error: couldn't get response output stream.");
2221
      }*/
2222
      out.println("<?xml version=\"1.0\"?>");
2223
      out.println("<error>");
2224
      out.println("Error: action not registered.  Please report this error.");
2225
      out.println("</error>");
2226
    }
2227
    out.close();
2228
  }
2229

    
2230
  /**
2231
   * Handle the upload action by saving the attached file to disk and
2232
   * registering it in the Metacat db
2233
   */
2234
  private void handleUploadAction(HttpServletRequest request,
2235
                                  PrintWriter out,
2236
                                  Hashtable params, Hashtable fileList,
2237
                                  String username, String[] groupnames)
2238
  {
2239
    //PrintWriter out = null;
2240
    //Connection conn = null;
2241
    String action = null;
2242
    String docid = null;
2243

    
2244
    /*response.setContentType("text/xml");
2245
    try
2246
    {
2247
      out = response.getWriter();
2248
    }
2249
    catch (IOException ioe2)
2250
    {
2251
      System.err.println("Fatal Error: couldn't get response output stream.");
2252
    }*/
2253

    
2254
    if (params.containsKey("docid"))
2255
    {
2256
      docid = (String)params.get("docid");
2257
    }
2258

    
2259
    // Make sure we have a docid and datafile
2260
    if (docid != null && fileList.containsKey("datafile")) {
2261

    
2262
      // Get a reference to the file part of the form
2263
      FilePart filePart = (FilePart)fileList.get("datafile");
2264
      String fileName = filePart.getFileName();
2265
      MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2266

    
2267
      // Check if the right file existed in the uploaded data
2268
      if (fileName != null) {
2269

    
2270
        try
2271
        {
2272
           //MetaCatUtil.debugMessage("Upload datafile " + docid +"...", 10);
2273
           //If document get lock data file grant
2274
           if (DocumentImpl.getDataFileLockGrant(docid))
2275
           {
2276
              // register the file in the database (which generates an exception
2277
              //if the docid is not acceptable or other untoward things happen
2278
              DocumentImpl.registerDocument(fileName, "BIN", docid, username);
2279

    
2280
              // Save the data file to disk using "docid" as the name
2281
              dataDirectory.mkdirs();
2282
              File newFile = new File(dataDirectory, docid);
2283
              long size = filePart.writeTo(newFile);
2284

    
2285
              // Force replication this data file
2286
              // To data file, "insert" and update is same
2287
              // The fourth parameter is null. Because it is notification server
2288
              // and this method is in MetaCatServerlet. It is original command,
2289
              // not get force replication info from another metacat
2290
              ForceReplicationHandler frh = new ForceReplicationHandler
2291
                                                (docid, "insert", false, null);
2292

    
2293
              // set content type and other response header fields first
2294
              out.println("<?xml version=\"1.0\"?>");
2295
              out.println("<success>");
2296
              out.println("<docid>" + docid + "</docid>");
2297
              out.println("<size>" + size + "</size>");
2298
              out.println("</success>");
2299
          }//if
2300

    
2301
        } //try
2302
        catch (Exception e)
2303
        {
2304
          out.println("<?xml version=\"1.0\"?>");
2305
          out.println("<error>");
2306
          out.println(e.getMessage());
2307
          out.println("</error>");
2308
        }
2309

    
2310
      }
2311
      else
2312
      {
2313
        // the field did not contain a file
2314
        out.println("<?xml version=\"1.0\"?>");
2315
        out.println("<error>");
2316
        out.println("The uploaded data did not contain a valid file.");
2317
        out.println("</error>");
2318
      }
2319
    }
2320
    else
2321
    {
2322
      // Error bcse docid missing or file missing
2323
      out.println("<?xml version=\"1.0\"?>");
2324
      out.println("<error>");
2325
      out.println("The uploaded data did not contain a valid docid " +
2326
                  "or valid file.");
2327
      out.println("</error>");
2328
    }
2329
  }
2330
  
2331
  /*
2332
   * A method to handle set access action
2333
   */
2334
  private void handleSetAccessAction(PrintWriter out,
2335
                                   Hashtable params,
2336
                                   String username)
2337
  {
2338
    String [] docList        = null;
2339
    String [] principalList  = null;
2340
    String [] permissionList = null;
2341
    String [] permTypeList   = null;
2342
    String [] permOrderList  = null;
2343
    String permission = null;
2344
    String permType   = null;
2345
    String permOrder  = null;
2346
    Vector errorList  = new Vector();
2347
    String error      = null;
2348
    Vector successList = new Vector();
2349
    String success    = null;
2350
   
2351
    
2352
    // Get parameters
2353
    if (params.containsKey("docid")) 
2354
    {
2355
      docList = (String[])params.get("docid");
2356
    }
2357
    if (params.containsKey("principal"))
2358
    {
2359
      principalList = (String[])params.get("principal"); 
2360
    }
2361
    if (params.containsKey("permission"))
2362
    {
2363
      permissionList = (String[])params.get("permission");
2364
      
2365
    }
2366
    if (params.containsKey("permType"))
2367
    {
2368
      permTypeList = (String[])params.get("permType");
2369
    
2370
    }
2371
    if (params.containsKey("permOrder"))
2372
    {
2373
      permOrderList = (String[])params.get("permOrder");
2374
     
2375
    }
2376
   
2377
    // Make sure the parameter is not null
2378
    if (docList == null || principalList == null || permTypeList == null ||
2379
        permissionList == null)
2380
    {
2381
      error = "Please check your parameter list, it should look like: "+
2382
              "?action=setaccess&docid=pipeline.1.1&principal=public" +
2383
              "&permission=read&permType=allow&permOrder=allowFirst";
2384
      errorList.addElement(error);
2385
      outputResponse(successList, errorList, out);
2386
      return;
2387
    }
2388
    
2389
    // Only select first element for permission, type and order
2390
    permission = permissionList[0];
2391
    permType = permTypeList[0];
2392
    if (permOrderList != null)
2393
    {
2394
       permOrder = permOrderList[0];
2395
    }
2396
    
2397
    // Get package doctype set
2398
    Vector packageSet =MetaCatUtil.getOptionList(
2399
                                    MetaCatUtil.getOption("packagedoctypeset"));
2400
    //debug
2401
    if (packageSet != null)
2402
    {
2403
      for (int i = 0; i<packageSet.size(); i++)
2404
      {
2405
        MetaCatUtil.debugMessage("doctype in package set: " + 
2406
                              (String)packageSet.elementAt(i), 34);
2407
      }
2408
    }//if
2409
    
2410
    // handle every accessionNumber
2411
    for (int i=0; i <docList.length; i++)
2412
    {
2413
      String accessionNumber = docList[i];
2414
      String owner = null;
2415
      String publicId = null;
2416
      // Get document owner and public id
2417
      try
2418
      {
2419
        owner = getFieldValueForDoc(accessionNumber, "user_owner");
2420
        publicId = getFieldValueForDoc(accessionNumber, "doctype");
2421
      }//try
2422
      catch (Exception e)
2423
      {
2424
        MetaCatUtil.debugMessage("Error in handleSetAccessAction: " +
2425
                                  e.getMessage(), 30);
2426
        error = "Error in set access control for document - " + accessionNumber+
2427
                 e.getMessage();
2428
        errorList.addElement(error);
2429
        continue;
2430
      }
2431
      //check if user is the owner. Only owner can do owner                            
2432
      if (username == null || owner == null || !username.equals(owner))
2433
      {
2434
        error = "User - " + username + " does not have permission to set " +
2435
                "access control for docid - " + accessionNumber;
2436
        errorList.addElement(error);
2437
        continue;
2438
      }
2439
      
2440
      // If docid publicid is BIN data file or other beta4, 6 package document
2441
      // we could not do set access control. Because we don't want inconsistent
2442
      // to its access docuemnt
2443
      if (publicId!=null && packageSet!=null && packageSet.contains(publicId))
2444
      {
2445
        error = "Could not set access control to document "+ accessionNumber +
2446
                "because it is in a pakcage and it has a access file for it";
2447
        errorList.addElement(error);
2448
        continue;
2449
      }
2450
      
2451
      // for every principle
2452
      for (int j = 0; j<principalList.length; j++)
2453
      {
2454
        String principal = principalList[j];
2455
        try
2456
        {
2457
          //insert permission
2458
          AccessControlForSingleFile accessControl = new 
2459
                           AccessControlForSingleFile(accessionNumber,
2460
                                    principal, permission, permType, permOrder);
2461
          accessControl.insertPermissions();
2462
          success = "Set access control to document "+ accessionNumber +
2463
                    " successfully";
2464
          successList.addElement(success);
2465
        }
2466
        catch (Exception ee)
2467
        {
2468
          MetaCatUtil.debugMessage("Erorr in handleSetAccessAction2: " +
2469
                                   ee.getMessage(), 30);
2470
          error = "Faild to set access control for document " + 
2471
                  accessionNumber + " because " + ee.getMessage();
2472
          errorList.addElement(error);
2473
          continue;
2474
        }
2475
      }//for every principle
2476
    }//for every document 
2477
    outputResponse(successList, errorList, out);
2478
  }//handleSetAccessAction
2479
  
2480
 
2481
  /*
2482
   * A method try to determin a docid's public id, if couldn't find null
2483
   * will be returned.
2484
   */
2485
  private String getFieldValueForDoc(String accessionNumber, String fieldName) 
2486
                                      throws Exception
2487
  {
2488
    if (accessionNumber==null || accessionNumber.equals("") ||fieldName == null
2489
        || fieldName.equals(""))
2490
    {
2491
      throw new Exception("Docid or field name was not specified");
2492
    }
2493
    
2494
    PreparedStatement pstmt = null;
2495
    ResultSet rs = null;
2496
    String fieldValue = null;
2497
    String docId = null;
2498
    DBConnection conn = null;
2499
    int serialNumber = -1;
2500
    
2501
    // get rid of revision if access number has
2502
    docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2503
    try
2504
    {
2505
      //check out DBConnection
2506
      conn=DBConnectionPool.getDBConnection("MetaCatServlet.getPublicIdForDoc");
2507
      serialNumber=conn.getCheckOutSerialNumber();
2508
      pstmt = conn.prepareStatement(
2509
            "SELECT " + fieldName + " FROM xml_documents " +
2510
            "WHERE docid = ? ");
2511
          
2512
      pstmt.setString(1, docId);
2513
      pstmt.execute();
2514
      rs = pstmt.getResultSet();
2515
      boolean hasRow = rs.next();
2516
      int perm = 0;
2517
      if ( hasRow ) 
2518
      {
2519
        fieldValue = rs.getString(1);
2520
      }
2521
      else
2522
      {
2523
        throw new Exception("Could not find document: "+accessionNumber);
2524
      }
2525
    }//try
2526
    catch (Exception e)
2527
    {
2528
      MetaCatUtil.debugMessage("Exception in MetacatServlet.getPublicIdForDoc: "
2529
                               + e.getMessage(), 30);
2530
      throw e;
2531
    }
2532
    finally
2533
    {
2534
      try
2535
      {
2536
        rs.close();
2537
        pstmt.close();
2538
        
2539
      }
2540
      finally
2541
      {
2542
        DBConnectionPool.returnDBConnection(conn, serialNumber);
2543
      }
2544
    }
2545
    return fieldValue;
2546
  }//getFieldValueForDoc
2547
  
2548
  /*
2549
   * A method to output setAccess action result
2550
   */
2551
  private void outputResponse(Vector successList, 
2552
                              Vector errorList,
2553
                              PrintWriter out)
2554
  {
2555
    boolean error = false;
2556
    boolean success = false;
2557
    // Output prolog
2558
    out.println(PROLOG);
2559
    // output success message
2560
    if ( successList != null)
2561
    {
2562
      for (int i = 0; i<successList.size(); i++)
2563
      {
2564
        out.println(SUCCESS);
2565
        out.println((String)successList.elementAt(i));
2566
        out.println(SUCCESSCLOSE);
2567
        success = true;
2568
      }//for
2569
    }//if
2570
    // output error message
2571
    if (errorList != null)
2572
    {
2573
      for (int i = 0; i<errorList.size(); i++)
2574
      {
2575
        out.println(ERROR);
2576
        out.println((String)errorList.elementAt(i));
2577
        out.println(ERRORCLOSE);
2578
        error = true;
2579
      }//for
2580
    }//if
2581
    
2582
    // if no error and no success info, send a error that nothing happened
2583
    if( !error && !success)
2584
    {
2585
      out.println(ERROR);
2586
      out.println("Nothing happend for setaccess action");
2587
      out.println(ERRORCLOSE);
2588
    }
2589
    
2590
  }//outputResponse
2591
}
(37-37/54)