Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: berkley $'
10
 *     '$Date: 2003-07-02 16:03:03 -0700 (Wed, 02 Jul 2003) $'
11
 * '$Revision: 1723 $'
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 Hashtable sessionHash = new Hashtable();
122
  private static final String PROLOG = "<?xml version=\"1.0\"?>";
123
  private static final String SUCCESS = "<success>";
124
  private static final String SUCCESSCLOSE = "</success>";
125
  private static final String ERROR = "<error>";
126
  private static final String ERRORCLOSE = "</error>";
127
  public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
128
  public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
129
  public static final String EML2KEYWORD =":eml";
130

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

    
141
      util = new MetaCatUtil();
142

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

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

    
155

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

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

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

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

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

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

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

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

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

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

    
217

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

    
224

    
225
      while (paramlist.hasMoreElements()) {
226

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

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

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

    
243

    
244
      //handle param is emptpy
245
      if (params.isEmpty() || params == null)
246
      {
247
        return;
248
      }
249

    
250
      //if the user clicked on the input images, decode which image
251
      //was clicked then set the action.
252
      String action = ((String[])params.get("action"))[0];
253
      util.debugMessage("Line 230: Action is: " + action, 1);
254

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

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

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

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

    
295
      // aware of session expiration on every request
296
      }
297
      else
298
      {
299
        HttpSession sess = request.getSession(true);
300
        if (sess.isNew() && !params.containsKey("sessionid")) {
301
          // session expired or has not been stored b/w user requests
302
          username = "public";
303
          sess.setAttribute("username", username);
304
        }
305
        else
306
        {
307
          try
308
          {
309
            if(params.containsKey("sessionid"))
310
            {
311
              sess_id = ((String[])params.get("sessionid"))[0];
312
              if(sessionHash.containsKey(sess_id))
313
              {
314
                sess = (HttpSession)sessionHash.get(sess_id);
315
              }
316
            }
317
            else
318
            {
319
              sess_id = (String)sess.getId();
320
              sessionHash.put(sess_id, sess);
321
            }
322
          }
323
          catch(IllegalStateException ise)
324
          {
325
            System.out.println("error in handleGetOrPost: this shouldn't " +
326
                               "happen: the session should be valid: " +
327
                               ise.getMessage());
328
          }
329

    
330
          username = (String)sess.getAttribute("username");
331
          password = (String)sess.getAttribute("password");
332
          groupnames = (String[])sess.getAttribute("groupnames");
333
        }
334
      }
335

    
336
       // Now that we know the session is valid, we can delegate the request
337
      // to a particular action handler
338
      if(action.equals("query")) {
339
        PrintWriter out = response.getWriter();
340
        handleQuery(out,params,response,username,groupnames,sess_id);
341
        out.close();
342
      } else if(action.equals("squery")) {
343
        PrintWriter out = response.getWriter();
344
        if(params.containsKey("query")) {
345
         handleSQuery(out, params,response,username,groupnames,sess_id);
346
         out.close();
347
        } else {
348
          out.println("Illegal action squery without \"query\" parameter");
349
          out.close();
350
        }
351
      } else if (action.equals("export")) {
352

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

    
462
      //util.closeConnections();
463
      // Close the stream to the client
464
      //out.close();
465
    }
466
  }
467

    
468
  // LOGIN & LOGOUT SECTION
469
  /**
470
   * Handle the login request. Create a new session object.
471
   * Do user authentication through the session.
472
   */
473
  private void handleLoginAction(PrintWriter out, Hashtable params,
474
               HttpServletRequest request, HttpServletResponse response) {
475

    
476
    AuthSession sess = null;
477
    String un = ((String[])params.get("username"))[0];
478
    String pw = ((String[])params.get("password"))[0];
479
    String action = ((String[])params.get("action"))[0];
480
    String qformat = ((String[])params.get("qformat"))[0];
481

    
482
    try {
483
      sess = new AuthSession();
484
    } catch (Exception e) {
485
      System.out.println("error in MetacatServlet.handleLoginAction: " +
486
                          e.getMessage());
487
      out.println(e.getMessage());
488
      return;
489
    }
490
    boolean isValid = sess.authenticate(request, un, pw);
491
    // format and transform the output
492
    if (qformat.equals("xml")) {
493
      response.setContentType("text/xml");
494
      out.println(sess.getMessage());
495
    } else {
496

    
497
      try {
498

    
499
        DBTransform trans = new DBTransform();
500
        response.setContentType("text/html");
501
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
502
                                   "-//W3C//HTML//EN", qformat, out, null);
503

    
504
      } catch(Exception e) {
505

    
506
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
507
                                +e.getMessage(), 30);
508
      }
509

    
510
    // any output is returned
511
    }
512
  }
513

    
514
  /**
515
   * Handle the logout request. Close the connection.
516
   */
517
  private void handleLogoutAction(PrintWriter out, Hashtable params,
518
               HttpServletRequest request, HttpServletResponse response) {
519

    
520
    String qformat = ((String[])params.get("qformat"))[0];
521

    
522
    // close the connection
523
    HttpSession sess = request.getSession(false);
524
    if (sess != null) { sess.invalidate();  }
525

    
526
    // produce output
527
    StringBuffer output = new StringBuffer();
528
    output.append("<?xml version=\"1.0\"?>");
529
    output.append("<logout>");
530
    output.append("User logged out");
531
    output.append("</logout>");
532

    
533
    //format and transform the output
534
    if (qformat.equals("xml")) {
535
      response.setContentType("text/xml");
536
      out.println(output.toString());
537
    } else {
538

    
539
      try {
540

    
541
        DBTransform trans = new DBTransform();
542
        response.setContentType("text/html");
543
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
544
                                   "-//W3C//HTML//EN", qformat, out, null);
545

    
546
      } catch(Exception e) {
547

    
548
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
549
                                  +e.getMessage(), 30);
550
      }
551
    }
552
  }
553
  // END OF LOGIN & LOGOUT SECTION
554

    
555
  // SQUERY & QUERY SECTION
556
  /**
557
   * Retreive the squery xml, execute it and display it
558
   *
559
   * @param out the output stream to the client
560
   * @param params the Hashtable of parameters that should be included
561
   * in the squery.
562
   * @param response the response object linked to the client
563
   * @param conn the database connection
564
   */
565
  protected void handleSQuery(PrintWriter out, Hashtable params,
566
                 HttpServletResponse response, String user, String[] groups,
567
                 String sessionid)
568
  {
569
    String xmlquery = ((String[])params.get("query"))[0];
570
    String qformat = ((String[])params.get("qformat"))[0];
571
    String resultdoc = null;
572
    MetaCatUtil.debugMessage("xmlquery: "+xmlquery, 30);
573
    double startTime = System.currentTimeMillis()/1000;
574
    Hashtable doclist = runQuery(xmlquery, user, groups);
575
    double docListTime = System.currentTimeMillis()/1000;
576
    MetaCatUtil.debugMessage("Time for getting doc list: "
577
                                            +(docListTime-startTime), 30);
578

    
579
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
580
    double toStringTime = System.currentTimeMillis()/1000;
581
    MetaCatUtil.debugMessage("Time to create xml string: "
582
                              +(toStringTime-docListTime), 30);
583
    //format and transform the results
584
    double outPutTime = 0;
585
    if(qformat.equals("xml")) {
586
      response.setContentType("text/xml");
587
      out.println(resultdoc);
588
      outPutTime = System.currentTimeMillis()/1000;
589
      MetaCatUtil.debugMessage("Output time: "+(outPutTime-toStringTime), 30);
590
    } else {
591
      transformResultset(resultdoc, response, out, qformat, sessionid);
592
      outPutTime = System.currentTimeMillis()/1000;
593
      MetaCatUtil.debugMessage("Output time: "+(outPutTime-toStringTime), 30);
594
    }
595
  }
596

    
597
   /**
598
    * Create the xml query, execute it and display the results.
599
    *
600
    * @param out the output stream to the client
601
    * @param params the Hashtable of parameters that should be included
602
    * in the squery.
603
    * @param response the response object linked to the client
604
    */
605
  protected void handleQuery(PrintWriter out, Hashtable params,
606
                 HttpServletResponse response, String user, String[] groups,
607
                 String sessionid)
608
  {
609
    //create the query and run it
610
    String xmlquery = DBQuery.createSQuery(params);
611
    Hashtable doclist = runQuery(xmlquery, user, groups);
612
    String qformat = ((String[])params.get("qformat"))[0];
613
    String resultdoc = null;
614

    
615
    resultdoc = createResultDocument(doclist, transformQuery(params));
616

    
617
    //format and transform the results
618
    if(qformat.equals("xml")) {
619
      response.setContentType("text/xml");
620
      out.println(resultdoc);
621
    } else {
622
      transformResultset(resultdoc, response, out, qformat, sessionid);
623
    }
624
  }
625

    
626
  /**
627
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
628
   * so it can properly be placed in the <query> tag of the resultset.
629
   * This method is overwritable so that other applications can customize
630
   * the structure of what is in the <query> tag.
631
   *
632
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
633
   */
634
  protected String transformQuery(Hashtable params)
635
  {
636
    //DBQuery.createSQuery is a re-calling of a previously called
637
    //function but it is necessary
638
    //so that overriding methods have access to the params hashtable
639
    String xmlquery = DBQuery.createSQuery(params);
640
    //the <?xml version="1.0"?> tag is the first 22 characters of the
641
    xmlquery = xmlquery.trim();
642
    int index = xmlquery.indexOf("?>");
643
    return xmlquery.substring(index + 2, xmlquery.length());
644
  }
645

    
646
  /**
647
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
648
   * string as a param instead of a hashtable.
649
   *
650
   * @param xmlquery a string representing a query.
651
   */
652
  protected String transformQuery(String xmlquery)
653
  {
654
    xmlquery = xmlquery.trim();
655
    int index = xmlquery.indexOf("?>");
656
    return xmlquery.substring(index + 2, xmlquery.length());
657
  }
658

    
659
  /**
660
   * Run the query and return a hashtable of results.
661
   *
662
   * @param xmlquery the query to run
663
   */
664
  private Hashtable runQuery(String xmlquery, String user, String[] groups)
665
  {
666
    Hashtable doclist=null;
667

    
668
    try
669
    {
670

    
671
      DBQuery queryobj = new DBQuery(saxparser);
672
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,groups);
673

    
674
      return doclist;
675
    }
676
    catch (Exception e)
677
    {
678

    
679
      MetaCatUtil.debugMessage("Error in MetacatServlet.runQuery: "
680
                                                      + e.getMessage(), 30);
681
      doclist = null;
682
      return doclist;
683
    }
684
  }
685

    
686
  /**
687
   * Transorms an xml resultset document to html and sends it to the browser
688
   *
689
   * @param resultdoc the string representation of the document that needs
690
   * to be transformed.
691
   * @param response the HttpServletResponse object bound to the client.
692
   * @param out the output stream to the client
693
   * @param qformat the name of the style-set to use for transformations
694
   */
695
  protected void transformResultset(String resultdoc,
696
                                    HttpServletResponse response,
697
                                    PrintWriter out, String qformat,
698
                                    String sessionid)
699
  {
700

    
701
    try {
702

    
703
      DBTransform trans = new DBTransform();
704
      response.setContentType("text/html");
705
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
706
                                 "-//W3C//HTML//EN", qformat, out, null,
707
                                 sessionid);
708

    
709
    }
710
    catch(Exception e)
711
    {
712

    
713
      MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
714
                                +e.getMessage(), 30);
715
    }
716
  }
717

    
718
  /**
719
   * Transforms a hashtable of documents to an xml or html result.
720
   *
721
   * @param doclist- the hashtable to transform
722
   * @param xmlquery- the query that returned the doclist result
723
   */
724
  protected String createResultDocument(Hashtable doclist, String xmlquery)
725
  {
726
    // Create a buffer to hold the xml result
727
    StringBuffer resultset = new StringBuffer();
728

    
729
    // Print the resulting root nodes
730
    String docid = null;
731
    String document = null;
732
    resultset.append("<?xml version=\"1.0\"?>\n");
733
    resultset.append("<resultset>\n");
734

    
735
    resultset.append("  <query>" + xmlquery + "</query>");
736

    
737
    if(doclist != null)
738
    {
739
      Enumeration doclistkeys = doclist.keys();
740
      while (doclistkeys.hasMoreElements())
741
      {
742
        docid = (String)doclistkeys.nextElement();
743
        document = (String)doclist.get(docid);
744
        resultset.append("  <document>" + document + "</document>");
745
      }
746
    }
747

    
748
    resultset.append("</resultset>");
749
    return resultset.toString();
750
  }
751
  // END OF SQUERY & QUERY SECTION
752

    
753
 //Exoport section
754
 /**
755
   * Handle the "export" request of data package from Metacat in zip format
756
   * @param params the Hashtable of HTTP request parameters
757
   * @param response the HTTP response object linked to the client
758
   * @param user the username sent the request
759
   * @param groups the user's groupnames
760
   */
761
  private void handleExportAction(Hashtable params,
762
    HttpServletResponse response, String user, String[] groups, String passWord)
763
  {
764
    // Output stream
765
    ServletOutputStream out = null;
766
    // Zip output stream
767
    ZipOutputStream zOut = null;
768
    DocumentImpl docImpls=null;
769
    DBQuery queryObj=null;
770

    
771
    String[] docs = new String[10];
772
    String docId = "";
773

    
774
    try
775
    {
776
      // read the params
777
      if (params.containsKey("docid"))
778
      {
779
        docs = (String[])params.get("docid");
780
      }//if
781
      // Create a DBuery to handle export
782
      queryObj = new DBQuery(saxparser);
783
      // Get the docid
784
      docId=docs[0];
785
      // Make sure the client specify docid
786
      if (docId == null || docId.equals(""))
787
      {
788
        response.setContentType("text/xml"); //MIME type
789
        // Get a printwriter
790
        PrintWriter pw = response.getWriter();
791
        // Send back message
792
        pw.println("<?xml version=\"1.0\"?>");
793
        pw.println("<error>");
794
        pw.println("You didn't specify requested docid");
795
        pw.println("</error>");
796
        // Close printwriter
797
        pw.close();
798
        return;
799
      }//if
800
      // Get output stream
801
      out = response.getOutputStream();
802
      response.setContentType("application/zip"); //MIME type
803
      zOut = new ZipOutputStream(out);
804
      zOut =queryObj.getZippedPackage(docId, out, user, groups, passWord);
805
      zOut.finish(); //terminate the zip file
806
      zOut.close();  //close the zip stream
807

    
808
    }//try
809
    catch (Exception e)
810
    {
811
      try
812
      {
813
        response.setContentType("text/xml"); //MIME type
814
        // Send error message back
815
        if (out != null)
816
        {
817
            PrintWriter pw = new PrintWriter(out);
818
            pw.println("<?xml version=\"1.0\"?>");
819
            pw.println("<error>");
820
            pw.println(e.getMessage());
821
            pw.println("</error>");
822
            // Close printwriter
823
            pw.close();
824
            // Close output stream
825
            out.close();
826
        }//if
827
        // Close zip output stream
828
        if ( zOut != null )
829
        {
830
          zOut.close();
831
        }//if
832
      }//try
833
      catch (IOException ioe)
834
      {
835
        MetaCatUtil.debugMessage("Problem with the servlet output " +
836
                           "in MetacatServlet.handleExportAction: " +
837
                           ioe.getMessage(), 30);
838
      }//catch
839

    
840
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleExportAction: " +
841
                         e.getMessage(), 30);
842
      e.printStackTrace(System.out);
843

    
844
    }//catch
845

    
846
  }//handleExportAction
847

    
848

    
849
   //read inline data section
850
 /**
851
   * In eml2 document, the xml can have inline data and data was stripped off
852
   * and store in file system. This action can be used to read inline data only
853
   * @param params the Hashtable of HTTP request parameters
854
   * @param response the HTTP response object linked to the client
855
   * @param user the username sent the request
856
   * @param groups the user's groupnames
857
   */
858
  private void handleReadInlineDataAction(Hashtable params,
859
                                          HttpServletResponse response,
860
                                          String user, String passWord,
861
                                          String[] groups)
862
  {
863
    String[] docs = new String[10];
864
    String inlineDataId = null;
865
    String docId = "";
866
    ServletOutputStream out = null;
867

    
868
    try
869
    {
870
      // read the params
871
      if (params.containsKey("inlinedataid"))
872
      {
873
        docs = (String[])params.get("inlinedataid");
874
      }//if
875
      // Get the docid
876
      inlineDataId=docs[0];
877
      // Make sure the client specify docid
878
      if (inlineDataId == null || inlineDataId.equals(""))
879
      {
880
        throw new Exception("You didn't specify requested inlinedataid");
881
      }//if
882

    
883
      // check for permission
884
      docId = MetaCatUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
885
      PermissionController controller = new PermissionController(docId);
886
      // check top level read permission
887
      if (!controller.hasPermission(user, groups,
888
                                    AccessControlInterface.READSTRING))
889
      {
890
          throw new Exception("User "+ user + " doesn't have permission "+
891
                              " to read document " + docId);
892
      }//if
893
      // if the document has subtree control, we need to check subtree control
894
      else if(controller.hasSubTreeAccessControl())
895
      {
896
        // get node id for inlinedata
897
        long nodeId=getInlineDataNodeId(inlineDataId, docId);
898
        if (!controller.hasPermissionForSubTreeNode(user, groups,
899
                                     AccessControlInterface.READSTRING, nodeId))
900
        {
901
           throw new Exception("User "+ user + " doesn't have permission "+
902
                              " to read inlinedata " + inlineDataId);
903
        }//if
904

    
905
      }//else
906

    
907
      // Get output stream
908
      out = response.getOutputStream();
909
      // read the inline data from the file
910
      String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
911
      File lineData = new File(inlinePath, inlineDataId);
912
      FileInputStream input = new FileInputStream(lineData);
913
      byte [] buffer = new byte[4*1024];
914
      int bytes = input.read(buffer);
915
      while (bytes != -1)
916
      {
917
        out.write(buffer, 0, bytes);
918
        bytes = input.read(buffer);
919
      }
920
      out.close();
921

    
922
    }//try
923
    catch (Exception e)
924
    {
925
      try
926
      {
927
        PrintWriter pw = null;
928
        // Send error message back
929
        if (out != null)
930
        {
931
            pw = new PrintWriter(out);
932
        }//if
933
        else
934
        {
935
          pw = response.getWriter();
936
        }
937
         pw.println("<?xml version=\"1.0\"?>");
938
         pw.println("<error>");
939
         pw.println(e.getMessage());
940
         pw.println("</error>");
941
         // Close printwriter
942
         pw.close();
943
         // Close output stream if out is not null
944
         if (out != null)
945
         {
946
           out.close();
947
         }
948
     }//try
949
     catch (IOException ioe)
950
     {
951
        MetaCatUtil.debugMessage("Problem with the servlet output " +
952
                           "in MetacatServlet.handleExportAction: " +
953
                           ioe.getMessage(), 30);
954
     }//catch
955

    
956
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadInlineDataAction: "
957
                                + e.getMessage(), 30);
958

    
959
    }//catch
960

    
961
  }//handleReadInlineDataAction
962

    
963
  /*
964
   * Get the nodeid from xml_nodes for the inlinedataid
965
   */
966
  private long getInlineDataNodeId(String inLineDataId, String docId)
967
                                   throws SQLException
968
  {
969
    long nodeId = 0;
970
    String INLINE = "inline";
971
    boolean hasRow;
972
    PreparedStatement pStmt = null;
973
    DBConnection conn = null;
974
    int serialNumber = -1;
975
    String sql ="SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? " +
976
                "AND nodetype='TEXT' AND parentnodeid IN " +
977
                "(SELECT nodeid FROM xml_nodes WHERE docid=? AND " +
978
                "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
979

    
980
    try
981
    {
982
      //check out DBConnection
983
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
984
      serialNumber=conn.getCheckOutSerialNumber();
985

    
986
      pStmt = conn.prepareStatement(sql);
987
      //bind value
988
      pStmt.setString(1, docId);//docid
989
      pStmt.setString(2, inLineDataId);//inlinedataid
990
      pStmt.setString(3, docId);
991
      // excute query
992
      pStmt.execute();
993
      ResultSet rs = pStmt.getResultSet();
994
      hasRow=rs.next();
995
      // get result
996
      if (hasRow)
997
      {
998
        nodeId = rs.getLong(1);
999
      }//if
1000

    
1001
    }//try
1002
    catch (SQLException e)
1003
    {
1004
      throw e;
1005
    }
1006
    finally
1007
    {
1008
      try
1009
      {
1010
        pStmt.close();
1011
      }
1012
      finally
1013
      {
1014
        DBConnectionPool.returnDBConnection(conn, serialNumber);
1015
      }
1016
    }
1017
    MetaCatUtil.debugMessage("The nodeid for inlinedataid " + inLineDataId +
1018
                             " is: "+nodeId, 35);
1019
    return nodeId;
1020
  }
1021

    
1022

    
1023

    
1024
  // READ SECTION
1025
  /**
1026
   * Handle the "read" request of metadata/data files from Metacat
1027
   * or any files from Internet;
1028
   * transformed metadata XML document into HTML presentation if requested;
1029
   * zip files when more than one were requested.
1030
   *
1031
   * @param params the Hashtable of HTTP request parameters
1032
   * @param response the HTTP response object linked to the client
1033
   * @param user the username sent the request
1034
   * @param groups the user's groupnames
1035
   */
1036
  private void handleReadAction(Hashtable params, HttpServletResponse response,
1037
                                String user, String passWord, String[] groups)
1038
  {
1039
    ServletOutputStream out = null;
1040
    ZipOutputStream zout = null;
1041
    PrintWriter pw = null;
1042
    boolean zip = false;
1043
    boolean withInlineData = true;
1044

    
1045
    try {
1046
      String[] docs = new String[0];
1047
      String docid = "";
1048
      String qformat = "";
1049
      String abstrpath = null;
1050

    
1051
      // read the params
1052
      if (params.containsKey("docid")) {
1053
        docs = (String[])params.get("docid");
1054
      }
1055
      if (params.containsKey("qformat")) {
1056
        qformat = ((String[])params.get("qformat"))[0];
1057
      }
1058
      // the param for only metadata (eml)
1059
      if (params.containsKey("inlinedata"))
1060
      {
1061

    
1062
        String inlineData = ((String[])params.get("inlinedata"))[0];
1063
        if (inlineData.equalsIgnoreCase("false"))
1064
        {
1065
          withInlineData = false;
1066
        }
1067
      }
1068
      if (params.containsKey("abstractpath")) {
1069
        abstrpath = ((String[])params.get("abstractpath"))[0];
1070
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
1071
          viewAbstract(response, abstrpath, docs[0]);
1072
          return;
1073
        }
1074
      }
1075
      if ( (docs.length > 1) || qformat.equals("zip") ) {
1076
        zip = true;
1077
        out = response.getOutputStream();
1078
        response.setContentType("application/zip"); //MIME type
1079
        zout = new ZipOutputStream(out);
1080
      }
1081
      // go through the list of docs to read
1082
      for (int i=0; i < docs.length; i++ ) {
1083
        try {
1084

    
1085
          URL murl = new URL(docs[i]);
1086
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
1087
          // case docid="http://.../?docid=aaa"
1088
          // or docid="metacat://.../?docid=bbb"
1089
          if (murlQueryStr.containsKey("docid")) {
1090
            // get only docid, eliminate the rest
1091
            docid = (String)murlQueryStr.get("docid");
1092
            if ( zip ) {
1093
              addDocToZip(docid, zout, user, groups);
1094
            } else {
1095
              readFromMetacat(response, docid, qformat, abstrpath,
1096
                              user, groups, zip, zout, withInlineData, params);
1097
            }
1098

    
1099
          // case docid="http://.../filename"
1100
          } else {
1101
            docid = docs[i];
1102
            if ( zip ) {
1103
              addDocToZip(docid, zout, user, groups);
1104
            } else {
1105
              readFromURLConnection(response, docid);
1106
            }
1107
          }
1108

    
1109
        // case docid="ccc"
1110
        } catch (MalformedURLException mue) {
1111
          docid = docs[i];
1112
          if ( zip ) {
1113
            addDocToZip(docid, zout, user, groups);
1114
          } else {
1115
            readFromMetacat(response, docid, qformat, abstrpath,
1116
                            user, groups, zip, zout, withInlineData, params);
1117
          }
1118
        }
1119

    
1120
      } /* end for */
1121

    
1122
      if ( zip ) {
1123
        zout.finish(); //terminate the zip file
1124
        zout.close();  //close the zip stream
1125
      }
1126

    
1127

    
1128
    }
1129
    // To handle doc not found exception
1130
    catch (McdbDocNotFoundException notFoundE)
1131
    {
1132
      // the docid which didn't be found
1133
      String notFoundDocId = notFoundE.getUnfoundDocId();
1134
      String notFoundRevision = notFoundE.getUnfoundRevision();
1135
      MetaCatUtil.debugMessage("Missed id: "+ notFoundDocId, 30);
1136
      MetaCatUtil.debugMessage("Missed rev: "+ notFoundRevision, 30);
1137
      try
1138
      {
1139
        // read docid from remote server
1140
        readFromRemoteMetaCat(response, notFoundDocId, notFoundRevision,
1141
                                              user, passWord, out, zip, zout);
1142
        // Close zout outputstream
1143
        if ( zout != null)
1144
        {
1145
          zout.close();
1146
        }
1147
        // close output stream
1148
        if (out != null)
1149
        {
1150
          out.close();
1151
        }
1152

    
1153
      }//try
1154
      catch ( Exception exc)
1155
      {
1156
        MetaCatUtil.debugMessage("Erorr in MetacatServlet.hanldReadAction: "+
1157
                                      exc.getMessage(), 30);
1158
        try
1159
        {
1160
          if (out != null)
1161
          {
1162
            response.setContentType("text/xml");
1163
            // Send back error message by printWriter
1164
            pw = new PrintWriter(out);
1165
            pw.println("<?xml version=\"1.0\"?>");
1166
            pw.println("<error>");
1167
            pw.println(notFoundE.getMessage());
1168
            pw.println("</error>");
1169
            pw.close();
1170
            out.close();
1171

    
1172
          }
1173
          else
1174
          {
1175
           response.setContentType("text/xml"); //MIME type
1176
           // Send back error message if out = null
1177
           if (pw == null)
1178
           {
1179
             // If pw is null, open the respnose
1180
            pw = response.getWriter();
1181
           }
1182
           pw.println("<?xml version=\"1.0\"?>");
1183
           pw.println("<error>");
1184
           pw.println(notFoundE.getMessage());
1185
           pw.println("</error>");
1186
           pw.close();
1187
        }
1188
        // close zout
1189
        if ( zout != null )
1190
        {
1191
          zout.close();
1192
        }
1193
        }//try
1194
        catch (IOException ie)
1195
        {
1196
          MetaCatUtil.debugMessage("Problem with the servlet output " +
1197
                           "in MetacatServlet.handleReadAction: " +
1198
                           ie.getMessage(), 30);
1199
        }//cathch
1200
      }//catch
1201
    }// catch McdbDocNotFoundException
1202
    catch (Exception e)
1203
    {
1204
      try {
1205

    
1206
        if (out != null) {
1207
            response.setContentType("text/xml"); //MIME type
1208
            pw = new PrintWriter(out);
1209
            pw.println("<?xml version=\"1.0\"?>");
1210
            pw.println("<error>");
1211
            pw.println(e.getMessage());
1212
            pw.println("</error>");
1213
            pw.close();
1214
            out.close();
1215
        }
1216
        else
1217
        {
1218
           response.setContentType("text/xml"); //MIME type
1219
           // Send back error message if out = null
1220
           if ( pw == null)
1221
           {
1222
            pw = response.getWriter();
1223
           }
1224
           pw.println("<?xml version=\"1.0\"?>");
1225
           pw.println("<error>");
1226
           pw.println(e.getMessage());
1227
           pw.println("</error>");
1228
           pw.close();
1229

    
1230
        }
1231
        // Close zip output stream
1232
        if ( zout != null ) { zout.close(); }
1233

    
1234
      } catch (IOException ioe) {
1235
        MetaCatUtil.debugMessage("Problem with the servlet output " +
1236
                           "in MetacatServlet.handleReadAction: " +
1237
                           ioe.getMessage(), 30);
1238
        ioe.printStackTrace(System.out);
1239

    
1240
      }
1241

    
1242
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadAction: " +
1243
                               e.getMessage(), 30);
1244
      //e.printStackTrace(System.out);
1245
    }
1246

    
1247
  }
1248

    
1249
  // read metadata or data from Metacat
1250
  private void readFromMetacat(HttpServletResponse response, String docid,
1251
                               String qformat, String abstrpath, String user,
1252
                               String[] groups, boolean zip,
1253
                               ZipOutputStream zout, boolean withInlineData,
1254
                               Hashtable params)
1255
               throws ClassNotFoundException, IOException, SQLException,
1256
                      McdbException, Exception
1257
  {
1258

    
1259
    try {
1260

    
1261

    
1262
      DocumentImpl doc = new DocumentImpl(docid);
1263

    
1264
      //check the permission for read
1265
      if (!doc.hasReadPermission(user, groups, docid))
1266
      {
1267
        Exception e = new Exception("User " + user + " does not have permission"
1268
                       +" to read the document with the docid " + docid);
1269

    
1270
        throw e;
1271
      }
1272

    
1273
      if ( doc.getRootNodeID() == 0 ) {
1274
        // this is data file
1275
        String filepath = util.getOption("datafilepath");
1276
        if(!filepath.endsWith("/")) {
1277
          filepath += "/";
1278
        }
1279
        String filename = filepath + docid;
1280
        FileInputStream fin = null;
1281
        fin = new FileInputStream(filename);
1282

    
1283
        //MIME type
1284
        String contentType = getServletContext().getMimeType(filename);
1285
        if (contentType == null)
1286
        {
1287
          ContentTypeProvider provider = new ContentTypeProvider(docid);
1288
          contentType = provider.getContentType();
1289
          MetaCatUtil.debugMessage("Final contenttype is: "+ contentType, 30);
1290
        }
1291

    
1292
        response.setContentType(contentType);
1293
        // if we decide to use "application/octet-stream" for all data returns
1294
        // response.setContentType("application/octet-stream");
1295

    
1296
        try {
1297

    
1298
          ServletOutputStream out = response.getOutputStream();
1299
          byte[] buf = new byte[4 * 1024]; // 4K buffer
1300
          int b = fin.read(buf);
1301
          while (b != -1) {
1302
            out.write(buf, 0, b);
1303
            b = fin.read(buf);
1304
          }
1305
        } finally {
1306
          if (fin != null) fin.close();
1307
        }
1308

    
1309
      } else {
1310
        // this is metadata doc
1311
        if ( qformat.equals("xml") ) {
1312

    
1313
          // set content type first
1314
          response.setContentType("text/xml");   //MIME type
1315
          PrintWriter out = response.getWriter();
1316
          doc.toXml(out, user, groups, withInlineData);
1317
        } else {
1318
          response.setContentType("text/html");  //MIME type
1319
          PrintWriter out = response.getWriter();
1320

    
1321
          // Look up the document type
1322
          String doctype = doc.getDoctype();
1323
          // Transform the document to the new doctype
1324
          DBTransform dbt = new DBTransform();
1325
          dbt.transformXMLDocument(doc.toString(user, groups, withInlineData),
1326
                                   doctype,"-//W3C//HTML//EN",
1327
                                   qformat, out, params);
1328
        }
1329

    
1330
      }
1331
    }
1332
    catch (Exception except)
1333
    {
1334
      throw except;
1335

    
1336
    }
1337

    
1338
  }
1339

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

    
1370
    // this is http url
1371
    URL url = new URL(docid);
1372
    BufferedInputStream bis = null;
1373
    try {
1374
      bis = new BufferedInputStream(url.openStream());
1375
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1376
      int b = bis.read(buf);
1377
      while (b != -1) {
1378
        out.write(buf, 0, b);
1379
        b = bis.read(buf);
1380
      }
1381
    } finally {
1382
      if (bis != null) bis.close();
1383
    }
1384

    
1385
  }
1386

    
1387
  // read file/doc and write to ZipOutputStream
1388
  private void addDocToZip(String docid, ZipOutputStream zout,
1389
                              String user, String[] groups)
1390
               throws ClassNotFoundException, IOException, SQLException,
1391
                      McdbException, Exception
1392
  {
1393
    byte[] bytestring = null;
1394
    ZipEntry zentry = null;
1395

    
1396
    try {
1397
      URL url = new URL(docid);
1398

    
1399
      // this http url; read from URLConnection; add to zip
1400
      zentry = new ZipEntry(docid);
1401
      zout.putNextEntry(zentry);
1402
      BufferedInputStream bis = null;
1403
      try {
1404
        bis = new BufferedInputStream(url.openStream());
1405
        byte[] buf = new byte[4 * 1024]; // 4K buffer
1406
        int b = bis.read(buf);
1407
        while(b != -1) {
1408
          zout.write(buf, 0, b);
1409
          b = bis.read(buf);
1410
        }
1411
      } finally {
1412
        if (bis != null) bis.close();
1413
      }
1414
      zout.closeEntry();
1415

    
1416
    } catch (MalformedURLException mue) {
1417

    
1418
      // this is metacat doc (data file or metadata doc)
1419

    
1420
      try {
1421

    
1422
        DocumentImpl doc = new DocumentImpl(docid);
1423

    
1424
        //check the permission for read
1425
        if (!doc.hasReadPermission(user, groups, docid))
1426
        {
1427
          Exception e = new Exception("User " + user + " does not have "
1428
                    +"permission to read the document with the docid " + docid);
1429

    
1430
          throw e;
1431
        }
1432

    
1433
        if ( doc.getRootNodeID() == 0 ) {
1434
          // this is data file; add file to zip
1435
          String filepath = util.getOption("datafilepath");
1436
          if(!filepath.endsWith("/")) {
1437
            filepath += "/";
1438
          }
1439
          String filename = filepath + docid;
1440
          FileInputStream fin = null;
1441
          fin = new FileInputStream(filename);
1442
          try {
1443

    
1444
            zentry = new ZipEntry(docid);
1445
            zout.putNextEntry(zentry);
1446
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1447
            int b = fin.read(buf);
1448
            while (b != -1) {
1449
              zout.write(buf, 0, b);
1450
              b = fin.read(buf);
1451
            }
1452
          } finally {
1453
            if (fin != null) fin.close();
1454
          }
1455
          zout.closeEntry();
1456

    
1457
        } else {
1458
          // this is metadata doc; add doc to zip
1459
          bytestring = doc.toString().getBytes();
1460
          zentry = new ZipEntry(docid + ".xml");
1461
          zentry.setSize(bytestring.length);
1462
          zout.putNextEntry(zentry);
1463
          zout.write(bytestring, 0, bytestring.length);
1464
          zout.closeEntry();
1465
        }
1466
      } catch (Exception except) {
1467
        throw except;
1468

    
1469
      }
1470

    
1471
    }
1472

    
1473
  }
1474

    
1475
  // view abstract within document
1476
  private void viewAbstract(HttpServletResponse response,
1477
                            String abstractpath, String docid)
1478
               throws ClassNotFoundException, IOException, SQLException,
1479
                      McdbException, Exception
1480
  {
1481

    
1482
    PrintWriter out =null;
1483
    try {
1484

    
1485
      response.setContentType("text/html");  //MIME type
1486
      out = response.getWriter();
1487
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid);
1488
      out.println("<html><head><title>Abstract</title></head>");
1489
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
1490
      for (int i=0; i<abstracts.length; i++) {
1491
        out.println("<p>" + (String)abstracts[i] + "</p>");
1492
      }
1493
      out.println("</body></html>");
1494

    
1495
    } catch (Exception e) {
1496
       out.println("<?xml version=\"1.0\"?>");
1497
       out.println("<error>");
1498
       out.println(e.getMessage());
1499
       out.println("</error>");
1500

    
1501

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

    
1541
  // END OF READ SECTION
1542

    
1543

    
1544

    
1545
  // INSERT/UPDATE SECTION
1546
  /**
1547
   * Handle the database putdocument request and write an XML document
1548
   * to the database connection
1549
   */
1550
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1551
               String user, String[] groups) {
1552

    
1553
    DBConnection dbConn = null;
1554
    int serialNumber = -1;
1555

    
1556
    try {
1557
      // Get the document indicated
1558
      String[] doctext = (String[])params.get("doctext");
1559

    
1560
      String pub = null;
1561
      if (params.containsKey("public")) {
1562
        pub = ((String[])params.get("public"))[0];
1563
      }
1564

    
1565
      StringReader dtd = null;
1566
      if (params.containsKey("dtdtext")) {
1567
        String[] dtdtext = (String[])params.get("dtdtext");
1568
        try {
1569
          if ( !dtdtext[0].equals("") ) {
1570
            dtd = new StringReader(dtdtext[0]);
1571
          }
1572
        } catch (NullPointerException npe) {}
1573
      }
1574

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

    
1611
        xml = new StringReader(doctext[0]);
1612

    
1613
        String[] action = (String[])params.get("action");
1614
        String[] docid = (String[])params.get("docid");
1615
        String newdocid = null;
1616

    
1617
        String doAction = null;
1618
        if (action[0].equals("insert")) {
1619
          doAction = "INSERT";
1620
        } else if (action[0].equals("update")) {
1621
          doAction = "UPDATE";
1622
        }
1623

    
1624
        try
1625
        {
1626
          // get a connection from the pool
1627
          dbConn=DBConnectionPool.
1628
                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1629
          serialNumber=dbConn.getCheckOutSerialNumber();
1630

    
1631

    
1632
          // write the document to the database
1633
          try
1634
          {
1635
            String accNumber = docid[0];
1636
            MetaCatUtil.debugMessage(""+ doAction + " " + accNumber +"...", 10);
1637
            if (accNumber.equals(""))
1638
            {
1639
              accNumber = null;
1640
            }//if
1641
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1642
                                          accNumber, user, groups);
1643

    
1644
          }//try
1645
          catch (NullPointerException npe)
1646
          {
1647
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1648
                                          null, user, groups);
1649
          }//catch
1650

    
1651
        }//try
1652
        finally
1653
        {
1654
          // Return db connection
1655
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1656
        }
1657

    
1658
        // set content type and other response header fields first
1659
        //response.setContentType("text/xml");
1660
        out.println("<?xml version=\"1.0\"?>");
1661
        out.println("<success>");
1662
        out.println("<docid>" + newdocid + "</docid>");
1663
        out.println("</success>");
1664

    
1665
      }
1666
      catch (NullPointerException npe)
1667
      {
1668
        //response.setContentType("text/xml");
1669
        out.println("<?xml version=\"1.0\"?>");
1670
        out.println("<error>");
1671
        out.println(npe.getMessage());
1672
        out.println("</error>");
1673
      }
1674
    }
1675
    catch (Exception e)
1676
    {
1677
      //response.setContentType("text/xml");
1678
      out.println("<?xml version=\"1.0\"?>");
1679
      out.println("<error>");
1680
      out.println(e.getMessage());
1681
      out.println("</error>");
1682
    }
1683
  }
1684

    
1685
  /**
1686
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1687
   * in order to decide whether to use validation parser
1688
   */
1689
  private static boolean needDTDValidation(String xmltext) throws IOException {
1690

    
1691
    StringReader xmlreader = new StringReader(xmltext);
1692
    StringBuffer cbuff = new StringBuffer();
1693
    java.util.Stack st = new java.util.Stack();
1694
    boolean validate = false;
1695
    int c;
1696
    int inx;
1697

    
1698
    // read from the stream until find the keywords
1699
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1700
      cbuff.append((char)c);
1701

    
1702
      // "<!DOCTYPE" keyword is found; put it in the stack
1703
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1704
        cbuff = new StringBuffer();
1705
        st.push("<!DOCTYPE");
1706
      }
1707
      // "PUBLIC" keyword is found; put it in the stack
1708
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1709
        cbuff = new StringBuffer();
1710
        st.push("PUBLIC");
1711
      }
1712
      // "SYSTEM" keyword is found; put it in the stack
1713
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1714
        cbuff = new StringBuffer();
1715
        st.push("SYSTEM");
1716
      }
1717
      // ">" character is found; put it in the stack
1718
      // ">" is found twice: fisrt from <?xml ...?>
1719
      // and second from <!DOCTYPE ... >
1720
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1721
        cbuff = new StringBuffer();
1722
        st.push(">");
1723
      }
1724
    }
1725

    
1726
    // close the stream
1727
    xmlreader.close();
1728

    
1729
    // check the stack whether it contains the keywords:
1730
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1731
    if ( st.size() == 4 ) {
1732
      if ( ((String)st.pop()).equals(">") &&
1733
           ( ((String)st.peek()).equals("PUBLIC") |
1734
             ((String)st.pop()).equals("SYSTEM") ) &&
1735
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1736
        validate = true;
1737
      }
1738
    }
1739

    
1740
    MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1741
    return validate;
1742
  }
1743
  // END OF INSERT/UPDATE SECTION
1744

    
1745
  /* check if the xml string contains key words to specify schema loocation*/
1746
  private boolean needSchemaValidation(String xml)
1747
  {
1748
    boolean needSchemaValidate =false;
1749
    if (xml == null)
1750
    {
1751
      MetaCatUtil.debugMessage("Validation for schema is " +
1752
                               needSchemaValidate, 10);
1753
      return needSchemaValidate;
1754
    }
1755
    String targetLine = getSchemaLine(xml);
1756
    // to see if the second line contain some keywords
1757
    if (targetLine != null && (targetLine.indexOf(SCHEMALOCATIONKEYWORD) != -1||
1758
             targetLine.indexOf(NONAMESPACELOCATION) != -1 ))
1759
    {
1760
      // if contains schema location key word, should be validate
1761
      needSchemaValidate = true;
1762
    }
1763

    
1764
    MetaCatUtil.debugMessage("Validation for schema is " +
1765
                             needSchemaValidate, 10);
1766
    return needSchemaValidate;
1767

    
1768
  }
1769

    
1770
   /* check if the xml string contains key words to specify schema loocation*/
1771
  private boolean needEml2Validation(String xml)
1772
  {
1773
    boolean needEml2Validate =false;
1774
    String emlNameSpace = "=\""+DocumentImpl.EMLNAMESPACE+"\"";
1775
    if (xml == null)
1776
    {
1777
      MetaCatUtil.debugMessage("Validation for schema is " +
1778
                               needEml2Validate, 10);
1779
      return needEml2Validate;
1780
    }
1781
    String targetLine = getSchemaLine(xml);
1782

    
1783
    if (targetLine != null && targetLine.indexOf(EML2KEYWORD) != -1 &&
1784
        targetLine.indexOf(emlNameSpace) != -1)
1785
    {
1786
      // if contains schema location key word, should be validate
1787
      needEml2Validate = true;
1788
    }
1789

    
1790
    MetaCatUtil.debugMessage("Validation for eml is " +
1791
                             needEml2Validate, 10);
1792
    return needEml2Validate;
1793

    
1794
  }
1795

    
1796
  private String getSchemaLine(String xml)
1797
  {
1798
    // find the line
1799
    String secondLine = null;
1800
    int count =0;
1801
    int endIndex = 0;
1802
    int startIndex = 0;
1803
    final int TARGETNUM = 2;
1804
    for (int i=0; i<xml.length(); i++)
1805
    {
1806
      // didn't count comment
1807
      if (xml.charAt(i) =='<' && xml.charAt(i+1) != '!')
1808
      {
1809
        count ++;
1810
        //find start index
1811
        if (count == TARGETNUM)
1812
        {
1813
          startIndex = i;
1814
        }
1815
      }//if
1816
      // find the end index
1817
      if (count== TARGETNUM && xml.charAt(i) =='>')
1818
      {
1819
        endIndex = i;
1820
        break;
1821
      }//if
1822
    }//for
1823
    // get the second line string
1824
    MetaCatUtil.debugMessage("The start index for second line: "+startIndex, 25);
1825
    MetaCatUtil.debugMessage("The end index for second line: "+endIndex, 25);
1826
    if (startIndex != 0 && endIndex != 0)
1827
    {
1828
      secondLine = xml.substring(startIndex+1, endIndex);
1829

    
1830
    }//if
1831
    MetaCatUtil.debugMessage("the second line string is: "+secondLine, 25);
1832
    return secondLine;
1833
  }
1834

    
1835
  // DELETE SECTION
1836
  /**
1837
   * Handle the database delete request and delete an XML document
1838
   * from the database connection
1839
   */
1840
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1841
               HttpServletResponse response, String user, String[] groups) {
1842

    
1843
    String[] docid = (String[])params.get("docid");
1844

    
1845
    // delete the document from the database
1846
    try {
1847

    
1848
                                      // NOTE -- NEED TO TEST HERE
1849
                                      // FOR EXISTENCE OF DOCID PARAM
1850
                                      // BEFORE ACCESSING ARRAY
1851
      try {
1852
        DocumentImpl.delete(docid[0], user, groups);
1853
        response.setContentType("text/xml");
1854
        out.println("<?xml version=\"1.0\"?>");
1855
        out.println("<success>");
1856
        out.println("Document deleted.");
1857
        out.println("</success>");
1858
      } catch (AccessionNumberException ane) {
1859
        response.setContentType("text/xml");
1860
        out.println("<?xml version=\"1.0\"?>");
1861
        out.println("<error>");
1862
        out.println("Error deleting document!!!");
1863
        out.println(ane.getMessage());
1864
        out.println("</error>");
1865
      }
1866
    } catch (Exception e) {
1867
      response.setContentType("text/xml");
1868
      out.println("<?xml version=\"1.0\"?>");
1869
      out.println("<error>");
1870
      out.println(e.getMessage());
1871
      out.println("</error>");
1872
    }
1873
  }
1874
  // END OF DELETE SECTION
1875

    
1876
  // VALIDATE SECTION
1877
  /**
1878
   * Handle the validation request and return the results to the requestor
1879
   */
1880
  private void handleValidateAction(PrintWriter out, Hashtable params) {
1881

    
1882
    // Get the document indicated
1883
    String valtext = null;
1884
    DBConnection dbConn = null;
1885
    int serialNumber = -1;
1886

    
1887
    try {
1888
      valtext = ((String[])params.get("valtext"))[0];
1889
    } catch (Exception nullpe) {
1890

    
1891

    
1892
      String docid = null;
1893
      try {
1894
        // Find the document id number
1895
        docid = ((String[])params.get("docid"))[0];
1896

    
1897

    
1898
        // Get the document indicated from the db
1899
        DocumentImpl xmldoc = new DocumentImpl(docid);
1900
        valtext = xmldoc.toString();
1901

    
1902
      } catch (NullPointerException npe) {
1903

    
1904
        out.println("<error>Error getting document ID: " + docid + "</error>");
1905
        //if ( conn != null ) { util.returnConnection(conn); }
1906
        return;
1907
      } catch (Exception e) {
1908

    
1909
        out.println(e.getMessage());
1910
      }
1911
    }
1912

    
1913

    
1914
    try {
1915
      // get a connection from the pool
1916
      dbConn=DBConnectionPool.
1917
                  getDBConnection("MetaCatServlet.handleValidateAction");
1918
      serialNumber=dbConn.getCheckOutSerialNumber();
1919
      DBValidate valobj = new DBValidate(saxparser,dbConn);
1920
      boolean valid = valobj.validateString(valtext);
1921

    
1922
      // set content type and other response header fields first
1923

    
1924
      out.println(valobj.returnErrors());
1925

    
1926
    } catch (NullPointerException npe2) {
1927
      // set content type and other response header fields first
1928

    
1929
      out.println("<error>Error validating document.</error>");
1930
    } catch (Exception e) {
1931

    
1932
      out.println(e.getMessage());
1933
    } finally {
1934
      // Return db connection
1935
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1936
    }
1937
  }
1938
  // END OF VALIDATE SECTION
1939

    
1940
  // OTHER ACTION HANDLERS
1941

    
1942
  /**
1943
   * Handle "getrevsionanddoctype" action
1944
   * Given a docid, return it's current revision and doctype from data base
1945
   * The output is String look like "rev;doctype"
1946
   */
1947
  private void handleGetRevisionAndDocTypeAction(PrintWriter out,
1948
                                                              Hashtable params)
1949
  {
1950
    // To store doc parameter
1951
    String [] docs = new String[10];
1952
    // Store a single doc id
1953
    String givenDocId = null;
1954
    // Get docid from parameters
1955
    if (params.containsKey("docid"))
1956
    {
1957
      docs = (String[])params.get("docid");
1958
    }
1959
    // Get first docid form string array
1960
    givenDocId = docs[0];
1961

    
1962
    try
1963
    {
1964
      // Make sure there is a docid
1965
      if (givenDocId == null || givenDocId.equals(""))
1966
      {
1967
        throw new Exception("User didn't specify docid!");
1968
      }//if
1969

    
1970
      // Create a DBUtil object
1971
      DBUtil dbutil = new DBUtil();
1972
      // Get a rev and doctype
1973
      String revAndDocType =
1974
                dbutil.getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1975
      out.println(revAndDocType);
1976

    
1977
    }//try
1978
    catch (Exception e)
1979
    {
1980
      // Handle exception
1981
      out.println("<?xml version=\"1.0\"?>");
1982
      out.println("<error>");
1983
      out.println(e.getMessage());
1984
      out.println("</error>");
1985
    }//catch
1986

    
1987
  }//handleGetRevisionAndDocTypeAction
1988

    
1989
  /**
1990
   * Handle "getaccesscontrol" action.
1991
   * Read Access Control List from db connection in XML format
1992
   */
1993
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
1994
                                       HttpServletResponse response,
1995
                                       String username, String[] groupnames) {
1996

    
1997
    DBConnection dbConn = null;
1998
    int serialNumber = -1;
1999
    String docid = ((String[])params.get("docid"))[0];
2000

    
2001
    try {
2002

    
2003
        // get connection from the pool
2004
        dbConn=DBConnectionPool.
2005
                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2006
        serialNumber=dbConn.getCheckOutSerialNumber();
2007
        AccessControlList aclobj = new AccessControlList(dbConn);
2008
        String acltext = aclobj.getACL(docid, username, groupnames);
2009
        out.println(acltext);
2010

    
2011
    } catch (Exception e) {
2012
      out.println("<?xml version=\"1.0\"?>");
2013
      out.println("<error>");
2014
      out.println(e.getMessage());
2015
      out.println("</error>");
2016
    } finally {
2017
      // Retrun db connection to pool
2018
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2019
    }
2020

    
2021
  }
2022

    
2023
  /**
2024
   * Handle the "getprincipals" action.
2025
   * Read all principals from authentication scheme in XML format
2026
   */
2027
  private void handleGetPrincipalsAction(PrintWriter out, String user,
2028
                                         String password) {
2029

    
2030

    
2031
    try {
2032

    
2033

    
2034
        AuthSession auth = new AuthSession();
2035
        String principals = auth.getPrincipals(user, password);
2036
        out.println(principals);
2037

    
2038
    } catch (Exception e) {
2039
      out.println("<?xml version=\"1.0\"?>");
2040
      out.println("<error>");
2041
      out.println(e.getMessage());
2042
      out.println("</error>");
2043
    }
2044

    
2045
  }
2046

    
2047
  /**
2048
   * Handle "getdoctypes" action.
2049
   * Read all doctypes from db connection in XML format
2050
   */
2051
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
2052
                                       HttpServletResponse response) {
2053

    
2054

    
2055
    try {
2056

    
2057

    
2058
        DBUtil dbutil = new DBUtil();
2059
        String doctypes = dbutil.readDoctypes();
2060
        out.println(doctypes);
2061

    
2062
    } catch (Exception e) {
2063
      out.println("<?xml version=\"1.0\"?>");
2064
      out.println("<error>");
2065
      out.println(e.getMessage());
2066
      out.println("</error>");
2067
    }
2068

    
2069
  }
2070

    
2071
  /**
2072
   * Handle the "getdtdschema" action.
2073
   * Read DTD or Schema file for a given doctype from Metacat catalog system
2074
   */
2075
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2076
                                        HttpServletResponse response) {
2077

    
2078

    
2079
    String doctype = null;
2080
    String[] doctypeArr = (String[])params.get("doctype");
2081

    
2082
    // get only the first doctype specified in the list of doctypes
2083
    // it could be done for all doctypes in that list
2084
    if (doctypeArr != null) {
2085
        doctype = ((String[])params.get("doctype"))[0];
2086
    }
2087

    
2088
    try {
2089

    
2090

    
2091
        DBUtil dbutil = new DBUtil();
2092
        String dtdschema = dbutil.readDTDSchema(doctype);
2093
        out.println(dtdschema);
2094

    
2095
    } catch (Exception e) {
2096
      out.println("<?xml version=\"1.0\"?>");
2097
      out.println("<error>");
2098
      out.println(e.getMessage());
2099
      out.println("</error>");
2100
    }
2101

    
2102
  }
2103

    
2104
  /**
2105
   * Handle the "getdataguide" action.
2106
   * Read Data Guide for a given doctype from db connection in XML format
2107
   */
2108
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
2109
                                        HttpServletResponse response) {
2110

    
2111

    
2112
    String doctype = null;
2113
    String[] doctypeArr = (String[])params.get("doctype");
2114

    
2115
    // get only the first doctype specified in the list of doctypes
2116
    // it could be done for all doctypes in that list
2117
    if (doctypeArr != null) {
2118
        doctype = ((String[])params.get("doctype"))[0];
2119
    }
2120

    
2121
    try {
2122

    
2123

    
2124
        DBUtil dbutil = new DBUtil();
2125
        String dataguide = dbutil.readDataGuide(doctype);
2126
        out.println(dataguide);
2127

    
2128
    } catch (Exception e) {
2129
      out.println("<?xml version=\"1.0\"?>");
2130
      out.println("<error>");
2131
      out.println(e.getMessage());
2132
      out.println("</error>");
2133
    }
2134

    
2135
  }
2136

    
2137
  /**
2138
   * Handle the "getlastdocid" action.
2139
   * Get the latest docid with rev number from db connection in XML format
2140
   */
2141
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2142
                                        HttpServletResponse response) {
2143

    
2144

    
2145
    String scope = ((String[])params.get("scope"))[0];
2146
    if (scope == null) {
2147
        scope = ((String[])params.get("username"))[0];
2148
    }
2149

    
2150
    try {
2151

    
2152

    
2153
        DBUtil dbutil = new DBUtil();
2154
        String lastDocid = dbutil.getMaxDocid(scope);
2155
        out.println("<?xml version=\"1.0\"?>");
2156
        out.println("<lastDocid>");
2157
        out.println("  <scope>" + scope + "</scope>");
2158
        out.println("  <docid>" + lastDocid + "</docid>");
2159
        out.println("</lastDocid>");
2160

    
2161
    } catch (Exception e) {
2162
      out.println("<?xml version=\"1.0\"?>");
2163
      out.println("<error>");
2164
      out.println(e.getMessage());
2165
      out.println("</error>");
2166
    }
2167

    
2168
  }
2169

    
2170
  /**
2171
   * Handle documents passed to metacat that are encoded using the
2172
   * "multipart/form-data" mime type.  This is typically used for uploading
2173
   * data files which may be binary and large.
2174
   */
2175
  private void handleMultipartForm(HttpServletRequest request,
2176
                                   HttpServletResponse response)
2177
  {
2178
    PrintWriter out = null;
2179
    String action = null;
2180

    
2181
    // Parse the multipart form, and save the parameters in a Hashtable and
2182
    // save the FileParts in a hashtable
2183

    
2184
    Hashtable params = new Hashtable();
2185
    Hashtable fileList = new Hashtable();
2186
    int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2187
                                                                   .intValue();
2188
    MetaCatUtil.debugMessage("The limit size of data file is: "+sizeLimit, 50);
2189

    
2190
    try {
2191
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
2192
      MultipartParser mp = new MultipartParser(request, sizeLimit*1024*1024);
2193
      Part part;
2194
      while ((part = mp.readNextPart()) != null) {
2195
        String name = part.getName();
2196

    
2197
        if (part.isParam()) {
2198
          // it's a parameter part
2199
          ParamPart paramPart = (ParamPart) part;
2200
          String value = paramPart.getStringValue();
2201
          params.put(name, value);
2202
          if (name.equals("action")) {
2203
            action = value;
2204
          }
2205
        } else if (part.isFile()) {
2206
          // it's a file part
2207
          FilePart filePart = (FilePart) part;
2208
          fileList.put(name, filePart);
2209

    
2210
          // Stop once the first file part is found, otherwise going onto the
2211
          // next part prevents access to the file contents.  So...for upload
2212
          // to work, the datafile must be the last part
2213
          break;
2214
        }
2215
      }
2216
    } catch (IOException ioe) {
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: problem reading multipart data.");
2225
      out.println("</error>");
2226
    }
2227

    
2228
    // Get the session information
2229
    String username = null;
2230
    String password = null;
2231
    String[] groupnames = null;
2232
    String sess_id = null;
2233

    
2234
    // be aware of session expiration on every request
2235
    HttpSession sess = request.getSession(true);
2236
    if (sess.isNew()) {
2237
      // session expired or has not been stored b/w user requests
2238
      username = "public";
2239
      sess.setAttribute("username", username);
2240
    } else {
2241
      username = (String)sess.getAttribute("username");
2242
      password = (String)sess.getAttribute("password");
2243
      groupnames = (String[])sess.getAttribute("groupnames");
2244
      try {
2245
        sess_id = (String)sess.getId();
2246
      } catch(IllegalStateException ise) {
2247
        System.out.println("error in  handleMultipartForm: this shouldn't " +
2248
                           "happen: the session should be valid: " +
2249
                           ise.getMessage());
2250
      }
2251
    }
2252

    
2253
    // Get the out stream
2254
    try {
2255
          out = response.getWriter();
2256
        } catch (IOException ioe2) {
2257
          util.debugMessage("Fatal Error: couldn't get response "+
2258
                             "output stream.", 30);
2259
        }
2260

    
2261
    if ( action.equals("upload")) {
2262
      if (username != null &&  !username.equals("public")) {
2263
        handleUploadAction(request, out, params, fileList,
2264
                           username, groupnames);
2265
      } else {
2266

    
2267
        out.println("<?xml version=\"1.0\"?>");
2268
        out.println("<error>");
2269
        out.println("Permission denied for " + action);
2270
        out.println("</error>");
2271
      }
2272
    } else {
2273
      /*try {
2274
        out = response.getWriter();
2275
      } catch (IOException ioe2) {
2276
        System.err.println("Fatal Error: couldn't get response output stream.");
2277
      }*/
2278
      out.println("<?xml version=\"1.0\"?>");
2279
      out.println("<error>");
2280
      out.println("Error: action not registered.  Please report this error.");
2281
      out.println("</error>");
2282
    }
2283
    out.close();
2284
  }
2285

    
2286
  /**
2287
   * Handle the upload action by saving the attached file to disk and
2288
   * registering it in the Metacat db
2289
   */
2290
  private void handleUploadAction(HttpServletRequest request,
2291
                                  PrintWriter out,
2292
                                  Hashtable params, Hashtable fileList,
2293
                                  String username, String[] groupnames)
2294
  {
2295
    //PrintWriter out = null;
2296
    //Connection conn = null;
2297
    String action = null;
2298
    String docid = null;
2299

    
2300
    /*response.setContentType("text/xml");
2301
    try
2302
    {
2303
      out = response.getWriter();
2304
    }
2305
    catch (IOException ioe2)
2306
    {
2307
      System.err.println("Fatal Error: couldn't get response output stream.");
2308
    }*/
2309

    
2310
    if (params.containsKey("docid"))
2311
    {
2312
      docid = (String)params.get("docid");
2313
    }
2314

    
2315
    // Make sure we have a docid and datafile
2316
    if (docid != null && fileList.containsKey("datafile")) {
2317

    
2318
      // Get a reference to the file part of the form
2319
      FilePart filePart = (FilePart)fileList.get("datafile");
2320
      String fileName = filePart.getFileName();
2321
      MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2322

    
2323
      // Check if the right file existed in the uploaded data
2324
      if (fileName != null) {
2325

    
2326
        try
2327
        {
2328
           //MetaCatUtil.debugMessage("Upload datafile " + docid +"...", 10);
2329
           //If document get lock data file grant
2330
           if (DocumentImpl.getDataFileLockGrant(docid))
2331
           {
2332
              // register the file in the database (which generates an exception
2333
              //if the docid is not acceptable or other untoward things happen
2334
              DocumentImpl.registerDocument(fileName, "BIN", docid, username);
2335

    
2336
              // Save the data file to disk using "docid" as the name
2337
              dataDirectory.mkdirs();
2338
              File newFile = new File(dataDirectory, docid);
2339
              long size = filePart.writeTo(newFile);
2340

    
2341
              // Force replication this data file
2342
              // To data file, "insert" and update is same
2343
              // The fourth parameter is null. Because it is notification server
2344
              // and this method is in MetaCatServerlet. It is original command,
2345
              // not get force replication info from another metacat
2346
              ForceReplicationHandler frh = new ForceReplicationHandler
2347
                                                (docid, "insert", false, null);
2348

    
2349
              // set content type and other response header fields first
2350
              out.println("<?xml version=\"1.0\"?>");
2351
              out.println("<success>");
2352
              out.println("<docid>" + docid + "</docid>");
2353
              out.println("<size>" + size + "</size>");
2354
              out.println("</success>");
2355
          }//if
2356

    
2357
        } //try
2358
        catch (Exception e)
2359
        {
2360
          out.println("<?xml version=\"1.0\"?>");
2361
          out.println("<error>");
2362
          out.println(e.getMessage());
2363
          out.println("</error>");
2364
        }
2365

    
2366
      }
2367
      else
2368
      {
2369
        // the field did not contain a file
2370
        out.println("<?xml version=\"1.0\"?>");
2371
        out.println("<error>");
2372
        out.println("The uploaded data did not contain a valid file.");
2373
        out.println("</error>");
2374
      }
2375
    }
2376
    else
2377
    {
2378
      // Error bcse docid missing or file missing
2379
      out.println("<?xml version=\"1.0\"?>");
2380
      out.println("<error>");
2381
      out.println("The uploaded data did not contain a valid docid " +
2382
                  "or valid file.");
2383
      out.println("</error>");
2384
    }
2385
  }
2386

    
2387
  /*
2388
   * A method to handle set access action
2389
   */
2390
  private void handleSetAccessAction(PrintWriter out,
2391
                                   Hashtable params,
2392
                                   String username)
2393
  {
2394
    String [] docList        = null;
2395
    String [] principalList  = null;
2396
    String [] permissionList = null;
2397
    String [] permTypeList   = null;
2398
    String [] permOrderList  = null;
2399
    String permission = null;
2400
    String permType   = null;
2401
    String permOrder  = null;
2402
    Vector errorList  = new Vector();
2403
    String error      = null;
2404
    Vector successList = new Vector();
2405
    String success    = null;
2406

    
2407

    
2408
    // Get parameters
2409
    if (params.containsKey("docid"))
2410
    {
2411
      docList = (String[])params.get("docid");
2412
    }
2413
    if (params.containsKey("principal"))
2414
    {
2415
      principalList = (String[])params.get("principal");
2416
    }
2417
    if (params.containsKey("permission"))
2418
    {
2419
      permissionList = (String[])params.get("permission");
2420

    
2421
    }
2422
    if (params.containsKey("permType"))
2423
    {
2424
      permTypeList = (String[])params.get("permType");
2425

    
2426
    }
2427
    if (params.containsKey("permOrder"))
2428
    {
2429
      permOrderList = (String[])params.get("permOrder");
2430

    
2431
    }
2432

    
2433
    // Make sure the parameter is not null
2434
    if (docList == null || principalList == null || permTypeList == null ||
2435
        permissionList == null)
2436
    {
2437
      error = "Please check your parameter list, it should look like: "+
2438
              "?action=setaccess&docid=pipeline.1.1&principal=public" +
2439
              "&permission=read&permType=allow&permOrder=allowFirst";
2440
      errorList.addElement(error);
2441
      outputResponse(successList, errorList, out);
2442
      return;
2443
    }
2444

    
2445
    // Only select first element for permission, type and order
2446
    permission = permissionList[0];
2447
    permType = permTypeList[0];
2448
    if (permOrderList != null)
2449
    {
2450
       permOrder = permOrderList[0];
2451
    }
2452

    
2453
    // Get package doctype set
2454
    Vector packageSet =MetaCatUtil.getOptionList(
2455
                                    MetaCatUtil.getOption("packagedoctypeset"));
2456
    //debug
2457
    if (packageSet != null)
2458
    {
2459
      for (int i = 0; i<packageSet.size(); i++)
2460
      {
2461
        MetaCatUtil.debugMessage("doctype in package set: " +
2462
                              (String)packageSet.elementAt(i), 34);
2463
      }
2464
    }//if
2465

    
2466
    // handle every accessionNumber
2467
    for (int i=0; i <docList.length; i++)
2468
    {
2469
      String accessionNumber = docList[i];
2470
      String owner = null;
2471
      String publicId = null;
2472
      // Get document owner and public id
2473
      try
2474
      {
2475
        owner = getFieldValueForDoc(accessionNumber, "user_owner");
2476
        publicId = getFieldValueForDoc(accessionNumber, "doctype");
2477
      }//try
2478
      catch (Exception e)
2479
      {
2480
        MetaCatUtil.debugMessage("Error in handleSetAccessAction: " +
2481
                                  e.getMessage(), 30);
2482
        error = "Error in set access control for document - " + accessionNumber+
2483
                 e.getMessage();
2484
        errorList.addElement(error);
2485
        continue;
2486
      }
2487
      //check if user is the owner. Only owner can do owner
2488
      if (username == null || owner == null || !username.equals(owner))
2489
      {
2490
        error = "User - " + username + " does not have permission to set " +
2491
                "access control for docid - " + accessionNumber;
2492
        errorList.addElement(error);
2493
        continue;
2494
      }
2495

    
2496
      // If docid publicid is BIN data file or other beta4, 6 package document
2497
      // we could not do set access control. Because we don't want inconsistent
2498
      // to its access docuemnt
2499
      if (publicId!=null && packageSet!=null && packageSet.contains(publicId))
2500
      {
2501
        error = "Could not set access control to document "+ accessionNumber +
2502
                "because it is in a pakcage and it has a access file for it";
2503
        errorList.addElement(error);
2504
        continue;
2505
      }
2506

    
2507
      // for every principle
2508
      for (int j = 0; j<principalList.length; j++)
2509
      {
2510
        String principal = principalList[j];
2511
        try
2512
        {
2513
          //insert permission
2514
          AccessControlForSingleFile accessControl = new
2515
                           AccessControlForSingleFile(accessionNumber,
2516
                                    principal, permission, permType, permOrder);
2517
          accessControl.insertPermissions();
2518
          success = "Set access control to document "+ accessionNumber +
2519
                    " successfully";
2520
          successList.addElement(success);
2521
        }
2522
        catch (Exception ee)
2523
        {
2524
          MetaCatUtil.debugMessage("Erorr in handleSetAccessAction2: " +
2525
                                   ee.getMessage(), 30);
2526
          error = "Faild to set access control for document " +
2527
                  accessionNumber + " because " + ee.getMessage();
2528
          errorList.addElement(error);
2529
          continue;
2530
        }
2531
      }//for every principle
2532
    }//for every document
2533
    outputResponse(successList, errorList, out);
2534
  }//handleSetAccessAction
2535

    
2536

    
2537
  /*
2538
   * A method try to determin a docid's public id, if couldn't find null
2539
   * will be returned.
2540
   */
2541
  private String getFieldValueForDoc(String accessionNumber, String fieldName)
2542
                                      throws Exception
2543
  {
2544
    if (accessionNumber==null || accessionNumber.equals("") ||fieldName == null
2545
        || fieldName.equals(""))
2546
    {
2547
      throw new Exception("Docid or field name was not specified");
2548
    }
2549

    
2550
    PreparedStatement pstmt = null;
2551
    ResultSet rs = null;
2552
    String fieldValue = null;
2553
    String docId = null;
2554
    DBConnection conn = null;
2555
    int serialNumber = -1;
2556

    
2557
    // get rid of revision if access number has
2558
    docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2559
    try
2560
    {
2561
      //check out DBConnection
2562
      conn=DBConnectionPool.getDBConnection("MetaCatServlet.getPublicIdForDoc");
2563
      serialNumber=conn.getCheckOutSerialNumber();
2564
      pstmt = conn.prepareStatement(
2565
            "SELECT " + fieldName + " FROM xml_documents " +
2566
            "WHERE docid = ? ");
2567

    
2568
      pstmt.setString(1, docId);
2569
      pstmt.execute();
2570
      rs = pstmt.getResultSet();
2571
      boolean hasRow = rs.next();
2572
      int perm = 0;
2573
      if ( hasRow )
2574
      {
2575
        fieldValue = rs.getString(1);
2576
      }
2577
      else
2578
      {
2579
        throw new Exception("Could not find document: "+accessionNumber);
2580
      }
2581
    }//try
2582
    catch (Exception e)
2583
    {
2584
      MetaCatUtil.debugMessage("Exception in MetacatServlet.getPublicIdForDoc: "
2585
                               + e.getMessage(), 30);
2586
      throw e;
2587
    }
2588
    finally
2589
    {
2590
      try
2591
      {
2592
        rs.close();
2593
        pstmt.close();
2594

    
2595
      }
2596
      finally
2597
      {
2598
        DBConnectionPool.returnDBConnection(conn, serialNumber);
2599
      }
2600
    }
2601
    return fieldValue;
2602
  }//getFieldValueForDoc
2603

    
2604
  /*
2605
   * A method to output setAccess action result
2606
   */
2607
  private void outputResponse(Vector successList,
2608
                              Vector errorList,
2609
                              PrintWriter out)
2610
  {
2611
    boolean error = false;
2612
    boolean success = false;
2613
    // Output prolog
2614
    out.println(PROLOG);
2615
    // output success message
2616
    if ( successList != null)
2617
    {
2618
      for (int i = 0; i<successList.size(); i++)
2619
      {
2620
        out.println(SUCCESS);
2621
        out.println((String)successList.elementAt(i));
2622
        out.println(SUCCESSCLOSE);
2623
        success = true;
2624
      }//for
2625
    }//if
2626
    // output error message
2627
    if (errorList != null)
2628
    {
2629
      for (int i = 0; i<errorList.size(); i++)
2630
      {
2631
        out.println(ERROR);
2632
        out.println((String)errorList.elementAt(i));
2633
        out.println(ERRORCLOSE);
2634
        error = true;
2635
      }//for
2636
    }//if
2637

    
2638
    // if no error and no success info, send a error that nothing happened
2639
    if( !error && !success)
2640
    {
2641
      out.println(ERROR);
2642
      out.println("Nothing happend for setaccess action");
2643
      out.println(ERRORCLOSE);
2644
    }
2645

    
2646
  }//outputResponse
2647
}
(40-40/57)