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: jones $'
10
 *     '$Date: 2003-12-10 01:15:07 -0800 (Wed, 10 Dec 2003) $'
11
 * '$Revision: 1956 $'
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
import edu.ucsb.nceas.utilities.Options;
70

    
71
import org.xml.sax.SAXException;
72

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

    
110
  private ServletConfig config = null;
111
  private ServletContext context = null;
112
  private String resultStyleURL = null;
113
  private String xmlcatalogfile = null;
114
  private String saxparser = null;
115
  private String datafilepath = null;
116
  private File dataDirectory = null;
117
  private String servletpath = null;
118
  private String htmlpath = null;
119
  private PropertyResourceBundle options = null;
120
  private MetaCatUtil util = null;
121
  private DBConnectionPool connPool = null;
122
  private Hashtable sessionHash = new Hashtable();
123
  private static final String PROLOG = "<?xml version=\"1.0\"?>";
124
  private static final String SUCCESS = "<success>";
125
  private static final String SUCCESSCLOSE = "</success>";
126
  private static final String ERROR = "<error>";
127
  private static final String ERRORCLOSE = "</error>";
128
  public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
129
  public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
130
  public static final String EML2KEYWORD =":eml";
131
  private static final String CONFIG_DIR  = "WEB-INF";
132
  private static final String CONFIG_NAME = "metacat.properties";
133

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

    
144
      // Initialize the properties file for our options
145
      String dirPath = context.getRealPath(CONFIG_DIR);
146
      File propertyFile = new File(dirPath,CONFIG_NAME);
147
      Options options = null;
148
      try {
149
          options = Options.initialize(propertyFile);
150
          MetaCatUtil.debugMessage("Options configured: " + 
151
            options.getOption("configured"), 20);
152
      } catch (IOException ioe) {
153
        MetaCatUtil.debugMessage("Error in loading options: "
154
           +ioe.getMessage(), 20);
155
      }
156

    
157
      util = new MetaCatUtil();
158

    
159
      //initial DBConnection pool
160
      connPool = DBConnectionPool.getInstance();
161

    
162
      // Get the configuration file information
163
      resultStyleURL = util.getOption("resultStyleURL");
164
      xmlcatalogfile = util.getOption("xmlcatalogfile");
165
      saxparser = util.getOption("saxparser");
166
      datafilepath = util.getOption("datafilepath");
167
      dataDirectory = new File(datafilepath);
168
      servletpath = util.getOption("servletpath");
169
      htmlpath = util.getOption("htmlpath");
170

    
171

    
172
    } catch ( ServletException ex ) {
173
      throw ex;
174
    } catch (SQLException e) {
175
      MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
176
                                          +e.getMessage(), 20);
177
    }
178
  }
179

    
180
  /**
181
   * Close all db connections from the pool
182
   */
183
  public void destroy() {
184
      // Close all db connection
185
      System.out.println("Destroying MetacatServlet");
186
      connPool.release();
187
  }
188

    
189
  /** Handle "GET" method requests from HTTP clients */
190
  public void doGet (HttpServletRequest request, HttpServletResponse response)
191
    throws ServletException, IOException {
192

    
193
    // Process the data and send back the response
194
    handleGetOrPost(request, response);
195
  }
196

    
197
  /** Handle "POST" method requests from HTTP clients */
198
  public void doPost( HttpServletRequest request, HttpServletResponse response)
199
    throws ServletException, IOException {
200

    
201
    // Process the data and send back the response
202
    handleGetOrPost(request, response);
203
  }
204

    
205
  /**
206
   * Control servlet response depending on the action parameter specified
207
   */
208
  private void handleGetOrPost(HttpServletRequest request,
209
                               HttpServletResponse response)
210
                               throws ServletException, IOException
211
  {
212

    
213
    if ( util == null ) {
214
        util = new MetaCatUtil();
215
    }
216
    /*MetaCatUtil.debugMessage("Connection pool size: "
217
                                     +connPool.getSizeOfDBConnectionPool(),10);
218
    MetaCatUtil.debugMessage("Free DBConnection number: "
219
                                  +connPool.getFreeDBConnectionNumber(), 10);*/
220
    //If all DBConnection in the pool are free and DBConnection pool
221
    //size is greater than initial value, shrink the connection pool
222
    //size to initial value
223
    DBConnectionPool.shrinkDBConnectionPoolSize();
224

    
225
    //Debug message to print out the method which have a busy DBConnection
226
    connPool.printMethodNameHavingBusyDBConnection();
227

    
228
    String ctype = request.getContentType();
229
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
230
      handleMultipartForm(request, response);
231
    } else {
232

    
233

    
234
      String name = null;
235
      String[] value = null;
236
      String[] docid = new String[3];
237
      Hashtable params = new Hashtable();
238
      Enumeration paramlist = request.getParameterNames();
239

    
240

    
241
      while (paramlist.hasMoreElements()) {
242

    
243
        name = (String)paramlist.nextElement();
244
        value = request.getParameterValues(name);
245

    
246
        // Decode the docid and mouse click information
247
        if (name.endsWith(".y")) {
248
          docid[0] = name.substring(0,name.length()-2);
249
          params.put("docid", docid);
250
          name = "ypos";
251
        }
252
        if (name.endsWith(".x")) {
253
          name = "xpos";
254
        }
255

    
256
        params.put(name,value);
257
      }
258

    
259

    
260
      //handle param is emptpy
261
      if (params.isEmpty() || params == null)
262
      {
263
        return;
264
      }
265

    
266
      //if the user clicked on the input images, decode which image
267
      //was clicked then set the action.
268
      String action = ((String[])params.get("action"))[0];
269
      util.debugMessage("Line 230: Action is: " + action, 1);
270

    
271
      // This block handles session management for the servlet
272
      // by looking up the current session information for all actions
273
      // other than "login" and "logout"
274
      String username = null;
275
      String password = null;
276
      String[] groupnames = null;
277
      String sess_id = null;
278

    
279
      // handle login action
280
      if (action.equals("login")) {
281
        PrintWriter out = response.getWriter();
282
        handleLoginAction(out, params, request, response);
283
        out.close();
284

    
285
      // handle logout action
286
      } else if (action.equals("logout")) {
287
        PrintWriter out = response.getWriter();
288
        handleLogoutAction(out, params, request, response);
289
        out.close();
290

    
291
      // handle shrink DBConnection request
292
      } else if (action.equals("shrink")) {
293
        PrintWriter out = response.getWriter();
294
        boolean success = false;
295
        //If all DBConnection in the pool are free and DBConnection pool
296
        //size is greater than initial value, shrink the connection pool
297
        //size to initial value
298
        success = DBConnectionPool.shrinkConnectionPoolSize();
299
        if (success)
300
        {
301
          //if successfully shrink the pool size to initial value
302
          out.println("DBConnection Pool shrink successfully");
303
        }//if
304
        else
305
        {
306
          out.println("DBConnection pool couldn't shrink successfully");
307
        }
308
       //close out put
309
        out.close();
310

    
311
      // aware of session expiration on every request
312
      }
313
      else
314
      {
315
        HttpSession sess = request.getSession(true);
316
        if (sess.isNew() && !params.containsKey("sessionid")) {
317
          // session expired or has not been stored b/w user requests
318
          username = "public";
319
          sess.setAttribute("username", username);
320
        }
321
        else
322
        {
323
          try
324
          {
325
            if(params.containsKey("sessionid"))
326
            {
327
              sess_id = ((String[])params.get("sessionid"))[0];
328
              if(sessionHash.containsKey(sess_id))
329
              {
330
                sess = (HttpSession)sessionHash.get(sess_id);
331
              }
332
            }
333
            else
334
            {
335
              sess_id = (String)sess.getId();
336
              sessionHash.put(sess_id, sess);
337
            }
338
          }
339
          catch(IllegalStateException ise)
340
          {
341
            System.out.println("error in handleGetOrPost: this shouldn't " +
342
                               "happen: the session should be valid: " +
343
                               ise.getMessage());
344
          }
345

    
346
          username = (String)sess.getAttribute("username");
347
          password = (String)sess.getAttribute("password");
348
          groupnames = (String[])sess.getAttribute("groupnames");
349
        }
350
      }
351
      
352
      //make user user username should be public
353
      if (username == null || (username.trim().equals("")))
354
      {
355
        username = "public";
356
      }
357

    
358
       // Now that we know the session is valid, we can delegate the request
359
      // to a particular action handler
360
      if(action.equals("query")) {
361
        PrintWriter out = response.getWriter();
362
        handleQuery(out,params,response,username,groupnames,sess_id);
363
        out.close();
364
      } else if(action.equals("squery")) {
365
        PrintWriter out = response.getWriter();
366
        if(params.containsKey("query")) {
367
         handleSQuery(out, params,response,username,groupnames,sess_id);
368
         out.close();
369
        } else {
370
          out.println("Illegal action squery without \"query\" parameter");
371
          out.close();
372
        }
373
      } else if (action.equals("export")) {
374

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

    
484
      //util.closeConnections();
485
      // Close the stream to the client
486
      //out.close();
487
    }
488
  }
489

    
490
  // LOGIN & LOGOUT SECTION
491
  /**
492
   * Handle the login request. Create a new session object.
493
   * Do user authentication through the session.
494
   */
495
  private void handleLoginAction(PrintWriter out, Hashtable params,
496
               HttpServletRequest request, HttpServletResponse response) {
497

    
498
    AuthSession sess = null;
499
    String un = ((String[])params.get("username"))[0];
500
    String pw = ((String[])params.get("password"))[0];
501
    String action = ((String[])params.get("action"))[0];
502
    String qformat = ((String[])params.get("qformat"))[0];
503

    
504
    try {
505
      sess = new AuthSession();
506
    } catch (Exception e) {
507
      System.out.println("error in MetacatServlet.handleLoginAction: " +
508
                          e.getMessage());
509
      out.println(e.getMessage());
510
      return;
511
    }
512
    boolean isValid = sess.authenticate(request, un, pw);
513
    // format and transform the output
514
    if (qformat.equals("xml")) {
515
      response.setContentType("text/xml");
516
      out.println(sess.getMessage());
517
    } else {
518

    
519
      try {
520

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

    
526
      } catch(Exception e) {
527

    
528
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
529
                                +e.getMessage(), 30);
530
      }
531

    
532
    // any output is returned
533
    }
534
  }
535

    
536
  /**
537
   * Handle the logout request. Close the connection.
538
   */
539
  private void handleLogoutAction(PrintWriter out, Hashtable params,
540
               HttpServletRequest request, HttpServletResponse response) {
541

    
542
    String qformat = ((String[])params.get("qformat"))[0];
543

    
544
    // close the connection
545
    HttpSession sess = request.getSession(false);
546
    if (sess != null) { sess.invalidate();  }
547

    
548
    // produce output
549
    StringBuffer output = new StringBuffer();
550
    output.append("<?xml version=\"1.0\"?>");
551
    output.append("<logout>");
552
    output.append("User logged out");
553
    output.append("</logout>");
554

    
555
    //format and transform the output
556
    if (qformat.equals("xml")) {
557
      response.setContentType("text/xml");
558
      out.println(output.toString());
559
    } else {
560

    
561
      try {
562

    
563
        DBTransform trans = new DBTransform();
564
        response.setContentType("text/html");
565
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
566
                                   "-//W3C//HTML//EN", qformat, out, null);
567

    
568
      } catch(Exception e) {
569

    
570
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
571
                                  +e.getMessage(), 30);
572
      }
573
    }
574
  }
575
  // END OF LOGIN & LOGOUT SECTION
576

    
577
  // SQUERY & QUERY SECTION
578
  /**
579
   * Retreive the squery xml, execute it and display it
580
   *
581
   * @param out the output stream to the client
582
   * @param params the Hashtable of parameters that should be included
583
   * in the squery.
584
   * @param response the response object linked to the client
585
   * @param conn the database connection
586
   */
587
  protected void handleSQuery(PrintWriter out, Hashtable params,
588
                 HttpServletResponse response, String user, String[] groups,
589
                 String sessionid)
590
  {
591
    String xmlquery = ((String[])params.get("query"))[0];
592
    String qformat = ((String[])params.get("qformat"))[0];
593
    String resultdoc = null;
594
    MetaCatUtil.debugMessage("xmlquery: "+xmlquery, 30);
595
    double startTime = System.currentTimeMillis()/1000;
596
    Hashtable doclist = runQuery(xmlquery, user, groups);
597
    double docListTime = System.currentTimeMillis()/1000;
598
    MetaCatUtil.debugMessage("Time for getting doc list: "
599
                                            +(docListTime-startTime), 30);
600

    
601
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
602
    double toStringTime = System.currentTimeMillis()/1000;
603
    MetaCatUtil.debugMessage("Time to create xml string: "
604
                              +(toStringTime-docListTime), 30);
605
    //format and transform the results
606
    double outPutTime = 0;
607
    if(qformat.equals("xml")) {
608
      response.setContentType("text/xml");
609
      out.println(resultdoc);
610
      outPutTime = System.currentTimeMillis()/1000;
611
      MetaCatUtil.debugMessage("Output time: "+(outPutTime-toStringTime), 30);
612
    } else {
613
      transformResultset(resultdoc, response, out, qformat, sessionid, params);
614
      outPutTime = System.currentTimeMillis()/1000;
615
      MetaCatUtil.debugMessage("Output time: "+(outPutTime-toStringTime), 30);
616
    }
617
  }
618

    
619
   /**
620
    * Create the xml query, execute it and display the results.
621
    *
622
    * @param out the output stream to the client
623
    * @param params the Hashtable of parameters that should be included
624
    * in the squery.
625
    * @param response the response object linked to the client
626
    */
627
  protected void handleQuery(PrintWriter out, Hashtable params,
628
                 HttpServletResponse response, String user, String[] groups,
629
                 String sessionid)
630
  {
631
    //create the query and run it
632
    String xmlquery = DBQuery.createSQuery(params);
633
    Hashtable doclist = runQuery(xmlquery, user, groups);
634
    String qformat = ((String[])params.get("qformat"))[0];
635
    String resultdoc = null;
636

    
637
    resultdoc = createResultDocument(doclist, transformQuery(params));
638

    
639
    //format and transform the results
640
    if(qformat.equals("xml")) {
641
      response.setContentType("text/xml");
642
      out.println(resultdoc);
643
    } else {
644
      transformResultset(resultdoc, response, out, qformat, sessionid, params);
645
    }
646
  }
647

    
648
  /**
649
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
650
   * so it can properly be placed in the <query> tag of the resultset.
651
   * This method is overwritable so that other applications can customize
652
   * the structure of what is in the <query> tag.
653
   *
654
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
655
   */
656
  protected String transformQuery(Hashtable params)
657
  {
658
    //DBQuery.createSQuery is a re-calling of a previously called
659
    //function but it is necessary
660
    //so that overriding methods have access to the params hashtable
661
    String xmlquery = DBQuery.createSQuery(params);
662
    //the <?xml version="1.0"?> tag is the first 22 characters of the
663
    xmlquery = xmlquery.trim();
664
    int index = xmlquery.indexOf("?>");
665
    if ( index != -1 )
666
    {
667
      //have <?xml version="1.0"?>
668
      return xmlquery.substring(index + 2, xmlquery.length());
669
    }
670
    else
671
    {
672
      // don't have <?xml version="1.0"?>
673
      return xmlquery;
674
    }
675
  }
676

    
677
  /**
678
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
679
   * string as a param instead of a hashtable.
680
   *
681
   * @param xmlquery a string representing a query.
682
   */
683
  protected String transformQuery(String xmlquery)
684
  {
685
    xmlquery = xmlquery.trim();
686
    int index = xmlquery.indexOf("?>");
687
    if (index != -1)
688
    {
689
      return xmlquery.substring(index + 2, xmlquery.length());
690
    }
691
    else
692
    {
693
      return xmlquery;
694
    }
695
  }
696

    
697
  /**
698
   * Run the query and return a hashtable of results.
699
   *
700
   * @param xmlquery the query to run
701
   */
702
  private Hashtable runQuery(String xmlquery, String user, String[] groups)
703
  {
704
    Hashtable doclist=null;
705

    
706
    try
707
    {
708

    
709
      DBQuery queryobj = new DBQuery(saxparser);
710
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,groups);
711

    
712
      return doclist;
713
    }
714
    catch (Exception e)
715
    {
716

    
717
      MetaCatUtil.debugMessage("Error in MetacatServlet.runQuery: "
718
                                                      + e.getMessage(), 30);
719
      doclist = null;
720
      return doclist;
721
    }
722
  }
723

    
724
  /**
725
   * Transorms an xml resultset document to html and sends it to the browser
726
   *
727
   * @param resultdoc the string representation of the document that needs
728
   * to be transformed.
729
   * @param response the HttpServletResponse object bound to the client.
730
   * @param out the output stream to the client
731
   * @param qformat the name of the style-set to use for transformations
732
   */
733
  protected void transformResultset(String resultdoc,
734
                                    HttpServletResponse response,
735
                                    PrintWriter out, String qformat,
736
                                    String sessionid, Hashtable params)
737
  {
738

    
739
    try {
740

    
741
      DBTransform trans = new DBTransform();
742
      response.setContentType("text/html");
743
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
744
                                 "-//W3C//HTML//EN", qformat, out, params,
745
                                 sessionid);
746

    
747
    }
748
    catch(Exception e)
749
    {
750

    
751
      MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
752
                                +e.getMessage(), 30);
753
    }
754
  }
755

    
756
  /**
757
   * Transforms a hashtable of documents to an xml or html result.
758
   *
759
   * @param doclist- the hashtable to transform
760
   * @param xmlquery- the query that returned the doclist result
761
   */
762
  protected String createResultDocument(Hashtable doclist, String xmlquery)
763
  {
764
    // Create a buffer to hold the xml result
765
    StringBuffer resultset = new StringBuffer();
766

    
767
    // Print the resulting root nodes
768
    String docid = null;
769
    String document = null;
770
    resultset.append("<?xml version=\"1.0\"?>\n");
771
    resultset.append("<resultset>\n");
772

    
773
    resultset.append("  <query>" + xmlquery + "</query>");
774

    
775
    if(doclist != null)
776
    {
777
      Enumeration doclistkeys = doclist.keys();
778
      while (doclistkeys.hasMoreElements())
779
      {
780
        docid = (String)doclistkeys.nextElement();
781
        document = (String)doclist.get(docid);
782
        resultset.append("  <document>" + document + "</document>");
783
      }
784
    }
785

    
786
    resultset.append("</resultset>");
787
    return resultset.toString();
788
  }
789
  // END OF SQUERY & QUERY SECTION
790

    
791
 //Exoport section
792
 /**
793
   * Handle the "export" request of data package from Metacat in zip format
794
   * @param params the Hashtable of HTTP request parameters
795
   * @param response the HTTP response object linked to the client
796
   * @param user the username sent the request
797
   * @param groups the user's groupnames
798
   */
799
  private void handleExportAction(Hashtable params,
800
    HttpServletResponse response, String user, String[] groups, String passWord)
801
  {
802
    // Output stream
803
    ServletOutputStream out = null;
804
    // Zip output stream
805
    ZipOutputStream zOut = null;
806
    DocumentImpl docImpls=null;
807
    DBQuery queryObj=null;
808

    
809
    String[] docs = new String[10];
810
    String docId = "";
811

    
812
    try
813
    {
814
      // read the params
815
      if (params.containsKey("docid"))
816
      {
817
        docs = (String[])params.get("docid");
818
      }//if
819
      // Create a DBuery to handle export
820
      queryObj = new DBQuery(saxparser);
821
      // Get the docid
822
      docId=docs[0];
823
      // Make sure the client specify docid
824
      if (docId == null || docId.equals(""))
825
      {
826
        response.setContentType("text/xml"); //MIME type
827
        // Get a printwriter
828
        PrintWriter pw = response.getWriter();
829
        // Send back message
830
        pw.println("<?xml version=\"1.0\"?>");
831
        pw.println("<error>");
832
        pw.println("You didn't specify requested docid");
833
        pw.println("</error>");
834
        // Close printwriter
835
        pw.close();
836
        return;
837
      }//if
838
      // Get output stream
839
      out = response.getOutputStream();
840
      response.setContentType("application/zip"); //MIME type
841
      zOut = new ZipOutputStream(out);
842
      zOut =queryObj.getZippedPackage(docId, out, user, groups, passWord);
843
      zOut.finish(); //terminate the zip file
844
      zOut.close();  //close the zip stream
845

    
846
    }//try
847
    catch (Exception e)
848
    {
849
      try
850
      {
851
        response.setContentType("text/xml"); //MIME type
852
        // Send error message back
853
        if (out != null)
854
        {
855
            PrintWriter pw = new PrintWriter(out);
856
            pw.println("<?xml version=\"1.0\"?>");
857
            pw.println("<error>");
858
            pw.println(e.getMessage());
859
            pw.println("</error>");
860
            // Close printwriter
861
            pw.close();
862
            // Close output stream
863
            out.close();
864
        }//if
865
        // Close zip output stream
866
        if ( zOut != null )
867
        {
868
          zOut.close();
869
        }//if
870
      }//try
871
      catch (IOException ioe)
872
      {
873
        MetaCatUtil.debugMessage("Problem with the servlet output " +
874
                           "in MetacatServlet.handleExportAction: " +
875
                           ioe.getMessage(), 30);
876
      }//catch
877

    
878
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleExportAction: " +
879
                         e.getMessage(), 30);
880
      e.printStackTrace(System.out);
881

    
882
    }//catch
883

    
884
  }//handleExportAction
885

    
886

    
887
   //read inline data section
888
 /**
889
   * In eml2 document, the xml can have inline data and data was stripped off
890
   * and store in file system. This action can be used to read inline data only
891
   * @param params the Hashtable of HTTP request parameters
892
   * @param response the HTTP response object linked to the client
893
   * @param user the username sent the request
894
   * @param groups the user's groupnames
895
   */
896
  private void handleReadInlineDataAction(Hashtable params,
897
                                          HttpServletResponse response,
898
                                          String user, String passWord,
899
                                          String[] groups)
900
  {
901
    String[] docs = new String[10];
902
    String inlineDataId = null;
903
    String docId = "";
904
    ServletOutputStream out = null;
905

    
906
    try
907
    {
908
      // read the params
909
      if (params.containsKey("inlinedataid"))
910
      {
911
        docs = (String[])params.get("inlinedataid");
912
      }//if
913
      // Get the docid
914
      inlineDataId=docs[0];
915
      // Make sure the client specify docid
916
      if (inlineDataId == null || inlineDataId.equals(""))
917
      {
918
        throw new Exception("You didn't specify requested inlinedataid");
919
      }//if
920

    
921
      // check for permission
922
      docId = MetaCatUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
923
      PermissionController controller = new PermissionController(docId);
924
      // check top level read permission
925
      if (!controller.hasPermission(user, groups,
926
                                    AccessControlInterface.READSTRING))
927
      {
928
          throw new Exception("User "+ user + " doesn't have permission "+
929
                              " to read document " + docId);
930
      }//if
931
      // if the document has subtree control, we need to check subtree control
932
      else if(controller.hasSubTreeAccessControl())
933
      {
934
        // get node id for inlinedata
935
        long nodeId=getInlineDataNodeId(inlineDataId, docId);
936
        if (!controller.hasPermissionForSubTreeNode(user, groups,
937
                                     AccessControlInterface.READSTRING, nodeId))
938
        {
939
           throw new Exception("User "+ user + " doesn't have permission "+
940
                              " to read inlinedata " + inlineDataId);
941
        }//if
942

    
943
      }//else
944

    
945
      // Get output stream
946
      out = response.getOutputStream();
947
      // read the inline data from the file
948
      String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
949
      File lineData = new File(inlinePath, inlineDataId);
950
      FileInputStream input = new FileInputStream(lineData);
951
      byte [] buffer = new byte[4*1024];
952
      int bytes = input.read(buffer);
953
      while (bytes != -1)
954
      {
955
        out.write(buffer, 0, bytes);
956
        bytes = input.read(buffer);
957
      }
958
      out.close();
959

    
960
    }//try
961
    catch (Exception e)
962
    {
963
      try
964
      {
965
        PrintWriter pw = null;
966
        // Send error message back
967
        if (out != null)
968
        {
969
            pw = new PrintWriter(out);
970
        }//if
971
        else
972
        {
973
          pw = response.getWriter();
974
        }
975
         pw.println("<?xml version=\"1.0\"?>");
976
         pw.println("<error>");
977
         pw.println(e.getMessage());
978
         pw.println("</error>");
979
         // Close printwriter
980
         pw.close();
981
         // Close output stream if out is not null
982
         if (out != null)
983
         {
984
           out.close();
985
         }
986
     }//try
987
     catch (IOException ioe)
988
     {
989
        MetaCatUtil.debugMessage("Problem with the servlet output " +
990
                           "in MetacatServlet.handleExportAction: " +
991
                           ioe.getMessage(), 30);
992
     }//catch
993

    
994
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadInlineDataAction: "
995
                                + e.getMessage(), 30);
996

    
997
    }//catch
998

    
999
  }//handleReadInlineDataAction
1000

    
1001
  /*
1002
   * Get the nodeid from xml_nodes for the inlinedataid
1003
   */
1004
  private long getInlineDataNodeId(String inLineDataId, String docId)
1005
                                   throws SQLException
1006
  {
1007
    long nodeId = 0;
1008
    String INLINE = "inline";
1009
    boolean hasRow;
1010
    PreparedStatement pStmt = null;
1011
    DBConnection conn = null;
1012
    int serialNumber = -1;
1013
    String sql ="SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? " +
1014
                "AND nodetype='TEXT' AND parentnodeid IN " +
1015
                "(SELECT nodeid FROM xml_nodes WHERE docid=? AND " +
1016
                "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
1017

    
1018
    try
1019
    {
1020
      //check out DBConnection
1021
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
1022
      serialNumber=conn.getCheckOutSerialNumber();
1023

    
1024
      pStmt = conn.prepareStatement(sql);
1025
      //bind value
1026
      pStmt.setString(1, docId);//docid
1027
      pStmt.setString(2, inLineDataId);//inlinedataid
1028
      pStmt.setString(3, docId);
1029
      // excute query
1030
      pStmt.execute();
1031
      ResultSet rs = pStmt.getResultSet();
1032
      hasRow=rs.next();
1033
      // get result
1034
      if (hasRow)
1035
      {
1036
        nodeId = rs.getLong(1);
1037
      }//if
1038

    
1039
    }//try
1040
    catch (SQLException e)
1041
    {
1042
      throw e;
1043
    }
1044
    finally
1045
    {
1046
      try
1047
      {
1048
        pStmt.close();
1049
      }
1050
      finally
1051
      {
1052
        DBConnectionPool.returnDBConnection(conn, serialNumber);
1053
      }
1054
    }
1055
    MetaCatUtil.debugMessage("The nodeid for inlinedataid " + inLineDataId +
1056
                             " is: "+nodeId, 35);
1057
    return nodeId;
1058
  }
1059

    
1060

    
1061

    
1062
  // READ SECTION
1063
  /**
1064
   * Handle the "read" request of metadata/data files from Metacat
1065
   * or any files from Internet;
1066
   * transformed metadata XML document into HTML presentation if requested;
1067
   * zip files when more than one were requested.
1068
   *
1069
   * @param params the Hashtable of HTTP request parameters
1070
   * @param response the HTTP response object linked to the client
1071
   * @param user the username sent the request
1072
   * @param groups the user's groupnames
1073
   */
1074
  private void handleReadAction(Hashtable params, HttpServletResponse response,
1075
                                String user, String passWord, String[] groups)
1076
  {
1077
    ServletOutputStream out = null;
1078
    ZipOutputStream zout = null;
1079
    PrintWriter pw = null;
1080
    boolean zip = false;
1081
    boolean withInlineData = true;
1082

    
1083
    try {
1084
      String[] docs = new String[0];
1085
      String docid = "";
1086
      String qformat = "";
1087
      String abstrpath = null;
1088

    
1089
      // read the params
1090
      if (params.containsKey("docid")) {
1091
        docs = (String[])params.get("docid");
1092
      }
1093
      if (params.containsKey("qformat")) {
1094
        qformat = ((String[])params.get("qformat"))[0];
1095
      }
1096
      // the param for only metadata (eml)
1097
      if (params.containsKey("inlinedata"))
1098
      {
1099

    
1100
        String inlineData = ((String[])params.get("inlinedata"))[0];
1101
        if (inlineData.equalsIgnoreCase("false"))
1102
        {
1103
          withInlineData = false;
1104
        }
1105
      }
1106
      if (params.containsKey("abstractpath")) {
1107
        abstrpath = ((String[])params.get("abstractpath"))[0];
1108
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
1109
          viewAbstract(response, abstrpath, docs[0]);
1110
          return;
1111
        }
1112
      }
1113
      if ( (docs.length > 1) || qformat.equals("zip") ) {
1114
        zip = true;
1115
        out = response.getOutputStream();
1116
        response.setContentType("application/zip"); //MIME type
1117
        zout = new ZipOutputStream(out);
1118
      }
1119
      // go through the list of docs to read
1120
      for (int i=0; i < docs.length; i++ ) {
1121
        try {
1122

    
1123
          URL murl = new URL(docs[i]);
1124
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
1125
          // case docid="http://.../?docid=aaa"
1126
          // or docid="metacat://.../?docid=bbb"
1127
          if (murlQueryStr.containsKey("docid")) {
1128
            // get only docid, eliminate the rest
1129
            docid = (String)murlQueryStr.get("docid");
1130
            if ( zip ) {
1131
              addDocToZip(docid, zout, user, groups);
1132
            } else {
1133
              readFromMetacat(response, docid, qformat, abstrpath,
1134
                              user, groups, zip, zout, withInlineData, params);
1135
            }
1136

    
1137
          // case docid="http://.../filename"
1138
          } else {
1139
            docid = docs[i];
1140
            if ( zip ) {
1141
              addDocToZip(docid, zout, user, groups);
1142
            } else {
1143
              readFromURLConnection(response, docid);
1144
            }
1145
          }
1146

    
1147
        // case docid="ccc"
1148
        } catch (MalformedURLException mue) {
1149
          docid = docs[i];
1150
          if ( zip ) {
1151
            addDocToZip(docid, zout, user, groups);
1152
          } else {
1153
            readFromMetacat(response, docid, qformat, abstrpath,
1154
                            user, groups, zip, zout, withInlineData, params);
1155
          }
1156
        }
1157

    
1158
      } /* end for */
1159

    
1160
      if ( zip ) {
1161
        zout.finish(); //terminate the zip file
1162
        zout.close();  //close the zip stream
1163
      }
1164

    
1165

    
1166
    }
1167
    // To handle doc not found exception
1168
    catch (McdbDocNotFoundException notFoundE)
1169
    {
1170
      // the docid which didn't be found
1171
      String notFoundDocId = notFoundE.getUnfoundDocId();
1172
      String notFoundRevision = notFoundE.getUnfoundRevision();
1173
      MetaCatUtil.debugMessage("Missed id: "+ notFoundDocId, 30);
1174
      MetaCatUtil.debugMessage("Missed rev: "+ notFoundRevision, 30);
1175
      try
1176
      {
1177
        // read docid from remote server
1178
        readFromRemoteMetaCat(response, notFoundDocId, notFoundRevision,
1179
                                              user, passWord, out, zip, zout);
1180
        // Close zout outputstream
1181
        if ( zout != null)
1182
        {
1183
          zout.close();
1184
        }
1185
        // close output stream
1186
        if (out != null)
1187
        {
1188
          out.close();
1189
        }
1190

    
1191
      }//try
1192
      catch ( Exception exc)
1193
      {
1194
        MetaCatUtil.debugMessage("Erorr in MetacatServlet.hanldReadAction: "+
1195
                                      exc.getMessage(), 30);
1196
        try
1197
        {
1198
          if (out != null)
1199
          {
1200
            response.setContentType("text/xml");
1201
            // Send back error message by printWriter
1202
            pw = new PrintWriter(out);
1203
            pw.println("<?xml version=\"1.0\"?>");
1204
            pw.println("<error>");
1205
            pw.println(notFoundE.getMessage());
1206
            pw.println("</error>");
1207
            pw.close();
1208
            out.close();
1209

    
1210
          }
1211
          else
1212
          {
1213
           response.setContentType("text/xml"); //MIME type
1214
           // Send back error message if out = null
1215
           if (pw == null)
1216
           {
1217
             // If pw is null, open the respnose
1218
            pw = response.getWriter();
1219
           }
1220
           pw.println("<?xml version=\"1.0\"?>");
1221
           pw.println("<error>");
1222
           pw.println(notFoundE.getMessage());
1223
           pw.println("</error>");
1224
           pw.close();
1225
        }
1226
        // close zout
1227
        if ( zout != null )
1228
        {
1229
          zout.close();
1230
        }
1231
        }//try
1232
        catch (IOException ie)
1233
        {
1234
          MetaCatUtil.debugMessage("Problem with the servlet output " +
1235
                           "in MetacatServlet.handleReadAction: " +
1236
                           ie.getMessage(), 30);
1237
        }//cathch
1238
      }//catch
1239
    }// catch McdbDocNotFoundException
1240
    catch (Exception e)
1241
    {
1242
      try {
1243

    
1244
        if (out != null) {
1245
            response.setContentType("text/xml"); //MIME type
1246
            pw = new PrintWriter(out);
1247
            pw.println("<?xml version=\"1.0\"?>");
1248
            pw.println("<error>");
1249
            pw.println(e.getMessage());
1250
            pw.println("</error>");
1251
            pw.close();
1252
            out.close();
1253
        }
1254
        else
1255
        {
1256
           response.setContentType("text/xml"); //MIME type
1257
           // Send back error message if out = null
1258
           if ( pw == null)
1259
           {
1260
            pw = response.getWriter();
1261
           }
1262
           pw.println("<?xml version=\"1.0\"?>");
1263
           pw.println("<error>");
1264
           pw.println(e.getMessage());
1265
           pw.println("</error>");
1266
           pw.close();
1267

    
1268
        }
1269
        // Close zip output stream
1270
        if ( zout != null ) { zout.close(); }
1271

    
1272
      } catch (IOException ioe) {
1273
        MetaCatUtil.debugMessage("Problem with the servlet output " +
1274
                           "in MetacatServlet.handleReadAction: " +
1275
                           ioe.getMessage(), 30);
1276
        ioe.printStackTrace(System.out);
1277

    
1278
      }
1279

    
1280
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadAction: " +
1281
                               e.getMessage(), 30);
1282
      //e.printStackTrace(System.out);
1283
    }
1284

    
1285
  }
1286

    
1287
  // read metadata or data from Metacat
1288
  private void readFromMetacat(HttpServletResponse response, String docid,
1289
                               String qformat, String abstrpath, String user,
1290
                               String[] groups, boolean zip,
1291
                               ZipOutputStream zout, boolean withInlineData,
1292
                               Hashtable params)
1293
               throws ClassNotFoundException, IOException, SQLException,
1294
                      McdbException, Exception
1295
  {
1296

    
1297
    try {
1298

    
1299

    
1300
      DocumentImpl doc = new DocumentImpl(docid);
1301

    
1302
      //check the permission for read
1303
      if (!doc.hasReadPermission(user, groups, docid))
1304
      {
1305
        Exception e = new Exception("User " + user + " does not have permission"
1306
                       +" to read the document with the docid " + docid);
1307

    
1308
        throw e;
1309
      }
1310

    
1311
      if ( doc.getRootNodeID() == 0 ) {
1312
        // this is data file
1313
        String filepath = util.getOption("datafilepath");
1314
        if(!filepath.endsWith("/")) {
1315
          filepath += "/";
1316
        }
1317
        String filename = filepath + docid;
1318
        FileInputStream fin = null;
1319
        fin = new FileInputStream(filename);
1320

    
1321
        //MIME type
1322
        String contentType = getServletContext().getMimeType(filename);
1323
        if (contentType == null)
1324
        {
1325
          ContentTypeProvider provider = new ContentTypeProvider(docid);
1326
          contentType = provider.getContentType();
1327
          MetaCatUtil.debugMessage("Final contenttype is: "+ contentType, 30);
1328
        }
1329

    
1330
        response.setContentType(contentType);
1331
        // if we decide to use "application/octet-stream" for all data returns
1332
        // response.setContentType("application/octet-stream");
1333

    
1334
        try {
1335

    
1336
          ServletOutputStream out = response.getOutputStream();
1337
          byte[] buf = new byte[4 * 1024]; // 4K buffer
1338
          int b = fin.read(buf);
1339
          while (b != -1) {
1340
            out.write(buf, 0, b);
1341
            b = fin.read(buf);
1342
          }
1343
        } finally {
1344
          if (fin != null) fin.close();
1345
        }
1346

    
1347
      } else {
1348
        // this is metadata doc
1349
        if ( qformat.equals("xml") ) {
1350

    
1351
          // set content type first
1352
          response.setContentType("text/xml");   //MIME type
1353
          PrintWriter out = response.getWriter();
1354
          doc.toXml(out, user, groups, withInlineData);
1355
        } else {
1356
          response.setContentType("text/html");  //MIME type
1357
          PrintWriter out = response.getWriter();
1358

    
1359
          // Look up the document type
1360
          String doctype = doc.getDoctype();
1361
          // Transform the document to the new doctype
1362
          DBTransform dbt = new DBTransform();
1363
          dbt.transformXMLDocument(doc.toString(user, groups, withInlineData),
1364
                                   doctype,"-//W3C//HTML//EN",
1365
                                   qformat, out, params);
1366
        }
1367

    
1368
      }
1369
    }
1370
    catch (Exception except)
1371
    {
1372
      throw except;
1373

    
1374
    }
1375

    
1376
  }
1377

    
1378
  // read data from URLConnection
1379
  private void readFromURLConnection(HttpServletResponse response, String docid)
1380
               throws IOException, MalformedURLException
1381
  {
1382
    ServletOutputStream out = response.getOutputStream();
1383
    String contentType = getServletContext().getMimeType(docid); //MIME type
1384
    if (contentType == null) {
1385
      if (docid.endsWith(".xml")) {
1386
        contentType="text/xml";
1387
      } else if (docid.endsWith(".css")) {
1388
        contentType="text/css";
1389
      } else if (docid.endsWith(".dtd")) {
1390
        contentType="text/plain";
1391
      } else if (docid.endsWith(".xsd")) {
1392
        contentType="text/xml";
1393
      } else if (docid.endsWith("/")) {
1394
        contentType="text/html";
1395
      } else {
1396
        File f = new File(docid);
1397
        if ( f.isDirectory() ) {
1398
          contentType="text/html";
1399
        } else {
1400
          contentType="application/octet-stream";
1401
        }
1402
      }
1403
    }
1404
    response.setContentType(contentType);
1405
    // if we decide to use "application/octet-stream" for all data returns
1406
    // response.setContentType("application/octet-stream");
1407

    
1408
    // this is http url
1409
    URL url = new URL(docid);
1410
    BufferedInputStream bis = null;
1411
    try {
1412
      bis = new BufferedInputStream(url.openStream());
1413
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1414
      int b = bis.read(buf);
1415
      while (b != -1) {
1416
        out.write(buf, 0, b);
1417
        b = bis.read(buf);
1418
      }
1419
    } finally {
1420
      if (bis != null) bis.close();
1421
    }
1422

    
1423
  }
1424

    
1425
  // read file/doc and write to ZipOutputStream
1426
  private void addDocToZip(String docid, ZipOutputStream zout,
1427
                              String user, String[] groups)
1428
               throws ClassNotFoundException, IOException, SQLException,
1429
                      McdbException, Exception
1430
  {
1431
    byte[] bytestring = null;
1432
    ZipEntry zentry = null;
1433

    
1434
    try {
1435
      URL url = new URL(docid);
1436

    
1437
      // this http url; read from URLConnection; add to zip
1438
      zentry = new ZipEntry(docid);
1439
      zout.putNextEntry(zentry);
1440
      BufferedInputStream bis = null;
1441
      try {
1442
        bis = new BufferedInputStream(url.openStream());
1443
        byte[] buf = new byte[4 * 1024]; // 4K buffer
1444
        int b = bis.read(buf);
1445
        while(b != -1) {
1446
          zout.write(buf, 0, b);
1447
          b = bis.read(buf);
1448
        }
1449
      } finally {
1450
        if (bis != null) bis.close();
1451
      }
1452
      zout.closeEntry();
1453

    
1454
    } catch (MalformedURLException mue) {
1455

    
1456
      // this is metacat doc (data file or metadata doc)
1457

    
1458
      try {
1459

    
1460
        DocumentImpl doc = new DocumentImpl(docid);
1461

    
1462
        //check the permission for read
1463
        if (!doc.hasReadPermission(user, groups, docid))
1464
        {
1465
          Exception e = new Exception("User " + user + " does not have "
1466
                    +"permission to read the document with the docid " + docid);
1467

    
1468
          throw e;
1469
        }
1470

    
1471
        if ( doc.getRootNodeID() == 0 ) {
1472
          // this is data file; add file to zip
1473
          String filepath = util.getOption("datafilepath");
1474
          if(!filepath.endsWith("/")) {
1475
            filepath += "/";
1476
          }
1477
          String filename = filepath + docid;
1478
          FileInputStream fin = null;
1479
          fin = new FileInputStream(filename);
1480
          try {
1481

    
1482
            zentry = new ZipEntry(docid);
1483
            zout.putNextEntry(zentry);
1484
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1485
            int b = fin.read(buf);
1486
            while (b != -1) {
1487
              zout.write(buf, 0, b);
1488
              b = fin.read(buf);
1489
            }
1490
          } finally {
1491
            if (fin != null) fin.close();
1492
          }
1493
          zout.closeEntry();
1494

    
1495
        } else {
1496
          // this is metadata doc; add doc to zip
1497
          bytestring = doc.toString().getBytes();
1498
          zentry = new ZipEntry(docid + ".xml");
1499
          zentry.setSize(bytestring.length);
1500
          zout.putNextEntry(zentry);
1501
          zout.write(bytestring, 0, bytestring.length);
1502
          zout.closeEntry();
1503
        }
1504
      } catch (Exception except) {
1505
        throw except;
1506

    
1507
      }
1508

    
1509
    }
1510

    
1511
  }
1512

    
1513
  // view abstract within document
1514
  private void viewAbstract(HttpServletResponse response,
1515
                            String abstractpath, String docid)
1516
               throws ClassNotFoundException, IOException, SQLException,
1517
                      McdbException, Exception
1518
  {
1519

    
1520
    PrintWriter out =null;
1521
    try {
1522

    
1523
      response.setContentType("text/html");  //MIME type
1524
      out = response.getWriter();
1525
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid);
1526
      out.println("<html><head><title>Abstract</title></head>");
1527
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
1528
      for (int i=0; i<abstracts.length; i++) {
1529
        out.println("<p>" + (String)abstracts[i] + "</p>");
1530
      }
1531
      out.println("</body></html>");
1532

    
1533
    } catch (Exception e) {
1534
       out.println("<?xml version=\"1.0\"?>");
1535
       out.println("<error>");
1536
       out.println(e.getMessage());
1537
       out.println("</error>");
1538

    
1539

    
1540
    }
1541
  }
1542
  /**
1543
   * If metacat couldn't find a data file or document locally, it will read this
1544
   * docid from its home server. This is for the replication feature
1545
   */
1546
  private void readFromRemoteMetaCat(HttpServletResponse response, String docid,
1547
                     String rev, String user, String password,
1548
                     ServletOutputStream out, boolean zip, ZipOutputStream zout)
1549
                        throws Exception
1550
 {
1551
   // Create a object of RemoteDocument, "" is for zipEntryPath
1552
   RemoteDocument remoteDoc =
1553
                        new RemoteDocument (docid, rev,user, password, "");
1554
   String docType = remoteDoc.getDocType();
1555
   // Only read data file
1556
   if (docType.equals("BIN"))
1557
   {
1558
    // If it is zip format
1559
    if (zip)
1560
    {
1561
      remoteDoc.readDocumentFromRemoteServerByZip(zout);
1562
    }//if
1563
    else
1564
    {
1565
      if (out == null)
1566
      {
1567
        out = response.getOutputStream();
1568
      }//if
1569
      response.setContentType("application/octet-stream");
1570
      remoteDoc.readDocumentFromRemoteServer(out);
1571
    }//else (not zip)
1572
   }//if doctype=bin
1573
   else
1574
   {
1575
     throw new Exception("Docid: "+docid+"."+rev+" couldn't find");
1576
   }//else
1577
 }//readFromRemoteMetaCat
1578

    
1579
  // END OF READ SECTION
1580

    
1581

    
1582

    
1583
  // INSERT/UPDATE SECTION
1584
  /**
1585
   * Handle the database putdocument request and write an XML document
1586
   * to the database connection
1587
   */
1588
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1589
               String user, String[] groups) {
1590

    
1591
    DBConnection dbConn = null;
1592
    int serialNumber = -1;
1593

    
1594
    try {
1595
      // Get the document indicated
1596
      String[] doctext = (String[])params.get("doctext");
1597

    
1598
      String pub = null;
1599
      if (params.containsKey("public")) {
1600
        pub = ((String[])params.get("public"))[0];
1601
      }
1602

    
1603
      StringReader dtd = null;
1604
      if (params.containsKey("dtdtext")) {
1605
        String[] dtdtext = (String[])params.get("dtdtext");
1606
        try {
1607
          if ( !dtdtext[0].equals("") ) {
1608
            dtd = new StringReader(dtdtext[0]);
1609
          }
1610
        } catch (NullPointerException npe) {}
1611
      }
1612

    
1613
      StringReader xml = new StringReader(doctext[0]);
1614
      boolean validate = false;
1615
      DocumentImplWrapper documentWrapper = null;
1616
      try {
1617
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1618
        // in order to decide whether to use validation parser
1619
        validate = needDTDValidation(xml);
1620
        if (validate)
1621
        {
1622
          // set a dtd base validation parser
1623
          String rule = DocumentImpl.DTD;
1624
          documentWrapper = new DocumentImplWrapper(rule, validate);
1625
        }
1626
        else if (needSchemaValidation(xml))
1627
        {
1628
          // for eml2
1629
          if (needEml2Validation(xml))
1630
          {
1631
             // set eml2 base validation parser
1632
            String rule = DocumentImpl.EML2;
1633
            // using emlparser to check id validation
1634
            EMLParser parser = new EMLParser(doctext[0]);
1635
            documentWrapper = new DocumentImplWrapper(rule, true);
1636
          }
1637
          else
1638
          {
1639
            // set schema base validation parser
1640
            String rule = DocumentImpl.SCHEMA;
1641
            documentWrapper = new DocumentImplWrapper(rule, true);
1642
          }
1643
        }
1644
        else
1645
        {
1646
          documentWrapper = new DocumentImplWrapper("", false);
1647
        }
1648

    
1649
        String[] action = (String[])params.get("action");
1650
        String[] docid = (String[])params.get("docid");
1651
        String newdocid = null;
1652

    
1653
        String doAction = null;
1654
        if (action[0].equals("insert")) {
1655
          doAction = "INSERT";
1656
        } else if (action[0].equals("update")) {
1657
          doAction = "UPDATE";
1658
        }
1659

    
1660
        try
1661
        {
1662
          // get a connection from the pool
1663
          dbConn=DBConnectionPool.
1664
                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1665
          serialNumber=dbConn.getCheckOutSerialNumber();
1666

    
1667
           // write the document to the database
1668
          try
1669
          {
1670
            String accNumber = docid[0];
1671
            MetaCatUtil.debugMessage(""+ doAction + " " + accNumber +"...", 10);
1672
            if (accNumber.equals(""))
1673
            {
1674
              accNumber = null;
1675
            }//if
1676
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1677
                                          accNumber, user, groups);
1678

    
1679
          }//try
1680
          catch (NullPointerException npe)
1681
          {
1682
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1683
                                          null, user, groups);
1684
          }//catch
1685

    
1686
        }//try
1687
        finally
1688
        {
1689
          // Return db connection
1690
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1691
        }
1692

    
1693
        // set content type and other response header fields first
1694
        //response.setContentType("text/xml");
1695
        out.println("<?xml version=\"1.0\"?>");
1696
        out.println("<success>");
1697
        out.println("<docid>" + newdocid + "</docid>");
1698
        out.println("</success>");
1699

    
1700
      }
1701
      catch (NullPointerException npe)
1702
      {
1703
        //response.setContentType("text/xml");
1704
        out.println("<?xml version=\"1.0\"?>");
1705
        out.println("<error>");
1706
        out.println(npe.getMessage());
1707
        out.println("</error>");
1708
      }
1709
    }
1710
    catch (Exception e)
1711
    {
1712
      //response.setContentType("text/xml");
1713
      out.println("<?xml version=\"1.0\"?>");
1714
      out.println("<error>");
1715
      out.println(e.getMessage());
1716
      out.println("</error>");
1717
    }
1718
  }
1719

    
1720
  /**
1721
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1722
   * in order to decide whether to use validation parser
1723
   */
1724
  private static boolean needDTDValidation(StringReader xmlreader) throws 
1725
                                                             IOException 
1726
  {
1727

    
1728
    
1729
    StringBuffer cbuff = new StringBuffer();
1730
    java.util.Stack st = new java.util.Stack();
1731
    boolean validate = false;
1732
    int c;
1733
    int inx;
1734

    
1735
    // read from the stream until find the keywords
1736
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1737
      cbuff.append((char)c);
1738

    
1739
      // "<!DOCTYPE" keyword is found; put it in the stack
1740
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1741
        cbuff = new StringBuffer();
1742
        st.push("<!DOCTYPE");
1743
      }
1744
      // "PUBLIC" keyword is found; put it in the stack
1745
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1746
        cbuff = new StringBuffer();
1747
        st.push("PUBLIC");
1748
      }
1749
      // "SYSTEM" keyword is found; put it in the stack
1750
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1751
        cbuff = new StringBuffer();
1752
        st.push("SYSTEM");
1753
      }
1754
      // ">" character is found; put it in the stack
1755
      // ">" is found twice: fisrt from <?xml ...?>
1756
      // and second from <!DOCTYPE ... >
1757
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1758
        cbuff = new StringBuffer();
1759
        st.push(">");
1760
      }
1761
    }
1762

    
1763
    // close the stream
1764
    xmlreader.reset();
1765

    
1766
    // check the stack whether it contains the keywords:
1767
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1768
    if ( st.size() == 4 ) {
1769
      if ( ((String)st.pop()).equals(">") &&
1770
           ( ((String)st.peek()).equals("PUBLIC") |
1771
             ((String)st.pop()).equals("SYSTEM") ) &&
1772
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1773
        validate = true;
1774
      }
1775
    }
1776

    
1777
    MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1778
    return validate;
1779
  }
1780
  // END OF INSERT/UPDATE SECTION
1781

    
1782
  /* check if the xml string contains key words to specify schema loocation*/
1783
  private boolean needSchemaValidation(StringReader xml) throws IOException
1784
  {
1785
    boolean needSchemaValidate =false;
1786
    if (xml == null)
1787
    {
1788
      MetaCatUtil.debugMessage("Validation for schema is " +
1789
                               needSchemaValidate, 10);
1790
      return needSchemaValidate;
1791
    }
1792
    System.out.println("before get target line");
1793
    String targetLine = getSchemaLine(xml);
1794
    System.out.println("before get target line");
1795
    // to see if the second line contain some keywords
1796
    if (targetLine != null && (targetLine.indexOf(SCHEMALOCATIONKEYWORD) != -1||
1797
             targetLine.indexOf(NONAMESPACELOCATION) != -1 ))
1798
    {
1799
      // if contains schema location key word, should be validate
1800
      needSchemaValidate = true;
1801
    }
1802

    
1803
    MetaCatUtil.debugMessage("Validation for schema is " +
1804
                             needSchemaValidate, 10);
1805
    return needSchemaValidate;
1806

    
1807
  }
1808

    
1809
   /* check if the xml string contains key words to specify schema loocation*/
1810
  private boolean needEml2Validation(StringReader xml) throws IOException
1811
  {
1812
    boolean needEml2Validate =false;
1813
    String emlNameSpace =DocumentImpl.EMLNAMESPACE;
1814
    String schemaLocationContent = null;
1815
    if (xml == null)
1816
    {
1817
      MetaCatUtil.debugMessage("Validation for schema is " +
1818
                               needEml2Validate, 10);
1819
      return needEml2Validate;
1820
    }
1821
    String targetLine = getSchemaLine(xml);
1822

    
1823
    if (targetLine != null)
1824
    {
1825
      
1826
      int startIndex = targetLine.indexOf(SCHEMALOCATIONKEYWORD);
1827
      int start = 1;
1828
      int end   = 1;
1829
      String schemaLocation = null;
1830
      int count = 0;
1831
      if (startIndex != -1)
1832
      {
1833
        for ( int i=startIndex; i<targetLine.length(); i++)
1834
        {
1835
          if (targetLine.charAt(i) =='"')
1836
          {
1837
            count ++;
1838
          }
1839
          if (targetLine.charAt(i) =='"' && count == 1)
1840
          {
1841
            start = i;
1842
          }
1843
          if (targetLine.charAt(i) =='"' && count == 2)
1844
          {
1845
            end = i;
1846
            break;
1847
          }
1848
        }
1849
      }
1850
      schemaLocation = targetLine.substring(start+1, end);
1851
      MetaCatUtil.debugMessage("schemaLocation in xml is: "+schemaLocation, 30);
1852
      if ( schemaLocation.indexOf(emlNameSpace) != -1)
1853
      {
1854
        needEml2Validate = true;
1855
      }
1856
    }
1857

    
1858
    MetaCatUtil.debugMessage("Validation for eml is " +
1859
                             needEml2Validate, 10);
1860
    return needEml2Validate;
1861

    
1862
  }
1863

    
1864
  private String getSchemaLine(StringReader xml) throws IOException
1865
  {
1866
    // find the line
1867
    String secondLine = null;
1868
    int count =0;
1869
    int endIndex = 0;
1870
    int startIndex = 0;
1871
    final int TARGETNUM = 2;
1872
    StringBuffer buffer = new StringBuffer();
1873
    boolean comment =false;
1874
    char thirdPreviousCharacter = '?';
1875
    char secondPreviousCharacter ='?';
1876
    char previousCharacter = '?';
1877
    char currentCharacter = '?';
1878
    
1879
    while ( (currentCharacter = (char) xml.read()) != -1)
1880
    {
1881
      //in a comment
1882
      if (currentCharacter =='-' && previousCharacter == '-'  && 
1883
          secondPreviousCharacter =='!' && thirdPreviousCharacter == '<')
1884
      {
1885
        comment = true;
1886
      }
1887
      //out of comment
1888
      if (comment && currentCharacter == '>' && previousCharacter == '-' && 
1889
          secondPreviousCharacter =='-')
1890
      {
1891
         comment = false;
1892
      }
1893
      
1894
      //this is not comment
1895
      if (currentCharacter !='!' && previousCharacter == '<' && !comment)
1896
      {
1897
        count ++;
1898
      }
1899
      // get target line
1900
      if (count == TARGETNUM && currentCharacter !='>')
1901
      {
1902
        buffer.append(currentCharacter);
1903
      }
1904
      if (count == TARGETNUM && currentCharacter == '>')
1905
      {
1906
          break;
1907
      }
1908
      thirdPreviousCharacter = secondPreviousCharacter;
1909
      secondPreviousCharacter = previousCharacter;
1910
      previousCharacter = currentCharacter;
1911
      
1912
    }
1913
    secondLine = buffer.toString();
1914
    MetaCatUtil.debugMessage("the second line string is: "+secondLine, 25);
1915
    xml.reset();
1916
    return secondLine;
1917
  }
1918

    
1919
  // DELETE SECTION
1920
  /**
1921
   * Handle the database delete request and delete an XML document
1922
   * from the database connection
1923
   */
1924
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1925
               HttpServletResponse response, String user, String[] groups) {
1926

    
1927
    String[] docid = (String[])params.get("docid");
1928

    
1929
    // delete the document from the database
1930
    try {
1931

    
1932
                                      // NOTE -- NEED TO TEST HERE
1933
                                      // FOR EXISTENCE OF DOCID PARAM
1934
                                      // BEFORE ACCESSING ARRAY
1935
      try {
1936
        DocumentImpl.delete(docid[0], user, groups);
1937
        response.setContentType("text/xml");
1938
        out.println("<?xml version=\"1.0\"?>");
1939
        out.println("<success>");
1940
        out.println("Document deleted.");
1941
        out.println("</success>");
1942
      } catch (AccessionNumberException ane) {
1943
        response.setContentType("text/xml");
1944
        out.println("<?xml version=\"1.0\"?>");
1945
        out.println("<error>");
1946
        out.println("Error deleting document!!!");
1947
        out.println(ane.getMessage());
1948
        out.println("</error>");
1949
      }
1950
    } catch (Exception e) {
1951
      response.setContentType("text/xml");
1952
      out.println("<?xml version=\"1.0\"?>");
1953
      out.println("<error>");
1954
      out.println(e.getMessage());
1955
      out.println("</error>");
1956
    }
1957
  }
1958
  // END OF DELETE SECTION
1959

    
1960
  // VALIDATE SECTION
1961
  /**
1962
   * Handle the validation request and return the results to the requestor
1963
   */
1964
  private void handleValidateAction(PrintWriter out, Hashtable params) {
1965

    
1966
    // Get the document indicated
1967
    String valtext = null;
1968
    DBConnection dbConn = null;
1969
    int serialNumber = -1;
1970

    
1971
    try {
1972
      valtext = ((String[])params.get("valtext"))[0];
1973
    } catch (Exception nullpe) {
1974

    
1975

    
1976
      String docid = null;
1977
      try {
1978
        // Find the document id number
1979
        docid = ((String[])params.get("docid"))[0];
1980

    
1981

    
1982
        // Get the document indicated from the db
1983
        DocumentImpl xmldoc = new DocumentImpl(docid);
1984
        valtext = xmldoc.toString();
1985

    
1986
      } catch (NullPointerException npe) {
1987

    
1988
        out.println("<error>Error getting document ID: " + docid + "</error>");
1989
        //if ( conn != null ) { util.returnConnection(conn); }
1990
        return;
1991
      } catch (Exception e) {
1992

    
1993
        out.println(e.getMessage());
1994
      }
1995
    }
1996

    
1997

    
1998
    try {
1999
      // get a connection from the pool
2000
      dbConn=DBConnectionPool.
2001
                  getDBConnection("MetaCatServlet.handleValidateAction");
2002
      serialNumber=dbConn.getCheckOutSerialNumber();
2003
      DBValidate valobj = new DBValidate(saxparser,dbConn);
2004
      boolean valid = valobj.validateString(valtext);
2005

    
2006
      // set content type and other response header fields first
2007

    
2008
      out.println(valobj.returnErrors());
2009

    
2010
    } catch (NullPointerException npe2) {
2011
      // set content type and other response header fields first
2012

    
2013
      out.println("<error>Error validating document.</error>");
2014
    } catch (Exception e) {
2015

    
2016
      out.println(e.getMessage());
2017
    } finally {
2018
      // Return db connection
2019
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2020
    }
2021
  }
2022
  // END OF VALIDATE SECTION
2023

    
2024
  // OTHER ACTION HANDLERS
2025

    
2026
  /**
2027
   * Handle "getrevsionanddoctype" action
2028
   * Given a docid, return it's current revision and doctype from data base
2029
   * The output is String look like "rev;doctype"
2030
   */
2031
  private void handleGetRevisionAndDocTypeAction(PrintWriter out,
2032
                                                              Hashtable params)
2033
  {
2034
    // To store doc parameter
2035
    String [] docs = new String[10];
2036
    // Store a single doc id
2037
    String givenDocId = null;
2038
    // Get docid from parameters
2039
    if (params.containsKey("docid"))
2040
    {
2041
      docs = (String[])params.get("docid");
2042
    }
2043
    // Get first docid form string array
2044
    givenDocId = docs[0];
2045

    
2046
    try
2047
    {
2048
      // Make sure there is a docid
2049
      if (givenDocId == null || givenDocId.equals(""))
2050
      {
2051
        throw new Exception("User didn't specify docid!");
2052
      }//if
2053

    
2054
      // Create a DBUtil object
2055
      DBUtil dbutil = new DBUtil();
2056
      // Get a rev and doctype
2057
      String revAndDocType =
2058
                dbutil.getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
2059
      out.println(revAndDocType);
2060

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

    
2071
  }//handleGetRevisionAndDocTypeAction
2072

    
2073
  /**
2074
   * Handle "getaccesscontrol" action.
2075
   * Read Access Control List from db connection in XML format
2076
   */
2077
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
2078
                                       HttpServletResponse response,
2079
                                       String username, String[] groupnames) {
2080

    
2081
    DBConnection dbConn = null;
2082
    int serialNumber = -1;
2083
    String docid = ((String[])params.get("docid"))[0];
2084

    
2085
    try {
2086

    
2087
        // get connection from the pool
2088
        dbConn=DBConnectionPool.
2089
                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2090
        serialNumber=dbConn.getCheckOutSerialNumber();
2091
        AccessControlList aclobj = new AccessControlList(dbConn);
2092
        String acltext = aclobj.getACL(docid, username, groupnames);
2093
        out.println(acltext);
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
    } finally {
2101
      // Retrun db connection to pool
2102
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2103
    }
2104

    
2105
  }
2106

    
2107
  /**
2108
   * Handle the "getprincipals" action.
2109
   * Read all principals from authentication scheme in XML format
2110
   */
2111
  private void handleGetPrincipalsAction(PrintWriter out, String user,
2112
                                         String password) {
2113

    
2114

    
2115
    try {
2116

    
2117

    
2118
        AuthSession auth = new AuthSession();
2119
        String principals = auth.getPrincipals(user, password);
2120
        out.println(principals);
2121

    
2122
    } catch (Exception e) {
2123
      out.println("<?xml version=\"1.0\"?>");
2124
      out.println("<error>");
2125
      out.println(e.getMessage());
2126
      out.println("</error>");
2127
    }
2128

    
2129
  }
2130

    
2131
  /**
2132
   * Handle "getdoctypes" action.
2133
   * Read all doctypes from db connection in XML format
2134
   */
2135
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
2136
                                       HttpServletResponse response) {
2137

    
2138

    
2139
    try {
2140

    
2141

    
2142
        DBUtil dbutil = new DBUtil();
2143
        String doctypes = dbutil.readDoctypes();
2144
        out.println(doctypes);
2145

    
2146
    } catch (Exception e) {
2147
      out.println("<?xml version=\"1.0\"?>");
2148
      out.println("<error>");
2149
      out.println(e.getMessage());
2150
      out.println("</error>");
2151
    }
2152

    
2153
  }
2154

    
2155
  /**
2156
   * Handle the "getdtdschema" action.
2157
   * Read DTD or Schema file for a given doctype from Metacat catalog system
2158
   */
2159
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2160
                                        HttpServletResponse response) {
2161

    
2162

    
2163
    String doctype = null;
2164
    String[] doctypeArr = (String[])params.get("doctype");
2165

    
2166
    // get only the first doctype specified in the list of doctypes
2167
    // it could be done for all doctypes in that list
2168
    if (doctypeArr != null) {
2169
        doctype = ((String[])params.get("doctype"))[0];
2170
    }
2171

    
2172
    try {
2173

    
2174

    
2175
        DBUtil dbutil = new DBUtil();
2176
        String dtdschema = dbutil.readDTDSchema(doctype);
2177
        out.println(dtdschema);
2178

    
2179
    } catch (Exception e) {
2180
      out.println("<?xml version=\"1.0\"?>");
2181
      out.println("<error>");
2182
      out.println(e.getMessage());
2183
      out.println("</error>");
2184
    }
2185

    
2186
  }
2187

    
2188
  /**
2189
   * Handle the "getdataguide" action.
2190
   * Read Data Guide for a given doctype from db connection in XML format
2191
   */
2192
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
2193
                                        HttpServletResponse response) {
2194

    
2195

    
2196
    String doctype = null;
2197
    String[] doctypeArr = (String[])params.get("doctype");
2198

    
2199
    // get only the first doctype specified in the list of doctypes
2200
    // it could be done for all doctypes in that list
2201
    if (doctypeArr != null) {
2202
        doctype = ((String[])params.get("doctype"))[0];
2203
    }
2204

    
2205
    try {
2206

    
2207

    
2208
        DBUtil dbutil = new DBUtil();
2209
        String dataguide = dbutil.readDataGuide(doctype);
2210
        out.println(dataguide);
2211

    
2212
    } catch (Exception e) {
2213
      out.println("<?xml version=\"1.0\"?>");
2214
      out.println("<error>");
2215
      out.println(e.getMessage());
2216
      out.println("</error>");
2217
    }
2218

    
2219
  }
2220

    
2221
  /**
2222
   * Handle the "getlastdocid" action.
2223
   * Get the latest docid with rev number from db connection in XML format
2224
   */
2225
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2226
                                        HttpServletResponse response) {
2227

    
2228

    
2229
    String scope = ((String[])params.get("scope"))[0];
2230
    if (scope == null) {
2231
        scope = ((String[])params.get("username"))[0];
2232
    }
2233

    
2234
    try {
2235

    
2236

    
2237
        DBUtil dbutil = new DBUtil();
2238
        String lastDocid = dbutil.getMaxDocid(scope);
2239
        out.println("<?xml version=\"1.0\"?>");
2240
        out.println("<lastDocid>");
2241
        out.println("  <scope>" + scope + "</scope>");
2242
        out.println("  <docid>" + lastDocid + "</docid>");
2243
        out.println("</lastDocid>");
2244

    
2245
    } catch (Exception e) {
2246
      out.println("<?xml version=\"1.0\"?>");
2247
      out.println("<error>");
2248
      out.println(e.getMessage());
2249
      out.println("</error>");
2250
    }
2251

    
2252
  }
2253

    
2254
  /**
2255
   * Handle documents passed to metacat that are encoded using the
2256
   * "multipart/form-data" mime type.  This is typically used for uploading
2257
   * data files which may be binary and large.
2258
   */
2259
  private void handleMultipartForm(HttpServletRequest request,
2260
                                   HttpServletResponse response)
2261
  {
2262
    PrintWriter out = null;
2263
    String action = null;
2264

    
2265
    // Parse the multipart form, and save the parameters in a Hashtable and
2266
    // save the FileParts in a hashtable
2267

    
2268
    Hashtable params = new Hashtable();
2269
    Hashtable fileList = new Hashtable();
2270
    int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2271
                                                                   .intValue();
2272
    MetaCatUtil.debugMessage("The limit size of data file is: "+sizeLimit, 50);
2273

    
2274
    try {
2275
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
2276
      MultipartParser mp = new MultipartParser(request, sizeLimit*1024*1024);
2277
      Part part;
2278
      while ((part = mp.readNextPart()) != null) {
2279
        String name = part.getName();
2280

    
2281
        if (part.isParam()) {
2282
          // it's a parameter part
2283
          ParamPart paramPart = (ParamPart) part;
2284
          String value = paramPart.getStringValue();
2285
          params.put(name, value);
2286
          if (name.equals("action")) {
2287
            action = value;
2288
          }
2289
        } else if (part.isFile()) {
2290
          // it's a file part
2291
          FilePart filePart = (FilePart) part;
2292
          fileList.put(name, filePart);
2293

    
2294
          // Stop once the first file part is found, otherwise going onto the
2295
          // next part prevents access to the file contents.  So...for upload
2296
          // to work, the datafile must be the last part
2297
          break;
2298
        }
2299
      }
2300
    } catch (IOException ioe) {
2301
      try {
2302
        out = response.getWriter();
2303
      } catch (IOException ioe2) {
2304
        System.err.println("Fatal Error: couldn't get response output stream.");
2305
      }
2306
      out.println("<?xml version=\"1.0\"?>");
2307
      out.println("<error>");
2308
      out.println("Error: problem reading multipart data.");
2309
      out.println("</error>");
2310
    }
2311

    
2312
    // Get the session information
2313
    String username = null;
2314
    String password = null;
2315
    String[] groupnames = null;
2316
    String sess_id = null;
2317

    
2318
    // be aware of session expiration on every request
2319
    HttpSession sess = request.getSession(true);
2320
    if (sess.isNew()) {
2321
      // session expired or has not been stored b/w user requests
2322
      username = "public";
2323
      sess.setAttribute("username", username);
2324
    } else {
2325
      username = (String)sess.getAttribute("username");
2326
      password = (String)sess.getAttribute("password");
2327
      groupnames = (String[])sess.getAttribute("groupnames");
2328
      try {
2329
        sess_id = (String)sess.getId();
2330
      } catch(IllegalStateException ise) {
2331
        System.out.println("error in  handleMultipartForm: this shouldn't " +
2332
                           "happen: the session should be valid: " +
2333
                           ise.getMessage());
2334
      }
2335
    }
2336

    
2337
    // Get the out stream
2338
    try {
2339
          out = response.getWriter();
2340
        } catch (IOException ioe2) {
2341
          util.debugMessage("Fatal Error: couldn't get response "+
2342
                             "output stream.", 30);
2343
        }
2344

    
2345
    if ( action.equals("upload")) {
2346
      if (username != null &&  !username.equals("public")) {
2347
        handleUploadAction(request, out, params, fileList,
2348
                           username, groupnames);
2349
      } else {
2350

    
2351
        out.println("<?xml version=\"1.0\"?>");
2352
        out.println("<error>");
2353
        out.println("Permission denied for " + action);
2354
        out.println("</error>");
2355
      }
2356
    } else {
2357
      /*try {
2358
        out = response.getWriter();
2359
      } catch (IOException ioe2) {
2360
        System.err.println("Fatal Error: couldn't get response output stream.");
2361
      }*/
2362
      out.println("<?xml version=\"1.0\"?>");
2363
      out.println("<error>");
2364
      out.println("Error: action not registered.  Please report this error.");
2365
      out.println("</error>");
2366
    }
2367
    out.close();
2368
  }
2369

    
2370
  /**
2371
   * Handle the upload action by saving the attached file to disk and
2372
   * registering it in the Metacat db
2373
   */
2374
  private void handleUploadAction(HttpServletRequest request,
2375
                                  PrintWriter out,
2376
                                  Hashtable params, Hashtable fileList,
2377
                                  String username, String[] groupnames)
2378
  {
2379
    //PrintWriter out = null;
2380
    //Connection conn = null;
2381
    String action = null;
2382
    String docid = null;
2383

    
2384
    /*response.setContentType("text/xml");
2385
    try
2386
    {
2387
      out = response.getWriter();
2388
    }
2389
    catch (IOException ioe2)
2390
    {
2391
      System.err.println("Fatal Error: couldn't get response output stream.");
2392
    }*/
2393

    
2394
    if (params.containsKey("docid"))
2395
    {
2396
      docid = (String)params.get("docid");
2397
    }
2398

    
2399
    // Make sure we have a docid and datafile
2400
    if (docid != null && fileList.containsKey("datafile")) {
2401

    
2402
      // Get a reference to the file part of the form
2403
      FilePart filePart = (FilePart)fileList.get("datafile");
2404
      String fileName = filePart.getFileName();
2405
      MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2406

    
2407
      // Check if the right file existed in the uploaded data
2408
      if (fileName != null) {
2409

    
2410
        try
2411
        {
2412
           //MetaCatUtil.debugMessage("Upload datafile " + docid +"...", 10);
2413
           //If document get lock data file grant
2414
           if (DocumentImpl.getDataFileLockGrant(docid))
2415
           {
2416
              // register the file in the database (which generates an exception
2417
              //if the docid is not acceptable or other untoward things happen
2418
              DocumentImpl.registerDocument(fileName, "BIN", docid, username);
2419

    
2420
              // Save the data file to disk using "docid" as the name
2421
              dataDirectory.mkdirs();
2422
              File newFile = new File(dataDirectory, docid);
2423
              long size = filePart.writeTo(newFile);
2424

    
2425
              // Force replication this data file
2426
              // To data file, "insert" and update is same
2427
              // The fourth parameter is null. Because it is notification server
2428
              // and this method is in MetaCatServerlet. It is original command,
2429
              // not get force replication info from another metacat
2430
              ForceReplicationHandler frh = new ForceReplicationHandler
2431
                                                (docid, "insert", false, null);
2432

    
2433
              // set content type and other response header fields first
2434
              out.println("<?xml version=\"1.0\"?>");
2435
              out.println("<success>");
2436
              out.println("<docid>" + docid + "</docid>");
2437
              out.println("<size>" + size + "</size>");
2438
              out.println("</success>");
2439
          }//if
2440

    
2441
        } //try
2442
        catch (Exception e)
2443
        {
2444
          out.println("<?xml version=\"1.0\"?>");
2445
          out.println("<error>");
2446
          out.println(e.getMessage());
2447
          out.println("</error>");
2448
        }
2449

    
2450
      }
2451
      else
2452
      {
2453
        // the field did not contain a file
2454
        out.println("<?xml version=\"1.0\"?>");
2455
        out.println("<error>");
2456
        out.println("The uploaded data did not contain a valid file.");
2457
        out.println("</error>");
2458
      }
2459
    }
2460
    else
2461
    {
2462
      // Error bcse docid missing or file missing
2463
      out.println("<?xml version=\"1.0\"?>");
2464
      out.println("<error>");
2465
      out.println("The uploaded data did not contain a valid docid " +
2466
                  "or valid file.");
2467
      out.println("</error>");
2468
    }
2469
  }
2470

    
2471
  /*
2472
   * A method to handle set access action
2473
   */
2474
  private void handleSetAccessAction(PrintWriter out,
2475
                                   Hashtable params,
2476
                                   String username)
2477
  {
2478
    String [] docList        = null;
2479
    String [] principalList  = null;
2480
    String [] permissionList = null;
2481
    String [] permTypeList   = null;
2482
    String [] permOrderList  = null;
2483
    String permission = null;
2484
    String permType   = null;
2485
    String permOrder  = null;
2486
    Vector errorList  = new Vector();
2487
    String error      = null;
2488
    Vector successList = new Vector();
2489
    String success    = null;
2490

    
2491

    
2492
    // Get parameters
2493
    if (params.containsKey("docid"))
2494
    {
2495
      docList = (String[])params.get("docid");
2496
    }
2497
    if (params.containsKey("principal"))
2498
    {
2499
      principalList = (String[])params.get("principal");
2500
    }
2501
    if (params.containsKey("permission"))
2502
    {
2503
      permissionList = (String[])params.get("permission");
2504

    
2505
    }
2506
    if (params.containsKey("permType"))
2507
    {
2508
      permTypeList = (String[])params.get("permType");
2509

    
2510
    }
2511
    if (params.containsKey("permOrder"))
2512
    {
2513
      permOrderList = (String[])params.get("permOrder");
2514

    
2515
    }
2516

    
2517
    // Make sure the parameter is not null
2518
    if (docList == null || principalList == null || permTypeList == null ||
2519
        permissionList == null)
2520
    {
2521
      error = "Please check your parameter list, it should look like: "+
2522
              "?action=setaccess&docid=pipeline.1.1&principal=public" +
2523
              "&permission=read&permType=allow&permOrder=allowFirst";
2524
      errorList.addElement(error);
2525
      outputResponse(successList, errorList, out);
2526
      return;
2527
    }
2528

    
2529
    // Only select first element for permission, type and order
2530
    permission = permissionList[0];
2531
    permType = permTypeList[0];
2532
    if (permOrderList != null)
2533
    {
2534
       permOrder = permOrderList[0];
2535
    }
2536

    
2537
    // Get package doctype set
2538
    Vector packageSet =MetaCatUtil.getOptionList(
2539
                                    MetaCatUtil.getOption("packagedoctypeset"));
2540
    //debug
2541
    if (packageSet != null)
2542
    {
2543
      for (int i = 0; i<packageSet.size(); i++)
2544
      {
2545
        MetaCatUtil.debugMessage("doctype in package set: " +
2546
                              (String)packageSet.elementAt(i), 34);
2547
      }
2548
    }//if
2549

    
2550
    // handle every accessionNumber
2551
    for (int i=0; i <docList.length; i++)
2552
    {
2553
      String accessionNumber = docList[i];
2554
      String owner = null;
2555
      String publicId = null;
2556
      // Get document owner and public id
2557
      try
2558
      {
2559
        owner = getFieldValueForDoc(accessionNumber, "user_owner");
2560
        publicId = getFieldValueForDoc(accessionNumber, "doctype");
2561
      }//try
2562
      catch (Exception e)
2563
      {
2564
        MetaCatUtil.debugMessage("Error in handleSetAccessAction: " +
2565
                                  e.getMessage(), 30);
2566
        error = "Error in set access control for document - " + accessionNumber+
2567
                 e.getMessage();
2568
        errorList.addElement(error);
2569
        continue;
2570
      }
2571
      //check if user is the owner. Only owner can do owner
2572
      if (username == null || owner == null || !username.equals(owner))
2573
      {
2574
        error = "User - " + username + " does not have permission to set " +
2575
                "access control for docid - " + accessionNumber;
2576
        errorList.addElement(error);
2577
        continue;
2578
      }
2579

    
2580
      // If docid publicid is BIN data file or other beta4, 6 package document
2581
      // we could not do set access control. Because we don't want inconsistent
2582
      // to its access docuemnt
2583
      if (publicId!=null && packageSet!=null && packageSet.contains(publicId))
2584
      {
2585
        error = "Could not set access control to document "+ accessionNumber +
2586
                "because it is in a pakcage and it has a access file for it";
2587
        errorList.addElement(error);
2588
        continue;
2589
      }
2590

    
2591
      // for every principle
2592
      for (int j = 0; j<principalList.length; j++)
2593
      {
2594
        String principal = principalList[j];
2595
        try
2596
        {
2597
          //insert permission
2598
          AccessControlForSingleFile accessControl = new
2599
                           AccessControlForSingleFile(accessionNumber,
2600
                                    principal, permission, permType, permOrder);
2601
          accessControl.insertPermissions();
2602
          success = "Set access control to document "+ accessionNumber +
2603
                    " successfully";
2604
          successList.addElement(success);
2605
        }
2606
        catch (Exception ee)
2607
        {
2608
          MetaCatUtil.debugMessage("Erorr in handleSetAccessAction2: " +
2609
                                   ee.getMessage(), 30);
2610
          error = "Faild to set access control for document " +
2611
                  accessionNumber + " because " + ee.getMessage();
2612
          errorList.addElement(error);
2613
          continue;
2614
        }
2615
      }//for every principle
2616
    }//for every document
2617
    outputResponse(successList, errorList, out);
2618
  }//handleSetAccessAction
2619

    
2620

    
2621
  /*
2622
   * A method try to determin a docid's public id, if couldn't find null
2623
   * will be returned.
2624
   */
2625
  private String getFieldValueForDoc(String accessionNumber, String fieldName)
2626
                                      throws Exception
2627
  {
2628
    if (accessionNumber==null || accessionNumber.equals("") ||fieldName == null
2629
        || fieldName.equals(""))
2630
    {
2631
      throw new Exception("Docid or field name was not specified");
2632
    }
2633

    
2634
    PreparedStatement pstmt = null;
2635
    ResultSet rs = null;
2636
    String fieldValue = null;
2637
    String docId = null;
2638
    DBConnection conn = null;
2639
    int serialNumber = -1;
2640

    
2641
    // get rid of revision if access number has
2642
    docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2643
    try
2644
    {
2645
      //check out DBConnection
2646
      conn=DBConnectionPool.getDBConnection("MetaCatServlet.getPublicIdForDoc");
2647
      serialNumber=conn.getCheckOutSerialNumber();
2648
      pstmt = conn.prepareStatement(
2649
            "SELECT " + fieldName + " FROM xml_documents " +
2650
            "WHERE docid = ? ");
2651

    
2652
      pstmt.setString(1, docId);
2653
      pstmt.execute();
2654
      rs = pstmt.getResultSet();
2655
      boolean hasRow = rs.next();
2656
      int perm = 0;
2657
      if ( hasRow )
2658
      {
2659
        fieldValue = rs.getString(1);
2660
      }
2661
      else
2662
      {
2663
        throw new Exception("Could not find document: "+accessionNumber);
2664
      }
2665
    }//try
2666
    catch (Exception e)
2667
    {
2668
      MetaCatUtil.debugMessage("Exception in MetacatServlet.getPublicIdForDoc: "
2669
                               + e.getMessage(), 30);
2670
      throw e;
2671
    }
2672
    finally
2673
    {
2674
      try
2675
      {
2676
        rs.close();
2677
        pstmt.close();
2678

    
2679
      }
2680
      finally
2681
      {
2682
        DBConnectionPool.returnDBConnection(conn, serialNumber);
2683
      }
2684
    }
2685
    return fieldValue;
2686
  }//getFieldValueForDoc
2687

    
2688
  /*
2689
   * A method to output setAccess action result
2690
   */
2691
  private void outputResponse(Vector successList,
2692
                              Vector errorList,
2693
                              PrintWriter out)
2694
  {
2695
    boolean error = false;
2696
    boolean success = false;
2697
    // Output prolog
2698
    out.println(PROLOG);
2699
    // output success message
2700
    if ( successList != null)
2701
    {
2702
      for (int i = 0; i<successList.size(); i++)
2703
      {
2704
        out.println(SUCCESS);
2705
        out.println((String)successList.elementAt(i));
2706
        out.println(SUCCESSCLOSE);
2707
        success = true;
2708
      }//for
2709
    }//if
2710
    // output error message
2711
    if (errorList != null)
2712
    {
2713
      for (int i = 0; i<errorList.size(); i++)
2714
      {
2715
        out.println(ERROR);
2716
        out.println((String)errorList.elementAt(i));
2717
        out.println(ERRORCLOSE);
2718
        error = true;
2719
      }//for
2720
    }//if
2721

    
2722
    // if no error and no success info, send a error that nothing happened
2723
    if( !error && !success)
2724
    {
2725
      out.println(ERROR);
2726
      out.println("Nothing happend for setaccess action");
2727
      out.println(ERRORCLOSE);
2728
    }
2729

    
2730
  }//outputResponse
2731
}
(39-39/58)