Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: tao $'
10
 *     '$Date: 2004-03-31 17:49:32 -0800 (Wed, 31 Mar 2004) $'
11
 * '$Revision: 2089 $'
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
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
97
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
98
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
99
 * action=getdataguide -- retrieve a Data Guide<br>
100
 * action=getprincipals -- retrieve a list of principals in XML<br>
101
 * datadoc -- data document name (id)<br>
102
 * <p>
103
 * The particular combination of parameters that are valid for each
104
 * particular action value is quite specific.  This documentation
105
 * will be reorganized to reflect this information.
106
 */
107
public class MetaCatServlet extends HttpServlet {
108

    
109
  private ServletConfig config = null;
110
  private ServletContext context = null;
111
  private String resultStyleURL = null;
112
  private String xmlcatalogfile = null;
113
  private String saxparser = null;
114
  private String datafilepath = null;
115
  private File dataDirectory = null;
116
  private String servletpath = null;
117
  private String htmlpath = null;
118
  private PropertyResourceBundle options = null;
119
  private MetaCatUtil util = null;
120
  private DBConnectionPool connPool = null;
121
  private Hashtable sessionHash = new Hashtable();
122
  private static final String PROLOG = "<?xml version=\"1.0\"?>";
123
  private static final String SUCCESS = "<success>";
124
  private static final String SUCCESSCLOSE = "</success>";
125
  private static final String ERROR = "<error>";
126
  private static final String ERRORCLOSE = "</error>";
127
  public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
128
  public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
129
  public static final String EML2KEYWORD =":eml";
130
  public static final String XMLFORMAT = "xml";
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
          MetaCatUtil.debugMessage("in session is new or no sessionid", 40);
319
          username = "public";
320
          sess.setAttribute("username", username);
321
        }
322
        else
323
        {
324
          MetaCatUtil.debugMessage("in session is not new or " +
325
                                    " has sessionid parameter", 40);
326
          try
327
          {
328
            if(params.containsKey("sessionid"))
329
            {
330
              sess_id = ((String[])params.get("sessionid"))[0];
331
              MetaCatUtil.debugMessage("in has sessionid " + sess_id, 40);
332
              if(sessionHash.containsKey(sess_id))
333
              {
334
                MetaCatUtil.debugMessage("find the id " + sess_id +
335
                                         " in hash table", 40);
336
                sess = (HttpSession)sessionHash.get(sess_id);
337
              }
338
            }
339
            else
340
            {
341
              // we already store the session in login, so we don't need here
342
              /*MetaCatUtil.debugMessage("in no sessionid parameter ", 40);
343
              sess_id = (String)sess.getId();
344
              MetaCatUtil.debugMessage("storing the session id "+ sess_id +
345
                  " which has username " + sess.getAttribute("username") +
346
                 " into session hash in handleGetOrPost method", 35);
347
              sessionHash.put(sess_id, sess);*/
348
            }
349
          }
350
          catch(IllegalStateException ise)
351
          {
352
            System.out.println("error in handleGetOrPost: this shouldn't " +
353
                               "happen: the session should be valid: " +
354
                               ise.getMessage());
355
          }
356

    
357
          username = (String)sess.getAttribute("username");
358
          MetaCatUtil.debugMessage("The user name from session is: "+
359
                                   username, 20);
360
          password = (String)sess.getAttribute("password");
361
          groupnames = (String[])sess.getAttribute("groupnames");
362
        }
363

    
364
        //make user user username should be public
365
        if (username == null || (username.trim().equals("")))
366
        {
367
          username = "public";
368
        }
369
        MetaCatUtil.debugMessage("The user is : "+ username, 5);
370
      }
371
       // Now that we know the session is valid, we can delegate the request
372
      // to a particular action handler
373
      if(action.equals("query")) {
374
        PrintWriter out = response.getWriter();
375
        handleQuery(out,params,response,username,groupnames,sess_id);
376
        out.close();
377
      } else if(action.equals("squery")) {
378
        PrintWriter out = response.getWriter();
379
        if(params.containsKey("query")) {
380
         handleSQuery(out, params,response,username,groupnames,sess_id);
381
         out.close();
382
        } else {
383
          out.println("Illegal action squery without \"query\" parameter");
384
          out.close();
385
        }
386
      } else if (action.equals("export")) {
387

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

    
498
      //util.closeConnections();
499
      // Close the stream to the client
500
      //out.close();
501
    }
502
  }
503

    
504
  // LOGIN & LOGOUT SECTION
505
  /**
506
   * Handle the login request. Create a new session object.
507
   * Do user authentication through the session.
508
   */
509
  private void handleLoginAction(PrintWriter out, Hashtable params,
510
               HttpServletRequest request, HttpServletResponse response) {
511

    
512
    AuthSession sess = null;
513
    String un = ((String[])params.get("username"))[0];
514
    MetaCatUtil.debugMessage("user " + un + " try to login", 20);
515
    String pw = ((String[])params.get("password"))[0];
516
    String action = ((String[])params.get("action"))[0];
517
    String qformat = ((String[])params.get("qformat"))[0];
518

    
519
    try {
520
      sess = new AuthSession();
521
    } catch (Exception e) {
522
      System.out.println("error in MetacatServlet.handleLoginAction: " +
523
                          e.getMessage());
524
      out.println(e.getMessage());
525
      return;
526
    }
527
    boolean isValid = sess.authenticate(request, un, pw);
528

    
529
    //if it is authernticate is true, store the session
530
    if (isValid)
531
    {
532
      HttpSession session = sess.getSessions();
533
      String id = session.getId();
534
      MetaCatUtil.debugMessage("Store session id " + id +
535
               "which has username" + session.getAttribute("username")+
536
               " into hash in login method", 35);
537
      sessionHash.put(id, session);
538
    }
539

    
540
    // format and transform the output
541
    if (qformat.equals("xml")) {
542
      response.setContentType("text/xml");
543
      out.println(sess.getMessage());
544
    } else {
545

    
546
      try {
547

    
548
        DBTransform trans = new DBTransform();
549
        response.setContentType("text/html");
550
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
551
                                   "-//W3C//HTML//EN", qformat, out, null);
552

    
553
      } catch(Exception e) {
554

    
555
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
556
                                +e.getMessage(), 30);
557
      }
558

    
559
    // any output is returned
560
    }
561
  }
562

    
563
  /**
564
   * Handle the logout request. Close the connection.
565
   */
566
  private void handleLogoutAction(PrintWriter out, Hashtable params,
567
               HttpServletRequest request, HttpServletResponse response) {
568

    
569
    String qformat = ((String[])params.get("qformat"))[0];
570

    
571
    // close the connection
572
    HttpSession sess = request.getSession(false);
573
    MetaCatUtil.debugMessage("After get session in logout request", 40);
574
    if (sess != null)
575
    {
576
     MetaCatUtil.debugMessage("The session id " + sess.getId() +
577
                              " will be invalidate in logout action", 30);
578
     MetaCatUtil.debugMessage("The session contains user " +
579
                               sess.getAttribute("username") +
580
                               " will be invalidate in logout action", 30);
581
      sess.invalidate();
582
    }
583

    
584
    // produce output
585
    StringBuffer output = new StringBuffer();
586
    output.append("<?xml version=\"1.0\"?>");
587
    output.append("<logout>");
588
    output.append("User logged out");
589
    output.append("</logout>");
590

    
591
    //format and transform the output
592
    if (qformat.equals("xml")) {
593
      response.setContentType("text/xml");
594
      out.println(output.toString());
595
    } else {
596

    
597
      try {
598

    
599
        DBTransform trans = new DBTransform();
600
        response.setContentType("text/html");
601
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
602
                                   "-//W3C//HTML//EN", qformat, out, null);
603

    
604
      } catch(Exception e) {
605

    
606
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
607
                                  +e.getMessage(), 30);
608
      }
609
    }
610
  }
611
  // END OF LOGIN & LOGOUT SECTION
612

    
613
  // SQUERY & QUERY SECTION
614
  /**
615
   * Retreive the squery xml, execute it and display it
616
   *
617
   * @param out the output stream to the client
618
   * @param params the Hashtable of parameters that should be included
619
   * in the squery.
620
   * @param response the response object linked to the client
621
   * @param conn the database connection
622
   */
623
  protected void handleSQuery(PrintWriter out, Hashtable params,
624
                 HttpServletResponse response, String user, String[] groups,
625
                 String sessionid)
626
  {
627
    double startTime = System.currentTimeMillis()/1000;
628
    DBQuery queryobj = new DBQuery(saxparser);
629
    queryobj.findDocuments(response, out, params, user, groups, sessionid);
630
    double outPutTime = System.currentTimeMillis()/1000;
631
    MetaCatUtil.debugMessage("total search time: "+(outPutTime-startTime), 30);
632

    
633
  }
634

    
635
   /**
636
    * Create the xml query, execute it and display the results.
637
    *
638
    * @param out the output stream to the client
639
    * @param params the Hashtable of parameters that should be included
640
    * in the squery.
641
    * @param response the response object linked to the client
642
    */
643
  protected void handleQuery(PrintWriter out, Hashtable params,
644
                 HttpServletResponse response, String user, String[] groups,
645
                 String sessionid)
646
  {
647
    //create the query and run it
648
    String xmlquery = DBQuery.createSQuery(params);
649
    String []queryArray = new String[1];
650
    queryArray[0] = xmlquery;
651
    params.put("query", queryArray);
652
    double startTime = System.currentTimeMillis()/1000;
653
    DBQuery queryobj = new DBQuery(saxparser);
654
    queryobj.findDocuments(response, out, params, user, groups, sessionid);
655
    double outPutTime = System.currentTimeMillis()/1000;
656
    MetaCatUtil.debugMessage("total search time: "+(outPutTime-startTime), 30);
657

    
658

    
659
    //handleSQuery(out, params, response,user, groups, sessionid);
660
  }
661

    
662
  // END OF SQUERY & QUERY SECTION
663

    
664
 //Exoport section
665
 /**
666
   * Handle the "export" request of data package from Metacat in zip format
667
   * @param params the Hashtable of HTTP request parameters
668
   * @param response the HTTP response object linked to the client
669
   * @param user the username sent the request
670
   * @param groups the user's groupnames
671
   */
672
  private void handleExportAction(Hashtable params,
673
    HttpServletResponse response, String user, String[] groups, String passWord)
674
  {
675
    // Output stream
676
    ServletOutputStream out = null;
677
    // Zip output stream
678
    ZipOutputStream zOut = null;
679
    DocumentImpl docImpls=null;
680
    DBQuery queryObj=null;
681

    
682
    String[] docs = new String[10];
683
    String docId = "";
684

    
685
    try
686
    {
687
      // read the params
688
      if (params.containsKey("docid"))
689
      {
690
        docs = (String[])params.get("docid");
691
      }//if
692
      // Create a DBuery to handle export
693
      queryObj = new DBQuery(saxparser);
694
      // Get the docid
695
      docId=docs[0];
696
      // Make sure the client specify docid
697
      if (docId == null || docId.equals(""))
698
      {
699
        response.setContentType("text/xml"); //MIME type
700
        // Get a printwriter
701
        PrintWriter pw = response.getWriter();
702
        // Send back message
703
        pw.println("<?xml version=\"1.0\"?>");
704
        pw.println("<error>");
705
        pw.println("You didn't specify requested docid");
706
        pw.println("</error>");
707
        // Close printwriter
708
        pw.close();
709
        return;
710
      }//if
711
      // Get output stream
712
      out = response.getOutputStream();
713
      response.setContentType("application/zip"); //MIME type
714
      zOut = new ZipOutputStream(out);
715
      zOut =queryObj.getZippedPackage(docId, out, user, groups, passWord);
716
      zOut.finish(); //terminate the zip file
717
      zOut.close();  //close the zip stream
718

    
719
    }//try
720
    catch (Exception e)
721
    {
722
      try
723
      {
724
        response.setContentType("text/xml"); //MIME type
725
        // Send error message back
726
        if (out != null)
727
        {
728
            PrintWriter pw = new PrintWriter(out);
729
            pw.println("<?xml version=\"1.0\"?>");
730
            pw.println("<error>");
731
            pw.println(e.getMessage());
732
            pw.println("</error>");
733
            // Close printwriter
734
            pw.close();
735
            // Close output stream
736
            out.close();
737
        }//if
738
        // Close zip output stream
739
        if ( zOut != null )
740
        {
741
          zOut.close();
742
        }//if
743
      }//try
744
      catch (IOException ioe)
745
      {
746
        MetaCatUtil.debugMessage("Problem with the servlet output " +
747
                           "in MetacatServlet.handleExportAction: " +
748
                           ioe.getMessage(), 30);
749
      }//catch
750

    
751
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleExportAction: " +
752
                         e.getMessage(), 30);
753
      e.printStackTrace(System.out);
754

    
755
    }//catch
756

    
757
  }//handleExportAction
758

    
759

    
760
   //read inline data section
761
 /**
762
   * In eml2 document, the xml can have inline data and data was stripped off
763
   * and store in file system. This action can be used to read inline data only
764
   * @param params the Hashtable of HTTP request parameters
765
   * @param response the HTTP response object linked to the client
766
   * @param user the username sent the request
767
   * @param groups the user's groupnames
768
   */
769
  private void handleReadInlineDataAction(Hashtable params,
770
                                          HttpServletResponse response,
771
                                          String user, String passWord,
772
                                          String[] groups)
773
  {
774
    String[] docs = new String[10];
775
    String inlineDataId = null;
776
    String docId = "";
777
    ServletOutputStream out = null;
778

    
779
    try
780
    {
781
      // read the params
782
      if (params.containsKey("inlinedataid"))
783
      {
784
        docs = (String[])params.get("inlinedataid");
785
      }//if
786
      // Get the docid
787
      inlineDataId=docs[0];
788
      // Make sure the client specify docid
789
      if (inlineDataId == null || inlineDataId.equals(""))
790
      {
791
        throw new Exception("You didn't specify requested inlinedataid");
792
      }//if
793

    
794
      // check for permission
795
      docId = MetaCatUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
796
      PermissionController controller = new PermissionController(docId);
797
      // check top level read permission
798
      if (!controller.hasPermission(user, groups,
799
                                    AccessControlInterface.READSTRING))
800
      {
801
          throw new Exception("User "+ user + " doesn't have permission "+
802
                              " to read document " + docId);
803
      }//if
804
      // if the document has subtree control, we need to check subtree control
805
      else if(controller.hasSubTreeAccessControl())
806
      {
807
        // get node id for inlinedata
808
        long nodeId=getInlineDataNodeId(inlineDataId, docId);
809
        if (!controller.hasPermissionForSubTreeNode(user, groups,
810
                                     AccessControlInterface.READSTRING, nodeId))
811
        {
812
           throw new Exception("User "+ user + " doesn't have permission "+
813
                              " to read inlinedata " + inlineDataId);
814
        }//if
815

    
816
      }//else
817

    
818
      // Get output stream
819
      out = response.getOutputStream();
820
      // read the inline data from the file
821
      String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
822
      File lineData = new File(inlinePath, inlineDataId);
823
      FileInputStream input = new FileInputStream(lineData);
824
      byte [] buffer = new byte[4*1024];
825
      int bytes = input.read(buffer);
826
      while (bytes != -1)
827
      {
828
        out.write(buffer, 0, bytes);
829
        bytes = input.read(buffer);
830
      }
831
      out.close();
832

    
833
    }//try
834
    catch (Exception e)
835
    {
836
      try
837
      {
838
        PrintWriter pw = null;
839
        // Send error message back
840
        if (out != null)
841
        {
842
            pw = new PrintWriter(out);
843
        }//if
844
        else
845
        {
846
          pw = response.getWriter();
847
        }
848
         pw.println("<?xml version=\"1.0\"?>");
849
         pw.println("<error>");
850
         pw.println(e.getMessage());
851
         pw.println("</error>");
852
         // Close printwriter
853
         pw.close();
854
         // Close output stream if out is not null
855
         if (out != null)
856
         {
857
           out.close();
858
         }
859
     }//try
860
     catch (IOException ioe)
861
     {
862
        MetaCatUtil.debugMessage("Problem with the servlet output " +
863
                           "in MetacatServlet.handleExportAction: " +
864
                           ioe.getMessage(), 30);
865
     }//catch
866

    
867
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadInlineDataAction: "
868
                                + e.getMessage(), 30);
869

    
870
    }//catch
871

    
872
  }//handleReadInlineDataAction
873

    
874
  /*
875
   * Get the nodeid from xml_nodes for the inlinedataid
876
   */
877
  private long getInlineDataNodeId(String inLineDataId, String docId)
878
                                   throws SQLException
879
  {
880
    long nodeId = 0;
881
    String INLINE = "inline";
882
    boolean hasRow;
883
    PreparedStatement pStmt = null;
884
    DBConnection conn = null;
885
    int serialNumber = -1;
886
    String sql ="SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? " +
887
                "AND nodetype='TEXT' AND parentnodeid IN " +
888
                "(SELECT nodeid FROM xml_nodes WHERE docid=? AND " +
889
                "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
890

    
891
    try
892
    {
893
      //check out DBConnection
894
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
895
      serialNumber=conn.getCheckOutSerialNumber();
896

    
897
      pStmt = conn.prepareStatement(sql);
898
      //bind value
899
      pStmt.setString(1, docId);//docid
900
      pStmt.setString(2, inLineDataId);//inlinedataid
901
      pStmt.setString(3, docId);
902
      // excute query
903
      pStmt.execute();
904
      ResultSet rs = pStmt.getResultSet();
905
      hasRow=rs.next();
906
      // get result
907
      if (hasRow)
908
      {
909
        nodeId = rs.getLong(1);
910
      }//if
911

    
912
    }//try
913
    catch (SQLException e)
914
    {
915
      throw e;
916
    }
917
    finally
918
    {
919
      try
920
      {
921
        pStmt.close();
922
      }
923
      finally
924
      {
925
        DBConnectionPool.returnDBConnection(conn, serialNumber);
926
      }
927
    }
928
    MetaCatUtil.debugMessage("The nodeid for inlinedataid " + inLineDataId +
929
                             " is: "+nodeId, 35);
930
    return nodeId;
931
  }
932

    
933

    
934

    
935
  // READ SECTION
936
  /**
937
   * Handle the "read" request of metadata/data files from Metacat
938
   * or any files from Internet;
939
   * transformed metadata XML document into HTML presentation if requested;
940
   * zip files when more than one were requested.
941
   *
942
   * @param params the Hashtable of HTTP request parameters
943
   * @param response the HTTP response object linked to the client
944
   * @param user the username sent the request
945
   * @param groups the user's groupnames
946
   */
947
  private void handleReadAction(Hashtable params, HttpServletResponse response,
948
                                String user, String passWord, String[] groups)
949
  {
950
    ServletOutputStream out = null;
951
    ZipOutputStream zout = null;
952
    PrintWriter pw = null;
953
    boolean zip = false;
954
    boolean withInlineData = true;
955

    
956
    try {
957
      String[] docs = new String[0];
958
      String docid = "";
959
      String qformat = "";
960
      String abstrpath = null;
961

    
962
      // read the params
963
      if (params.containsKey("docid")) {
964
        docs = (String[])params.get("docid");
965
      }
966
      if (params.containsKey("qformat")) {
967
        qformat = ((String[])params.get("qformat"))[0];
968
      }
969
      // the param for only metadata (eml)
970
      if (params.containsKey("inlinedata"))
971
      {
972

    
973
        String inlineData = ((String[])params.get("inlinedata"))[0];
974
        if (inlineData.equalsIgnoreCase("false"))
975
        {
976
          withInlineData = false;
977
        }
978
      }
979
      if ( (docs.length > 1) || qformat.equals("zip") ) {
980
        zip = true;
981
        out = response.getOutputStream();
982
        response.setContentType("application/zip"); //MIME type
983
        zout = new ZipOutputStream(out);
984
      }
985
      // go through the list of docs to read
986
      for (int i=0; i < docs.length; i++ ) {
987
        try {
988

    
989
          URL murl = new URL(docs[i]);
990
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
991
          // case docid="http://.../?docid=aaa"
992
          // or docid="metacat://.../?docid=bbb"
993
          if (murlQueryStr.containsKey("docid")) {
994
            // get only docid, eliminate the rest
995
            docid = (String)murlQueryStr.get("docid");
996
            if ( zip ) {
997
              addDocToZip(docid, zout, user, groups);
998
            } else {
999
              readFromMetacat(response, docid, qformat, abstrpath,
1000
                              user, groups, zip, zout, withInlineData, params);
1001
            }
1002

    
1003
          // case docid="http://.../filename"
1004
          } else {
1005
            docid = docs[i];
1006
            if ( zip ) {
1007
              addDocToZip(docid, zout, user, groups);
1008
            } else {
1009
              readFromURLConnection(response, docid);
1010
            }
1011
          }
1012

    
1013
        // case docid="ccc"
1014
        } catch (MalformedURLException mue) {
1015
          docid = docs[i];
1016
          if ( zip ) {
1017
            addDocToZip(docid, zout, user, groups);
1018
          } else {
1019
            readFromMetacat(response, docid, qformat, abstrpath,
1020
                            user, groups, zip, zout, withInlineData, params);
1021
          }
1022
        }
1023

    
1024
      } /* end for */
1025

    
1026
      if ( zip ) {
1027
        zout.finish(); //terminate the zip file
1028
        zout.close();  //close the zip stream
1029
      }
1030

    
1031

    
1032
    }
1033
    // To handle doc not found exception
1034
    catch (McdbDocNotFoundException notFoundE)
1035
    {
1036
      // the docid which didn't be found
1037
      String notFoundDocId = notFoundE.getUnfoundDocId();
1038
      String notFoundRevision = notFoundE.getUnfoundRevision();
1039
      MetaCatUtil.debugMessage("Missed id: "+ notFoundDocId, 30);
1040
      MetaCatUtil.debugMessage("Missed rev: "+ notFoundRevision, 30);
1041
      try
1042
      {
1043
        // read docid from remote server
1044
        readFromRemoteMetaCat(response, notFoundDocId, notFoundRevision,
1045
                                              user, passWord, out, zip, zout);
1046
        // Close zout outputstream
1047
        if ( zout != null)
1048
        {
1049
          zout.close();
1050
        }
1051
        // close output stream
1052
        if (out != null)
1053
        {
1054
          out.close();
1055
        }
1056

    
1057
      }//try
1058
      catch ( Exception exc)
1059
      {
1060
        MetaCatUtil.debugMessage("Erorr in MetacatServlet.hanldReadAction: "+
1061
                                      exc.getMessage(), 30);
1062
        try
1063
        {
1064
          if (out != null)
1065
          {
1066
            response.setContentType("text/xml");
1067
            // Send back error message by printWriter
1068
            pw = new PrintWriter(out);
1069
            pw.println("<?xml version=\"1.0\"?>");
1070
            pw.println("<error>");
1071
            pw.println(notFoundE.getMessage());
1072
            pw.println("</error>");
1073
            pw.close();
1074
            out.close();
1075

    
1076
          }
1077
          else
1078
          {
1079
           response.setContentType("text/xml"); //MIME type
1080
           // Send back error message if out = null
1081
           if (pw == null)
1082
           {
1083
             // If pw is null, open the respnose
1084
            pw = response.getWriter();
1085
           }
1086
           pw.println("<?xml version=\"1.0\"?>");
1087
           pw.println("<error>");
1088
           pw.println(notFoundE.getMessage());
1089
           pw.println("</error>");
1090
           pw.close();
1091
        }
1092
        // close zout
1093
        if ( zout != null )
1094
        {
1095
          zout.close();
1096
        }
1097
        }//try
1098
        catch (IOException ie)
1099
        {
1100
          MetaCatUtil.debugMessage("Problem with the servlet output " +
1101
                           "in MetacatServlet.handleReadAction: " +
1102
                           ie.getMessage(), 30);
1103
        }//cathch
1104
      }//catch
1105
    }// catch McdbDocNotFoundException
1106
    catch (Exception e)
1107
    {
1108
      try {
1109

    
1110
        if (out != null) {
1111
            response.setContentType("text/xml"); //MIME type
1112
            pw = new PrintWriter(out);
1113
            pw.println("<?xml version=\"1.0\"?>");
1114
            pw.println("<error>");
1115
            pw.println(e.getMessage());
1116
            pw.println("</error>");
1117
            pw.close();
1118
            out.close();
1119
        }
1120
        else
1121
        {
1122
           response.setContentType("text/xml"); //MIME type
1123
           // Send back error message if out = null
1124
           if ( pw == null)
1125
           {
1126
            pw = response.getWriter();
1127
           }
1128
           pw.println("<?xml version=\"1.0\"?>");
1129
           pw.println("<error>");
1130
           pw.println(e.getMessage());
1131
           pw.println("</error>");
1132
           pw.close();
1133

    
1134
        }
1135
        // Close zip output stream
1136
        if ( zout != null ) { zout.close(); }
1137

    
1138
      } catch (IOException ioe) {
1139
        MetaCatUtil.debugMessage("Problem with the servlet output " +
1140
                           "in MetacatServlet.handleReadAction: " +
1141
                           ioe.getMessage(), 30);
1142
        ioe.printStackTrace(System.out);
1143

    
1144
      }
1145

    
1146
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadAction: " +
1147
                               e.getMessage(), 30);
1148
      //e.printStackTrace(System.out);
1149
    }
1150

    
1151
  }
1152

    
1153
  // read metadata or data from Metacat
1154
  private void readFromMetacat(HttpServletResponse response, String docid,
1155
                               String qformat, String abstrpath, String user,
1156
                               String[] groups, boolean zip,
1157
                               ZipOutputStream zout, boolean withInlineData,
1158
                               Hashtable params)
1159
               throws ClassNotFoundException, IOException, SQLException,
1160
                      McdbException, Exception
1161
  {
1162

    
1163
    try {
1164

    
1165

    
1166
      DocumentImpl doc = new DocumentImpl(docid);
1167

    
1168
      //check the permission for read
1169
      if (!doc.hasReadPermission(user, groups, docid))
1170
      {
1171
        Exception e = new Exception("User " + user + " does not have permission"
1172
                       +" to read the document with the docid " + docid);
1173

    
1174
        throw e;
1175
      }
1176

    
1177
      if ( doc.getRootNodeID() == 0 ) {
1178
        // this is data file
1179
        String filepath = util.getOption("datafilepath");
1180
        if(!filepath.endsWith("/")) {
1181
          filepath += "/";
1182
        }
1183
        String filename = filepath + docid;
1184
        FileInputStream fin = null;
1185
        fin = new FileInputStream(filename);
1186

    
1187
        //MIME type
1188
        String contentType = getServletContext().getMimeType(filename);
1189
        if (contentType == null)
1190
        {
1191
          ContentTypeProvider provider = new ContentTypeProvider(docid);
1192
          contentType = provider.getContentType();
1193
          MetaCatUtil.debugMessage("Final contenttype is: "+ contentType, 30);
1194
        }
1195

    
1196
        response.setContentType(contentType);
1197
        // if we decide to use "application/octet-stream" for all data returns
1198
        // response.setContentType("application/octet-stream");
1199

    
1200
        try {
1201

    
1202
          ServletOutputStream out = response.getOutputStream();
1203
          byte[] buf = new byte[4 * 1024]; // 4K buffer
1204
          int b = fin.read(buf);
1205
          while (b != -1) {
1206
            out.write(buf, 0, b);
1207
            b = fin.read(buf);
1208
          }
1209
        } finally {
1210
          if (fin != null) fin.close();
1211
        }
1212

    
1213
      } else {
1214
        // this is metadata doc
1215
        if ( qformat.equals("xml") ) {
1216

    
1217
          // set content type first
1218
          response.setContentType("text/xml");   //MIME type
1219
          PrintWriter out = response.getWriter();
1220
          doc.toXml(out, user, groups, withInlineData);
1221
        } else {
1222
          response.setContentType("text/html");  //MIME type
1223
          PrintWriter out = response.getWriter();
1224

    
1225
          // Look up the document type
1226
          String doctype = doc.getDoctype();
1227
          // Transform the document to the new doctype
1228
          DBTransform dbt = new DBTransform();
1229
          dbt.transformXMLDocument(doc.toString(user, groups, withInlineData),
1230
                                   doctype,"-//W3C//HTML//EN",
1231
                                   qformat, out, params);
1232
        }
1233

    
1234
      }
1235
    }
1236
    catch (Exception except)
1237
    {
1238
      throw except;
1239

    
1240
    }
1241

    
1242
  }
1243

    
1244
  // read data from URLConnection
1245
  private void readFromURLConnection(HttpServletResponse response, String docid)
1246
               throws IOException, MalformedURLException
1247
  {
1248
    ServletOutputStream out = response.getOutputStream();
1249
    String contentType = getServletContext().getMimeType(docid); //MIME type
1250
    if (contentType == null) {
1251
      if (docid.endsWith(".xml")) {
1252
        contentType="text/xml";
1253
      } else if (docid.endsWith(".css")) {
1254
        contentType="text/css";
1255
      } else if (docid.endsWith(".dtd")) {
1256
        contentType="text/plain";
1257
      } else if (docid.endsWith(".xsd")) {
1258
        contentType="text/xml";
1259
      } else if (docid.endsWith("/")) {
1260
        contentType="text/html";
1261
      } else {
1262
        File f = new File(docid);
1263
        if ( f.isDirectory() ) {
1264
          contentType="text/html";
1265
        } else {
1266
          contentType="application/octet-stream";
1267
        }
1268
      }
1269
    }
1270
    response.setContentType(contentType);
1271
    // if we decide to use "application/octet-stream" for all data returns
1272
    // response.setContentType("application/octet-stream");
1273

    
1274
    // this is http url
1275
    URL url = new URL(docid);
1276
    BufferedInputStream bis = null;
1277
    try {
1278
      bis = new BufferedInputStream(url.openStream());
1279
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1280
      int b = bis.read(buf);
1281
      while (b != -1) {
1282
        out.write(buf, 0, b);
1283
        b = bis.read(buf);
1284
      }
1285
    } finally {
1286
      if (bis != null) bis.close();
1287
    }
1288

    
1289
  }
1290

    
1291
  // read file/doc and write to ZipOutputStream
1292
  private void addDocToZip(String docid, ZipOutputStream zout,
1293
                              String user, String[] groups)
1294
               throws ClassNotFoundException, IOException, SQLException,
1295
                      McdbException, Exception
1296
  {
1297
    byte[] bytestring = null;
1298
    ZipEntry zentry = null;
1299

    
1300
    try {
1301
      URL url = new URL(docid);
1302

    
1303
      // this http url; read from URLConnection; add to zip
1304
      zentry = new ZipEntry(docid);
1305
      zout.putNextEntry(zentry);
1306
      BufferedInputStream bis = null;
1307
      try {
1308
        bis = new BufferedInputStream(url.openStream());
1309
        byte[] buf = new byte[4 * 1024]; // 4K buffer
1310
        int b = bis.read(buf);
1311
        while(b != -1) {
1312
          zout.write(buf, 0, b);
1313
          b = bis.read(buf);
1314
        }
1315
      } finally {
1316
        if (bis != null) bis.close();
1317
      }
1318
      zout.closeEntry();
1319

    
1320
    } catch (MalformedURLException mue) {
1321

    
1322
      // this is metacat doc (data file or metadata doc)
1323

    
1324
      try {
1325

    
1326
        DocumentImpl doc = new DocumentImpl(docid);
1327

    
1328
        //check the permission for read
1329
        if (!doc.hasReadPermission(user, groups, docid))
1330
        {
1331
          Exception e = new Exception("User " + user + " does not have "
1332
                    +"permission to read the document with the docid " + docid);
1333

    
1334
          throw e;
1335
        }
1336

    
1337
        if ( doc.getRootNodeID() == 0 ) {
1338
          // this is data file; add file to zip
1339
          String filepath = util.getOption("datafilepath");
1340
          if(!filepath.endsWith("/")) {
1341
            filepath += "/";
1342
          }
1343
          String filename = filepath + docid;
1344
          FileInputStream fin = null;
1345
          fin = new FileInputStream(filename);
1346
          try {
1347

    
1348
            zentry = new ZipEntry(docid);
1349
            zout.putNextEntry(zentry);
1350
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1351
            int b = fin.read(buf);
1352
            while (b != -1) {
1353
              zout.write(buf, 0, b);
1354
              b = fin.read(buf);
1355
            }
1356
          } finally {
1357
            if (fin != null) fin.close();
1358
          }
1359
          zout.closeEntry();
1360

    
1361
        } else {
1362
          // this is metadata doc; add doc to zip
1363
          bytestring = doc.toString().getBytes();
1364
          zentry = new ZipEntry(docid + ".xml");
1365
          zentry.setSize(bytestring.length);
1366
          zout.putNextEntry(zentry);
1367
          zout.write(bytestring, 0, bytestring.length);
1368
          zout.closeEntry();
1369
        }
1370
      } catch (Exception except) {
1371
        throw except;
1372

    
1373
      }
1374

    
1375
    }
1376

    
1377
  }
1378

    
1379
  /**
1380
   * If metacat couldn't find a data file or document locally, it will read this
1381
   * docid from its home server. This is for the replication feature
1382
   */
1383
  private void readFromRemoteMetaCat(HttpServletResponse response, String docid,
1384
                     String rev, String user, String password,
1385
                     ServletOutputStream out, boolean zip, ZipOutputStream zout)
1386
                        throws Exception
1387
 {
1388
   // Create a object of RemoteDocument, "" is for zipEntryPath
1389
   RemoteDocument remoteDoc =
1390
                        new RemoteDocument (docid, rev,user, password, "");
1391
   String docType = remoteDoc.getDocType();
1392
   // Only read data file
1393
   if (docType.equals("BIN"))
1394
   {
1395
    // If it is zip format
1396
    if (zip)
1397
    {
1398
      remoteDoc.readDocumentFromRemoteServerByZip(zout);
1399
    }//if
1400
    else
1401
    {
1402
      if (out == null)
1403
      {
1404
        out = response.getOutputStream();
1405
      }//if
1406
      response.setContentType("application/octet-stream");
1407
      remoteDoc.readDocumentFromRemoteServer(out);
1408
    }//else (not zip)
1409
   }//if doctype=bin
1410
   else
1411
   {
1412
     throw new Exception("Docid: "+docid+"."+rev+" couldn't find");
1413
   }//else
1414
 }//readFromRemoteMetaCat
1415

    
1416
  // END OF READ SECTION
1417

    
1418

    
1419

    
1420
  // INSERT/UPDATE SECTION
1421
  /**
1422
   * Handle the database putdocument request and write an XML document
1423
   * to the database connection
1424
   */
1425
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1426
               String user, String[] groups) {
1427

    
1428
    DBConnection dbConn = null;
1429
    int serialNumber = -1;
1430

    
1431
    try {
1432
      // Get the document indicated
1433
      String[] doctext = (String[])params.get("doctext");
1434

    
1435
      String pub = null;
1436
      if (params.containsKey("public")) {
1437
        pub = ((String[])params.get("public"))[0];
1438
      }
1439

    
1440
      StringReader dtd = null;
1441
      if (params.containsKey("dtdtext")) {
1442
        String[] dtdtext = (String[])params.get("dtdtext");
1443
        try {
1444
          if ( !dtdtext[0].equals("") ) {
1445
            dtd = new StringReader(dtdtext[0]);
1446
          }
1447
        } catch (NullPointerException npe) {}
1448
      }
1449

    
1450
      StringReader xml = new StringReader(doctext[0]);
1451
      boolean validate = false;
1452
      DocumentImplWrapper documentWrapper = null;
1453
      try {
1454
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1455
        // in order to decide whether to use validation parser
1456
        validate = needDTDValidation(xml);
1457
        if (validate)
1458
        {
1459
          // set a dtd base validation parser
1460
          String rule = DocumentImpl.DTD;
1461
          documentWrapper = new DocumentImplWrapper(rule, validate);
1462
        }
1463
        else if (needSchemaValidation(xml))
1464
        {
1465
          // for eml2
1466
          if (needEml2Validation(xml))
1467
          {
1468
             // set eml2 base validation parser
1469
            String rule = DocumentImpl.EML2;
1470
            // using emlparser to check id validation
1471
            EMLParser parser = new EMLParser(doctext[0]);
1472
            documentWrapper = new DocumentImplWrapper(rule, true);
1473
          }
1474
          else
1475
          {
1476
            // set schema base validation parser
1477
            String rule = DocumentImpl.SCHEMA;
1478
            documentWrapper = new DocumentImplWrapper(rule, true);
1479
          }
1480
        }
1481
        else
1482
        {
1483
          documentWrapper = new DocumentImplWrapper("", false);
1484
        }
1485

    
1486
        String[] action = (String[])params.get("action");
1487
        String[] docid = (String[])params.get("docid");
1488
        String newdocid = null;
1489

    
1490
        String doAction = null;
1491
        if (action[0].equals("insert")) {
1492
          doAction = "INSERT";
1493
        } else if (action[0].equals("update")) {
1494
          doAction = "UPDATE";
1495
        }
1496

    
1497
        try
1498
        {
1499
          // get a connection from the pool
1500
          dbConn=DBConnectionPool.
1501
                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1502
          serialNumber=dbConn.getCheckOutSerialNumber();
1503

    
1504
           // write the document to the database
1505
          try
1506
          {
1507
            String accNumber = docid[0];
1508
            MetaCatUtil.debugMessage(""+ doAction + " " + accNumber +"...", 10);
1509
            if (accNumber.equals(""))
1510
            {
1511
              accNumber = null;
1512
            }//if
1513
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1514
                                          accNumber, user, groups);
1515

    
1516
          }//try
1517
          catch (NullPointerException npe)
1518
          {
1519
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1520
                                          null, user, groups);
1521
          }//catch
1522

    
1523
        }//try
1524
        finally
1525
        {
1526
          // Return db connection
1527
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1528
        }
1529

    
1530
        // set content type and other response header fields first
1531
        //response.setContentType("text/xml");
1532
        out.println("<?xml version=\"1.0\"?>");
1533
        out.println("<success>");
1534
        out.println("<docid>" + newdocid + "</docid>");
1535
        out.println("</success>");
1536

    
1537
      }
1538
      catch (NullPointerException npe)
1539
      {
1540
        //response.setContentType("text/xml");
1541
        out.println("<?xml version=\"1.0\"?>");
1542
        out.println("<error>");
1543
        out.println(npe.getMessage());
1544
        out.println("</error>");
1545
      }
1546
    }
1547
    catch (Exception e)
1548
    {
1549
      //response.setContentType("text/xml");
1550
      out.println("<?xml version=\"1.0\"?>");
1551
      out.println("<error>");
1552
      out.println(e.getMessage());
1553
      out.println("</error>");
1554
    }
1555
  }
1556

    
1557
  /**
1558
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1559
   * in order to decide whether to use validation parser
1560
   */
1561
  private static boolean needDTDValidation(StringReader xmlreader) throws
1562
                                                             IOException
1563
  {
1564

    
1565

    
1566
    StringBuffer cbuff = new StringBuffer();
1567
    java.util.Stack st = new java.util.Stack();
1568
    boolean validate = false;
1569
    int c;
1570
    int inx;
1571

    
1572
    // read from the stream until find the keywords
1573
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1574
      cbuff.append((char)c);
1575

    
1576
      // "<!DOCTYPE" keyword is found; put it in the stack
1577
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1578
        cbuff = new StringBuffer();
1579
        st.push("<!DOCTYPE");
1580
      }
1581
      // "PUBLIC" keyword is found; put it in the stack
1582
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1583
        cbuff = new StringBuffer();
1584
        st.push("PUBLIC");
1585
      }
1586
      // "SYSTEM" keyword is found; put it in the stack
1587
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1588
        cbuff = new StringBuffer();
1589
        st.push("SYSTEM");
1590
      }
1591
      // ">" character is found; put it in the stack
1592
      // ">" is found twice: fisrt from <?xml ...?>
1593
      // and second from <!DOCTYPE ... >
1594
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1595
        cbuff = new StringBuffer();
1596
        st.push(">");
1597
      }
1598
    }
1599

    
1600
    // close the stream
1601
    xmlreader.reset();
1602

    
1603
    // check the stack whether it contains the keywords:
1604
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1605
    if ( st.size() == 4 ) {
1606
      if ( ((String)st.pop()).equals(">") &&
1607
           ( ((String)st.peek()).equals("PUBLIC") |
1608
             ((String)st.pop()).equals("SYSTEM") ) &&
1609
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1610
        validate = true;
1611
      }
1612
    }
1613

    
1614
    MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1615
    return validate;
1616
  }
1617
  // END OF INSERT/UPDATE SECTION
1618

    
1619
  /* check if the xml string contains key words to specify schema loocation*/
1620
  private boolean needSchemaValidation(StringReader xml) throws IOException
1621
  {
1622
    boolean needSchemaValidate =false;
1623
    if (xml == null)
1624
    {
1625
      MetaCatUtil.debugMessage("Validation for schema is " +
1626
                               needSchemaValidate, 10);
1627
      return needSchemaValidate;
1628
    }
1629
    System.out.println("before get target line");
1630
    String targetLine = getSchemaLine(xml);
1631
    System.out.println("before get target line");
1632
    // to see if the second line contain some keywords
1633
    if (targetLine != null && (targetLine.indexOf(SCHEMALOCATIONKEYWORD) != -1||
1634
             targetLine.indexOf(NONAMESPACELOCATION) != -1 ))
1635
    {
1636
      // if contains schema location key word, should be validate
1637
      needSchemaValidate = true;
1638
    }
1639

    
1640
    MetaCatUtil.debugMessage("Validation for schema is " +
1641
                             needSchemaValidate, 10);
1642
    return needSchemaValidate;
1643

    
1644
  }
1645

    
1646
   /* check if the xml string contains key words to specify schema loocation*/
1647
  private boolean needEml2Validation(StringReader xml) throws IOException
1648
  {
1649
    boolean needEml2Validate =false;
1650
    String emlNameSpace =DocumentImpl.EMLNAMESPACE;
1651
    String schemaLocationContent = null;
1652
    if (xml == null)
1653
    {
1654
      MetaCatUtil.debugMessage("Validation for schema is " +
1655
                               needEml2Validate, 10);
1656
      return needEml2Validate;
1657
    }
1658
    String targetLine = getSchemaLine(xml);
1659

    
1660
    if (targetLine != null)
1661
    {
1662

    
1663
      int startIndex = targetLine.indexOf(SCHEMALOCATIONKEYWORD);
1664
      int start = 1;
1665
      int end   = 1;
1666
      String schemaLocation = null;
1667
      int count = 0;
1668
      if (startIndex != -1)
1669
      {
1670
        for ( int i=startIndex; i<targetLine.length(); i++)
1671
        {
1672
          if (targetLine.charAt(i) =='"')
1673
          {
1674
            count ++;
1675
          }
1676
          if (targetLine.charAt(i) =='"' && count == 1)
1677
          {
1678
            start = i;
1679
          }
1680
          if (targetLine.charAt(i) =='"' && count == 2)
1681
          {
1682
            end = i;
1683
            break;
1684
          }
1685
        }
1686
      }
1687
      schemaLocation = targetLine.substring(start+1, end);
1688
      MetaCatUtil.debugMessage("schemaLocation in xml is: "+schemaLocation, 30);
1689
      if ( schemaLocation.indexOf(emlNameSpace) != -1)
1690
      {
1691
        needEml2Validate = true;
1692
      }
1693
    }
1694

    
1695
    MetaCatUtil.debugMessage("Validation for eml is " +
1696
                             needEml2Validate, 10);
1697
    return needEml2Validate;
1698

    
1699
  }
1700

    
1701
  private String getSchemaLine(StringReader xml) throws IOException
1702
  {
1703
    // find the line
1704
    String secondLine = null;
1705
    int count =0;
1706
    int endIndex = 0;
1707
    int startIndex = 0;
1708
    final int TARGETNUM = 2;
1709
    StringBuffer buffer = new StringBuffer();
1710
    boolean comment =false;
1711
    char thirdPreviousCharacter = '?';
1712
    char secondPreviousCharacter ='?';
1713
    char previousCharacter = '?';
1714
    char currentCharacter = '?';
1715

    
1716
    while ( (currentCharacter = (char) xml.read()) != -1)
1717
    {
1718
      //in a comment
1719
      if (currentCharacter =='-' && previousCharacter == '-'  &&
1720
          secondPreviousCharacter =='!' && thirdPreviousCharacter == '<')
1721
      {
1722
        comment = true;
1723
      }
1724
      //out of comment
1725
      if (comment && currentCharacter == '>' && previousCharacter == '-' &&
1726
          secondPreviousCharacter =='-')
1727
      {
1728
         comment = false;
1729
      }
1730

    
1731
      //this is not comment
1732
      if (currentCharacter !='!' && previousCharacter == '<' && !comment)
1733
      {
1734
        count ++;
1735
      }
1736
      // get target line
1737
      if (count == TARGETNUM && currentCharacter !='>')
1738
      {
1739
        buffer.append(currentCharacter);
1740
      }
1741
      if (count == TARGETNUM && currentCharacter == '>')
1742
      {
1743
          break;
1744
      }
1745
      thirdPreviousCharacter = secondPreviousCharacter;
1746
      secondPreviousCharacter = previousCharacter;
1747
      previousCharacter = currentCharacter;
1748

    
1749
    }
1750
    secondLine = buffer.toString();
1751
    MetaCatUtil.debugMessage("the second line string is: "+secondLine, 25);
1752
    xml.reset();
1753
    return secondLine;
1754
  }
1755

    
1756
  // DELETE SECTION
1757
  /**
1758
   * Handle the database delete request and delete an XML document
1759
   * from the database connection
1760
   */
1761
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1762
               HttpServletResponse response, String user, String[] groups) {
1763

    
1764
    String[] docid = (String[])params.get("docid");
1765

    
1766
    // delete the document from the database
1767
    try {
1768

    
1769
                                      // NOTE -- NEED TO TEST HERE
1770
                                      // FOR EXISTENCE OF DOCID PARAM
1771
                                      // BEFORE ACCESSING ARRAY
1772
      try {
1773
        DocumentImpl.delete(docid[0], user, groups);
1774
        response.setContentType("text/xml");
1775
        out.println("<?xml version=\"1.0\"?>");
1776
        out.println("<success>");
1777
        out.println("Document deleted.");
1778
        out.println("</success>");
1779
      } catch (AccessionNumberException ane) {
1780
        response.setContentType("text/xml");
1781
        out.println("<?xml version=\"1.0\"?>");
1782
        out.println("<error>");
1783
        out.println("Error deleting document!!!");
1784
        out.println(ane.getMessage());
1785
        out.println("</error>");
1786
      }
1787
    } catch (Exception e) {
1788
      response.setContentType("text/xml");
1789
      out.println("<?xml version=\"1.0\"?>");
1790
      out.println("<error>");
1791
      out.println(e.getMessage());
1792
      out.println("</error>");
1793
    }
1794
  }
1795
  // END OF DELETE SECTION
1796

    
1797
  // VALIDATE SECTION
1798
  /**
1799
   * Handle the validation request and return the results to the requestor
1800
   */
1801
  private void handleValidateAction(PrintWriter out, Hashtable params) {
1802

    
1803
    // Get the document indicated
1804
    String valtext = null;
1805
    DBConnection dbConn = null;
1806
    int serialNumber = -1;
1807

    
1808
    try {
1809
      valtext = ((String[])params.get("valtext"))[0];
1810
    } catch (Exception nullpe) {
1811

    
1812

    
1813
      String docid = null;
1814
      try {
1815
        // Find the document id number
1816
        docid = ((String[])params.get("docid"))[0];
1817

    
1818

    
1819
        // Get the document indicated from the db
1820
        DocumentImpl xmldoc = new DocumentImpl(docid);
1821
        valtext = xmldoc.toString();
1822

    
1823
      } catch (NullPointerException npe) {
1824

    
1825
        out.println("<error>Error getting document ID: " + docid + "</error>");
1826
        //if ( conn != null ) { util.returnConnection(conn); }
1827
        return;
1828
      } catch (Exception e) {
1829

    
1830
        out.println(e.getMessage());
1831
      }
1832
    }
1833

    
1834

    
1835
    try {
1836
      // get a connection from the pool
1837
      dbConn=DBConnectionPool.
1838
                  getDBConnection("MetaCatServlet.handleValidateAction");
1839
      serialNumber=dbConn.getCheckOutSerialNumber();
1840
      DBValidate valobj = new DBValidate(saxparser,dbConn);
1841
      boolean valid = valobj.validateString(valtext);
1842

    
1843
      // set content type and other response header fields first
1844

    
1845
      out.println(valobj.returnErrors());
1846

    
1847
    } catch (NullPointerException npe2) {
1848
      // set content type and other response header fields first
1849

    
1850
      out.println("<error>Error validating document.</error>");
1851
    } catch (Exception e) {
1852

    
1853
      out.println(e.getMessage());
1854
    } finally {
1855
      // Return db connection
1856
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1857
    }
1858
  }
1859
  // END OF VALIDATE SECTION
1860

    
1861
  // OTHER ACTION HANDLERS
1862

    
1863
  /**
1864
   * Handle "getrevsionanddoctype" action
1865
   * Given a docid, return it's current revision and doctype from data base
1866
   * The output is String look like "rev;doctype"
1867
   */
1868
  private void handleGetRevisionAndDocTypeAction(PrintWriter out,
1869
                                                              Hashtable params)
1870
  {
1871
    // To store doc parameter
1872
    String [] docs = new String[10];
1873
    // Store a single doc id
1874
    String givenDocId = null;
1875
    // Get docid from parameters
1876
    if (params.containsKey("docid"))
1877
    {
1878
      docs = (String[])params.get("docid");
1879
    }
1880
    // Get first docid form string array
1881
    givenDocId = docs[0];
1882

    
1883
    try
1884
    {
1885
      // Make sure there is a docid
1886
      if (givenDocId == null || givenDocId.equals(""))
1887
      {
1888
        throw new Exception("User didn't specify docid!");
1889
      }//if
1890

    
1891
      // Create a DBUtil object
1892
      DBUtil dbutil = new DBUtil();
1893
      // Get a rev and doctype
1894
      String revAndDocType =
1895
                dbutil.getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1896
      out.println(revAndDocType);
1897

    
1898
    }//try
1899
    catch (Exception e)
1900
    {
1901
      // Handle exception
1902
      out.println("<?xml version=\"1.0\"?>");
1903
      out.println("<error>");
1904
      out.println(e.getMessage());
1905
      out.println("</error>");
1906
    }//catch
1907

    
1908
  }//handleGetRevisionAndDocTypeAction
1909

    
1910
  /**
1911
   * Handle "getaccesscontrol" action.
1912
   * Read Access Control List from db connection in XML format
1913
   */
1914
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
1915
                                       HttpServletResponse response,
1916
                                       String username, String[] groupnames) {
1917

    
1918
    DBConnection dbConn = null;
1919
    int serialNumber = -1;
1920
    String docid = ((String[])params.get("docid"))[0];
1921

    
1922
    try {
1923

    
1924
        // get connection from the pool
1925
        dbConn=DBConnectionPool.
1926
                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
1927
        serialNumber=dbConn.getCheckOutSerialNumber();
1928
        AccessControlList aclobj = new AccessControlList(dbConn);
1929
        String acltext = aclobj.getACL(docid, username, groupnames);
1930
        out.println(acltext);
1931

    
1932
    } catch (Exception e) {
1933
      out.println("<?xml version=\"1.0\"?>");
1934
      out.println("<error>");
1935
      out.println(e.getMessage());
1936
      out.println("</error>");
1937
    } finally {
1938
      // Retrun db connection to pool
1939
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1940
    }
1941

    
1942
  }
1943

    
1944
  /**
1945
   * Handle the "getprincipals" action.
1946
   * Read all principals from authentication scheme in XML format
1947
   */
1948
  private void handleGetPrincipalsAction(PrintWriter out, String user,
1949
                                         String password) {
1950

    
1951

    
1952
    try {
1953

    
1954

    
1955
        AuthSession auth = new AuthSession();
1956
        String principals = auth.getPrincipals(user, password);
1957
        out.println(principals);
1958

    
1959
    } catch (Exception e) {
1960
      out.println("<?xml version=\"1.0\"?>");
1961
      out.println("<error>");
1962
      out.println(e.getMessage());
1963
      out.println("</error>");
1964
    }
1965

    
1966
  }
1967

    
1968
  /**
1969
   * Handle "getdoctypes" action.
1970
   * Read all doctypes from db connection in XML format
1971
   */
1972
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1973
                                       HttpServletResponse response) {
1974

    
1975

    
1976
    try {
1977

    
1978

    
1979
        DBUtil dbutil = new DBUtil();
1980
        String doctypes = dbutil.readDoctypes();
1981
        out.println(doctypes);
1982

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

    
1990
  }
1991

    
1992
  /**
1993
   * Handle the "getdtdschema" action.
1994
   * Read DTD or Schema file for a given doctype from Metacat catalog system
1995
   */
1996
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1997
                                        HttpServletResponse response) {
1998

    
1999

    
2000
    String doctype = null;
2001
    String[] doctypeArr = (String[])params.get("doctype");
2002

    
2003
    // get only the first doctype specified in the list of doctypes
2004
    // it could be done for all doctypes in that list
2005
    if (doctypeArr != null) {
2006
        doctype = ((String[])params.get("doctype"))[0];
2007
    }
2008

    
2009
    try {
2010

    
2011

    
2012
        DBUtil dbutil = new DBUtil();
2013
        String dtdschema = dbutil.readDTDSchema(doctype);
2014
        out.println(dtdschema);
2015

    
2016
    } catch (Exception e) {
2017
      out.println("<?xml version=\"1.0\"?>");
2018
      out.println("<error>");
2019
      out.println(e.getMessage());
2020
      out.println("</error>");
2021
    }
2022

    
2023
  }
2024

    
2025
  /**
2026
   * Handle the "getlastdocid" action.
2027
   * Get the latest docid with rev number from db connection in XML format
2028
   */
2029
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2030
                                        HttpServletResponse response) {
2031

    
2032

    
2033
    String scope = ((String[])params.get("scope"))[0];
2034
    if (scope == null) {
2035
        scope = ((String[])params.get("username"))[0];
2036
    }
2037

    
2038
    try {
2039

    
2040

    
2041
        DBUtil dbutil = new DBUtil();
2042
        String lastDocid = dbutil.getMaxDocid(scope);
2043
        out.println("<?xml version=\"1.0\"?>");
2044
        out.println("<lastDocid>");
2045
        out.println("  <scope>" + scope + "</scope>");
2046
        out.println("  <docid>" + lastDocid + "</docid>");
2047
        out.println("</lastDocid>");
2048

    
2049
    } catch (Exception e) {
2050
      out.println("<?xml version=\"1.0\"?>");
2051
      out.println("<error>");
2052
      out.println(e.getMessage());
2053
      out.println("</error>");
2054
    }
2055

    
2056
  }
2057

    
2058
  /**
2059
   * Handle documents passed to metacat that are encoded using the
2060
   * "multipart/form-data" mime type.  This is typically used for uploading
2061
   * data files which may be binary and large.
2062
   */
2063
  private void handleMultipartForm(HttpServletRequest request,
2064
                                   HttpServletResponse response)
2065
  {
2066
    PrintWriter out = null;
2067
    String action = null;
2068

    
2069
    // Parse the multipart form, and save the parameters in a Hashtable and
2070
    // save the FileParts in a hashtable
2071

    
2072
    Hashtable params = new Hashtable();
2073
    Hashtable fileList = new Hashtable();
2074
    int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2075
                                                                   .intValue();
2076
    MetaCatUtil.debugMessage("The limit size of data file is: "+sizeLimit, 50);
2077

    
2078
    try {
2079
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
2080
      MultipartParser mp = new MultipartParser(request, sizeLimit*1024*1024);
2081
      Part part;
2082
      while ((part = mp.readNextPart()) != null) {
2083
        String name = part.getName();
2084

    
2085
        if (part.isParam()) {
2086
          // it's a parameter part
2087
          ParamPart paramPart = (ParamPart) part;
2088
          String value = paramPart.getStringValue();
2089
          params.put(name, value);
2090
          if (name.equals("action")) {
2091
            action = value;
2092
          }
2093
        } else if (part.isFile()) {
2094
          // it's a file part
2095
          FilePart filePart = (FilePart) part;
2096
          fileList.put(name, filePart);
2097

    
2098
          // Stop once the first file part is found, otherwise going onto the
2099
          // next part prevents access to the file contents.  So...for upload
2100
          // to work, the datafile must be the last part
2101
          break;
2102
        }
2103
      }
2104
    } catch (IOException ioe) {
2105
      try {
2106
        out = response.getWriter();
2107
      } catch (IOException ioe2) {
2108
        System.err.println("Fatal Error: couldn't get response output stream.");
2109
      }
2110
      out.println("<?xml version=\"1.0\"?>");
2111
      out.println("<error>");
2112
      out.println("Error: problem reading multipart data.");
2113
      out.println("</error>");
2114
    }
2115

    
2116
    // Get the session information
2117
    String username = null;
2118
    String password = null;
2119
    String[] groupnames = null;
2120
    String sess_id = null;
2121

    
2122
    // be aware of session expiration on every request
2123
    HttpSession sess = request.getSession(true);
2124
    if (sess.isNew()) {
2125
      // session expired or has not been stored b/w user requests
2126
      username = "public";
2127
      sess.setAttribute("username", username);
2128
    } else {
2129
      username = (String)sess.getAttribute("username");
2130
      password = (String)sess.getAttribute("password");
2131
      groupnames = (String[])sess.getAttribute("groupnames");
2132
      try {
2133
        sess_id = (String)sess.getId();
2134
      } catch(IllegalStateException ise) {
2135
        System.out.println("error in  handleMultipartForm: this shouldn't " +
2136
                           "happen: the session should be valid: " +
2137
                           ise.getMessage());
2138
      }
2139
    }
2140

    
2141
    // Get the out stream
2142
    try {
2143
          out = response.getWriter();
2144
        } catch (IOException ioe2) {
2145
          util.debugMessage("Fatal Error: couldn't get response "+
2146
                             "output stream.", 30);
2147
        }
2148

    
2149
    if ( action.equals("upload")) {
2150
      if (username != null &&  !username.equals("public")) {
2151
        handleUploadAction(request, out, params, fileList,
2152
                           username, groupnames);
2153
      } else {
2154

    
2155
        out.println("<?xml version=\"1.0\"?>");
2156
        out.println("<error>");
2157
        out.println("Permission denied for " + action);
2158
        out.println("</error>");
2159
      }
2160
    } else {
2161
      /*try {
2162
        out = response.getWriter();
2163
      } catch (IOException ioe2) {
2164
        System.err.println("Fatal Error: couldn't get response output stream.");
2165
      }*/
2166
      out.println("<?xml version=\"1.0\"?>");
2167
      out.println("<error>");
2168
      out.println("Error: action not registered.  Please report this error.");
2169
      out.println("</error>");
2170
    }
2171
    out.close();
2172
  }
2173

    
2174
  /**
2175
   * Handle the upload action by saving the attached file to disk and
2176
   * registering it in the Metacat db
2177
   */
2178
  private void handleUploadAction(HttpServletRequest request,
2179
                                  PrintWriter out,
2180
                                  Hashtable params, Hashtable fileList,
2181
                                  String username, String[] groupnames)
2182
  {
2183
    //PrintWriter out = null;
2184
    //Connection conn = null;
2185
    String action = null;
2186
    String docid = null;
2187

    
2188
    /*response.setContentType("text/xml");
2189
    try
2190
    {
2191
      out = response.getWriter();
2192
    }
2193
    catch (IOException ioe2)
2194
    {
2195
      System.err.println("Fatal Error: couldn't get response output stream.");
2196
    }*/
2197

    
2198
    if (params.containsKey("docid"))
2199
    {
2200
      docid = (String)params.get("docid");
2201
    }
2202

    
2203
    // Make sure we have a docid and datafile
2204
    if (docid != null && fileList.containsKey("datafile")) {
2205

    
2206
      // Get a reference to the file part of the form
2207
      FilePart filePart = (FilePart)fileList.get("datafile");
2208
      String fileName = filePart.getFileName();
2209
      MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2210

    
2211
      // Check if the right file existed in the uploaded data
2212
      if (fileName != null) {
2213

    
2214
        try
2215
        {
2216
           //MetaCatUtil.debugMessage("Upload datafile " + docid +"...", 10);
2217
           //If document get lock data file grant
2218
           if (DocumentImpl.getDataFileLockGrant(docid))
2219
           {
2220
              // register the file in the database (which generates an exception
2221
              //if the docid is not acceptable or other untoward things happen
2222
              DocumentImpl.registerDocument(fileName, "BIN", docid, username);
2223

    
2224
              // Save the data file to disk using "docid" as the name
2225
              dataDirectory.mkdirs();
2226
              File newFile = new File(dataDirectory, docid);
2227
              long size = filePart.writeTo(newFile);
2228

    
2229
              // Force replication this data file
2230
              // To data file, "insert" and update is same
2231
              // The fourth parameter is null. Because it is notification server
2232
              // and this method is in MetaCatServerlet. It is original command,
2233
              // not get force replication info from another metacat
2234
              ForceReplicationHandler frh = new ForceReplicationHandler
2235
                                                (docid, "insert", false, null);
2236

    
2237
              // set content type and other response header fields first
2238
              out.println("<?xml version=\"1.0\"?>");
2239
              out.println("<success>");
2240
              out.println("<docid>" + docid + "</docid>");
2241
              out.println("<size>" + size + "</size>");
2242
              out.println("</success>");
2243
          }//if
2244

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

    
2254
      }
2255
      else
2256
      {
2257
        // the field did not contain a file
2258
        out.println("<?xml version=\"1.0\"?>");
2259
        out.println("<error>");
2260
        out.println("The uploaded data did not contain a valid file.");
2261
        out.println("</error>");
2262
      }
2263
    }
2264
    else
2265
    {
2266
      // Error bcse docid missing or file missing
2267
      out.println("<?xml version=\"1.0\"?>");
2268
      out.println("<error>");
2269
      out.println("The uploaded data did not contain a valid docid " +
2270
                  "or valid file.");
2271
      out.println("</error>");
2272
    }
2273
  }
2274

    
2275
  /*
2276
   * A method to handle set access action
2277
   */
2278
  private void handleSetAccessAction(PrintWriter out,
2279
                                   Hashtable params,
2280
                                   String username)
2281
  {
2282
    String [] docList        = null;
2283
    String [] principalList  = null;
2284
    String [] permissionList = null;
2285
    String [] permTypeList   = null;
2286
    String [] permOrderList  = null;
2287
    String permission = null;
2288
    String permType   = null;
2289
    String permOrder  = null;
2290
    Vector errorList  = new Vector();
2291
    String error      = null;
2292
    Vector successList = new Vector();
2293
    String success    = null;
2294

    
2295

    
2296
    // Get parameters
2297
    if (params.containsKey("docid"))
2298
    {
2299
      docList = (String[])params.get("docid");
2300
    }
2301
    if (params.containsKey("principal"))
2302
    {
2303
      principalList = (String[])params.get("principal");
2304
    }
2305
    if (params.containsKey("permission"))
2306
    {
2307
      permissionList = (String[])params.get("permission");
2308

    
2309
    }
2310
    if (params.containsKey("permType"))
2311
    {
2312
      permTypeList = (String[])params.get("permType");
2313

    
2314
    }
2315
    if (params.containsKey("permOrder"))
2316
    {
2317
      permOrderList = (String[])params.get("permOrder");
2318

    
2319
    }
2320

    
2321
    // Make sure the parameter is not null
2322
    if (docList == null || principalList == null || permTypeList == null ||
2323
        permissionList == null)
2324
    {
2325
      error = "Please check your parameter list, it should look like: "+
2326
              "?action=setaccess&docid=pipeline.1.1&principal=public" +
2327
              "&permission=read&permType=allow&permOrder=allowFirst";
2328
      errorList.addElement(error);
2329
      outputResponse(successList, errorList, out);
2330
      return;
2331
    }
2332

    
2333
    // Only select first element for permission, type and order
2334
    permission = permissionList[0];
2335
    permType = permTypeList[0];
2336
    if (permOrderList != null)
2337
    {
2338
       permOrder = permOrderList[0];
2339
    }
2340

    
2341
    // Get package doctype set
2342
    Vector packageSet =MetaCatUtil.getOptionList(
2343
                                    MetaCatUtil.getOption("packagedoctypeset"));
2344
    //debug
2345
    if (packageSet != null)
2346
    {
2347
      for (int i = 0; i<packageSet.size(); i++)
2348
      {
2349
        MetaCatUtil.debugMessage("doctype in package set: " +
2350
                              (String)packageSet.elementAt(i), 34);
2351
      }
2352
    }//if
2353

    
2354
    // handle every accessionNumber
2355
    for (int i=0; i <docList.length; i++)
2356
    {
2357
      String accessionNumber = docList[i];
2358
      String owner = null;
2359
      String publicId = null;
2360
      // Get document owner and public id
2361
      try
2362
      {
2363
        owner = getFieldValueForDoc(accessionNumber, "user_owner");
2364
        publicId = getFieldValueForDoc(accessionNumber, "doctype");
2365
      }//try
2366
      catch (Exception e)
2367
      {
2368
        MetaCatUtil.debugMessage("Error in handleSetAccessAction: " +
2369
                                  e.getMessage(), 30);
2370
        error = "Error in set access control for document - " + accessionNumber+
2371
                 e.getMessage();
2372
        errorList.addElement(error);
2373
        continue;
2374
      }
2375
      //check if user is the owner. Only owner can do owner
2376
      if (username == null || owner == null || !username.equals(owner))
2377
      {
2378
        error = "User - " + username + " does not have permission to set " +
2379
                "access control for docid - " + accessionNumber;
2380
        errorList.addElement(error);
2381
        continue;
2382
      }
2383

    
2384
      // If docid publicid is BIN data file or other beta4, 6 package document
2385
      // we could not do set access control. Because we don't want inconsistent
2386
      // to its access docuemnt
2387
      if (publicId!=null && packageSet!=null && packageSet.contains(publicId))
2388
      {
2389
        error = "Could not set access control to document "+ accessionNumber +
2390
                "because it is in a pakcage and it has a access file for it";
2391
        errorList.addElement(error);
2392
        continue;
2393
      }
2394

    
2395
      // for every principle
2396
      for (int j = 0; j<principalList.length; j++)
2397
      {
2398
        String principal = principalList[j];
2399
        try
2400
        {
2401
          //insert permission
2402
          AccessControlForSingleFile accessControl = new
2403
                           AccessControlForSingleFile(accessionNumber,
2404
                                    principal, permission, permType, permOrder);
2405
          accessControl.insertPermissions();
2406
          success = "Set access control to document "+ accessionNumber +
2407
                    " successfully";
2408
          successList.addElement(success);
2409
        }
2410
        catch (Exception ee)
2411
        {
2412
          MetaCatUtil.debugMessage("Erorr in handleSetAccessAction2: " +
2413
                                   ee.getMessage(), 30);
2414
          error = "Faild to set access control for document " +
2415
                  accessionNumber + " because " + ee.getMessage();
2416
          errorList.addElement(error);
2417
          continue;
2418
        }
2419
      }//for every principle
2420
    }//for every document
2421
    outputResponse(successList, errorList, out);
2422
  }//handleSetAccessAction
2423

    
2424

    
2425
  /*
2426
   * A method try to determin a docid's public id, if couldn't find null
2427
   * will be returned.
2428
   */
2429
  private String getFieldValueForDoc(String accessionNumber, String fieldName)
2430
                                      throws Exception
2431
  {
2432
    if (accessionNumber==null || accessionNumber.equals("") ||fieldName == null
2433
        || fieldName.equals(""))
2434
    {
2435
      throw new Exception("Docid or field name was not specified");
2436
    }
2437

    
2438
    PreparedStatement pstmt = null;
2439
    ResultSet rs = null;
2440
    String fieldValue = null;
2441
    String docId = null;
2442
    DBConnection conn = null;
2443
    int serialNumber = -1;
2444

    
2445
    // get rid of revision if access number has
2446
    docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2447
    try
2448
    {
2449
      //check out DBConnection
2450
      conn=DBConnectionPool.getDBConnection("MetaCatServlet.getPublicIdForDoc");
2451
      serialNumber=conn.getCheckOutSerialNumber();
2452
      pstmt = conn.prepareStatement(
2453
            "SELECT " + fieldName + " FROM xml_documents " +
2454
            "WHERE docid = ? ");
2455

    
2456
      pstmt.setString(1, docId);
2457
      pstmt.execute();
2458
      rs = pstmt.getResultSet();
2459
      boolean hasRow = rs.next();
2460
      int perm = 0;
2461
      if ( hasRow )
2462
      {
2463
        fieldValue = rs.getString(1);
2464
      }
2465
      else
2466
      {
2467
        throw new Exception("Could not find document: "+accessionNumber);
2468
      }
2469
    }//try
2470
    catch (Exception e)
2471
    {
2472
      MetaCatUtil.debugMessage("Exception in MetacatServlet.getPublicIdForDoc: "
2473
                               + e.getMessage(), 30);
2474
      throw e;
2475
    }
2476
    finally
2477
    {
2478
      try
2479
      {
2480
        rs.close();
2481
        pstmt.close();
2482

    
2483
      }
2484
      finally
2485
      {
2486
        DBConnectionPool.returnDBConnection(conn, serialNumber);
2487
      }
2488
    }
2489
    return fieldValue;
2490
  }//getFieldValueForDoc
2491

    
2492
  /*
2493
   * A method to output setAccess action result
2494
   */
2495
  private void outputResponse(Vector successList,
2496
                              Vector errorList,
2497
                              PrintWriter out)
2498
  {
2499
    boolean error = false;
2500
    boolean success = false;
2501
    // Output prolog
2502
    out.println(PROLOG);
2503
    // output success message
2504
    if ( successList != null)
2505
    {
2506
      for (int i = 0; i<successList.size(); i++)
2507
      {
2508
        out.println(SUCCESS);
2509
        out.println((String)successList.elementAt(i));
2510
        out.println(SUCCESSCLOSE);
2511
        success = true;
2512
      }//for
2513
    }//if
2514
    // output error message
2515
    if (errorList != null)
2516
    {
2517
      for (int i = 0; i<errorList.size(); i++)
2518
      {
2519
        out.println(ERROR);
2520
        out.println((String)errorList.elementAt(i));
2521
        out.println(ERRORCLOSE);
2522
        error = true;
2523
      }//for
2524
    }//if
2525

    
2526
    // if no error and no success info, send a error that nothing happened
2527
    if( !error && !success)
2528
    {
2529
      out.println(ERROR);
2530
      out.println("Nothing happend for setaccess action");
2531
      out.println(ERRORCLOSE);
2532
    }
2533

    
2534
  }//outputResponse
2535
}
(39-39/59)