Project

General

Profile

1 51 jones
/**
2 203 jones
 *  '$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 361 berkley
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7 348 jones
 *    Release: @release@
8 154 jones
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
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 51 jones
 */
27
28
package edu.ucsb.nceas.metacat;
29
30 798 jones
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 733 bojilova
import java.io.File;
36 46 jones
import java.io.PrintWriter;
37
import java.io.IOException;
38 50 jones
import java.io.StringReader;
39 185 jones
import java.io.FileInputStream;
40 731 bojilova
import java.io.BufferedInputStream;
41 46 jones
import java.util.Enumeration;
42
import java.util.Hashtable;
43 1360 tao
import java.util.ResourceBundle;
44 648 berkley
import java.util.Random;
45 82 jones
import java.util.PropertyResourceBundle;
46 1369 tao
import java.util.Vector;
47 50 jones
import java.net.URL;
48
import java.net.MalformedURLException;
49 85 jones
import java.sql.PreparedStatement;
50
import java.sql.ResultSet;
51 50 jones
import java.sql.Connection;
52 55 jones
import java.sql.SQLException;
53 361 berkley
import java.lang.reflect.*;
54 453 berkley
import java.net.*;
55 458 berkley
import java.util.zip.*;
56 46 jones
57
import javax.servlet.ServletConfig;
58
import javax.servlet.ServletContext;
59
import javax.servlet.ServletException;
60 48 jones
import javax.servlet.ServletInputStream;
61 46 jones
import javax.servlet.http.HttpServlet;
62
import javax.servlet.http.HttpServletRequest;
63
import javax.servlet.http.HttpServletResponse;
64 210 bojilova
import javax.servlet.http.HttpSession;
65 47 jones
import javax.servlet.http.HttpUtils;
66 458 berkley
import javax.servlet.ServletOutputStream;
67 46 jones
68 1471 tao
import org.ecoinformatics.eml.EMLParser;
69 1951 jones
import edu.ucsb.nceas.utilities.Options;
70 1471 tao
71 204 jones
import org.xml.sax.SAXException;
72
73 46 jones
/**
74
 * A metadata catalog server implemented as a Java Servlet
75 154 jones
 *
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 1360 tao
 * action=squery -- structured query (see pathquery.dtd)<br>
80 943 tao
 * action= -- export a zip format for data packadge<br>
81 731 bojilova
 * action=read -- read any metadata/data file from Metacat and from Internet<br>
82 205 jones
 * 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 154 jones
 * qformat=xml -- display resultset from query in XML<br>
88
 * qformat=html -- display resultset from query in HTML<br>
89 731 bojilova
 * qformat=zip -- zip resultset from query<br>
90 154 jones
 * docid=34 -- display the document with the document ID number 34<br>
91 205 jones
 * doctext -- XML text of the document to load into the database<br>
92 598 bojilova
 * 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 183 jones
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
95 205 jones
 * valtext -- XML text to be validated<br>
96 688 bojilova
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
97
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
98 699 bojilova
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
99 688 bojilova
 * action=getdataguide -- retrieve a Data Guide<br>
100 725 bojilova
 * action=getprincipals -- retrieve a list of principals in XML<br>
101 205 jones
 * datadoc -- data document name (id)<br>
102
 * <p>
103 1360 tao
 * The particular combination of parameters that are valid for each
104 205 jones
 * particular action value is quite specific.  This documentation
105
 * will be reorganized to reflect this information.
106 46 jones
 */
107
public class MetaCatServlet extends HttpServlet {
108
109 370 berkley
  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 1360 tao
  private String datafilepath = null;
115 798 jones
  private File dataDirectory = null;
116 1360 tao
  private String servletpath = null;
117
  private String htmlpath = null;
118 380 jones
  private PropertyResourceBundle options = null;
119
  private MetaCatUtil util = null;
120 1217 tao
  private DBConnectionPool connPool = null;
121 1723 berkley
  private Hashtable sessionHash = new Hashtable();
122 1369 tao
  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 1466 tao
  public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
128
  public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
129 1610 tao
  public static final String EML2KEYWORD =":eml";
130 2089 tao
  public static final String XMLFORMAT = "xml";
131 1951 jones
  private static final String CONFIG_DIR  = "WEB-INF";
132
  private static final String CONFIG_NAME = "metacat.properties";
133 380 jones
134 50 jones
  /**
135
   * Initialize the servlet by creating appropriate database connections
136
   */
137 46 jones
  public void init( ServletConfig config ) throws ServletException {
138
    try {
139
      super.init( config );
140
      this.config = config;
141 1360 tao
      this.context = config.getServletContext();
142 184 jones
      System.out.println("MetaCatServlet Initialize");
143 82 jones
144 1951 jones
      // 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 2089 tao
          MetaCatUtil.debugMessage("Options configured: " +
151 1951 jones
            options.getOption("configured"), 20);
152
      } catch (IOException ioe) {
153
        MetaCatUtil.debugMessage("Error in loading options: "
154
           +ioe.getMessage(), 20);
155
      }
156
157 184 jones
      util = new MetaCatUtil();
158 1360 tao
159 1217 tao
      //initial DBConnection pool
160
      connPool = DBConnectionPool.getInstance();
161 184 jones
162 83 jones
      // Get the configuration file information
163 184 jones
      resultStyleURL = util.getOption("resultStyleURL");
164
      xmlcatalogfile = util.getOption("xmlcatalogfile");
165
      saxparser = util.getOption("saxparser");
166 798 jones
      datafilepath = util.getOption("datafilepath");
167
      dataDirectory = new File(datafilepath);
168 360 bojilova
      servletpath = util.getOption("servletpath");
169
      htmlpath = util.getOption("htmlpath");
170 598 bojilova
171 1217 tao
172 46 jones
    } catch ( ServletException ex ) {
173
      throw ex;
174 1217 tao
    } catch (SQLException e) {
175
      MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
176
                                          +e.getMessage(), 20);
177 46 jones
    }
178
  }
179
180 320 bojilova
  /**
181
   * Close all db connections from the pool
182
   */
183
  public void destroy() {
184 1360 tao
      // Close all db connection
185
      System.out.println("Destroying MetacatServlet");
186 1217 tao
      connPool.release();
187 320 bojilova
  }
188
189 50 jones
  /** Handle "GET" method requests from HTTP clients */
190 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
191
    throws ServletException, IOException {
192
193 48 jones
    // Process the data and send back the response
194 59 jones
    handleGetOrPost(request, response);
195 48 jones
  }
196
197 50 jones
  /** Handle "POST" method requests from HTTP clients */
198 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
199
    throws ServletException, IOException {
200
201
    // Process the data and send back the response
202 59 jones
    handleGetOrPost(request, response);
203 48 jones
  }
204
205 49 jones
  /**
206 50 jones
   * Control servlet response depending on the action parameter specified
207 49 jones
   */
208 1360 tao
  private void handleGetOrPost(HttpServletRequest request,
209
                               HttpServletResponse response)
210
                               throws ServletException, IOException
211 798 jones
  {
212 48 jones
213 309 bojilova
    if ( util == null ) {
214 1360 tao
        util = new MetaCatUtil();
215 309 bojilova
    }
216 1221 tao
    /*MetaCatUtil.debugMessage("Connection pool size: "
217 1217 tao
                                     +connPool.getSizeOfDBConnectionPool(),10);
218
    MetaCatUtil.debugMessage("Free DBConnection number: "
219 1221 tao
                                  +connPool.getFreeDBConnectionNumber(), 10);*/
220 1360 tao
    //If all DBConnection in the pool are free and DBConnection pool
221
    //size is greater than initial value, shrink the connection pool
222 1221 tao
    //size to initial value
223
    DBConnectionPool.shrinkDBConnectionPoolSize();
224 1360 tao
225 1217 tao
    //Debug message to print out the method which have a busy DBConnection
226
    connPool.printMethodNameHavingBusyDBConnection();
227 1360 tao
228 800 jones
    String ctype = request.getContentType();
229
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
230 798 jones
      handleMultipartForm(request, response);
231
    } else {
232 1360 tao
233
234 798 jones
      String name = null;
235
      String[] value = null;
236
      String[] docid = new String[3];
237
      Hashtable params = new Hashtable();
238
      Enumeration paramlist = request.getParameterNames();
239 1360 tao
240
241 798 jones
      while (paramlist.hasMoreElements()) {
242 1360 tao
243 798 jones
        name = (String)paramlist.nextElement();
244
        value = request.getParameterValues(name);
245 1360 tao
246 798 jones
        // 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 648 berkley
        }
252 798 jones
        if (name.endsWith(".x")) {
253
          name = "xpos";
254 1360 tao
        }
255
256
        params.put(name,value);
257
      }
258
259
260 1217 tao
      //handle param is emptpy
261
      if (params.isEmpty() || params == null)
262
      {
263
        return;
264
      }
265 1716 berkley
266 798 jones
      //if the user clicked on the input images, decode which image
267
      //was clicked then set the action.
268 1360 tao
      String action = ((String[])params.get("action"))[0];
269 1217 tao
      util.debugMessage("Line 230: Action is: " + action, 1);
270 1360 tao
271 798 jones
      // 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 802 bojilova
      String[] groupnames = null;
277 798 jones
      String sess_id = null;
278 1360 tao
279 798 jones
      // handle login action
280
      if (action.equals("login")) {
281 1217 tao
        PrintWriter out = response.getWriter();
282
        handleLoginAction(out, params, request, response);
283
        out.close();
284 1360 tao
285
      // handle logout action
286 798 jones
      } else if (action.equals("logout")) {
287 1217 tao
        PrintWriter out = response.getWriter();
288
        handleLogoutAction(out, params, request, response);
289
        out.close();
290 1360 tao
291 1221 tao
      // handle shrink DBConnection request
292
      } else if (action.equals("shrink")) {
293
        PrintWriter out = response.getWriter();
294
        boolean success = false;
295 1360 tao
        //If all DBConnection in the pool are free and DBConnection pool
296
        //size is greater than initial value, shrink the connection pool
297 1221 tao
        //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 1360 tao
311
      // aware of session expiration on every request
312 1723 berkley
      }
313
      else
314
      {
315 798 jones
        HttpSession sess = request.getSession(true);
316 1723 berkley
        if (sess.isNew() && !params.containsKey("sessionid")) {
317 798 jones
          // session expired or has not been stored b/w user requests
318 2045 tao
          MetaCatUtil.debugMessage("in session is new or no sessionid", 40);
319 798 jones
          username = "public";
320
          sess.setAttribute("username", username);
321 1723 berkley
        }
322
        else
323
        {
324 2089 tao
          MetaCatUtil.debugMessage("in session is not new or " +
325 2045 tao
                                    " has sessionid parameter", 40);
326 1723 berkley
          try
327
          {
328 1716 berkley
            if(params.containsKey("sessionid"))
329
            {
330 1723 berkley
              sess_id = ((String[])params.get("sessionid"))[0];
331 2045 tao
              MetaCatUtil.debugMessage("in has sessionid " + sess_id, 40);
332 1723 berkley
              if(sessionHash.containsKey(sess_id))
333
              {
334 2089 tao
                MetaCatUtil.debugMessage("find the id " + sess_id +
335 2045 tao
                                         " in hash table", 40);
336 1723 berkley
                sess = (HttpSession)sessionHash.get(sess_id);
337
              }
338 1716 berkley
            }
339
            else
340
            {
341 2045 tao
              // we already store the session in login, so we don't need here
342
              /*MetaCatUtil.debugMessage("in no sessionid parameter ", 40);
343 1716 berkley
              sess_id = (String)sess.getId();
344 2045 tao
              MetaCatUtil.debugMessage("storing the session id "+ sess_id +
345 2089 tao
                  " which has username " + sess.getAttribute("username") +
346 2045 tao
                 " into session hash in handleGetOrPost method", 35);
347
              sessionHash.put(sess_id, sess);*/
348 1716 berkley
            }
349 1723 berkley
          }
350
          catch(IllegalStateException ise)
351
          {
352 798 jones
            System.out.println("error in handleGetOrPost: this shouldn't " +
353 1360 tao
                               "happen: the session should be valid: " +
354 798 jones
                               ise.getMessage());
355
          }
356 1723 berkley
357
          username = (String)sess.getAttribute("username");
358 2045 tao
          MetaCatUtil.debugMessage("The user name from session is: "+
359
                                   username, 20);
360 1723 berkley
          password = (String)sess.getAttribute("password");
361
          groupnames = (String[])sess.getAttribute("groupnames");
362 1360 tao
        }
363 2089 tao
364 2045 tao
        //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 1906 tao
      }
371 947 tao
       // Now that we know the session is valid, we can delegate the request
372 798 jones
      // to a particular action handler
373
      if(action.equals("query")) {
374 1217 tao
        PrintWriter out = response.getWriter();
375 1716 berkley
        handleQuery(out,params,response,username,groupnames,sess_id);
376 1217 tao
        out.close();
377 798 jones
      } else if(action.equals("squery")) {
378 1217 tao
        PrintWriter out = response.getWriter();
379 798 jones
        if(params.containsKey("query")) {
380 1716 berkley
         handleSQuery(out, params,response,username,groupnames,sess_id);
381 1217 tao
         out.close();
382 798 jones
        } else {
383
          out.println("Illegal action squery without \"query\" parameter");
384 1217 tao
          out.close();
385 798 jones
        }
386 943 tao
      } else if (action.equals("export")) {
387 1360 tao
388 1292 tao
        handleExportAction(params, response, username, groupnames, password);
389 798 jones
      } else if (action.equals("read")) {
390 1292 tao
        handleReadAction(params, response, username,password, groupnames);
391 1483 tao
      } else if (action.equals("readinlinedata")) {
392 1716 berkley
        handleReadInlineDataAction(params, response, username,
393 1483 tao
                                   password, groupnames);
394 798 jones
      } else if (action.equals("insert") || action.equals("update")) {
395 458 berkley
        PrintWriter out = response.getWriter();
396 1444 tao
        if ( (username != null) &&  !username.equals("public") ) {
397 1377 tao
          handleInsertOrUpdateAction(out,params,username,groupnames);
398 1444 tao
        } else {
399 1556 tao
          out.println("Permission denied for user "+username +" " + action);
400
       }
401 1217 tao
        out.close();
402 798 jones
      } else if (action.equals("delete")) {
403
        PrintWriter out = response.getWriter();
404
        if ( (username != null) &&  !username.equals("public") ) {
405 802 bojilova
          handleDeleteAction(out, params, response, username, groupnames);
406 1360 tao
        } else {
407 798 jones
          out.println("Permission denied for " + action);
408 1217 tao
        }
409
        out.close();
410 798 jones
      } else if (action.equals("validate")) {
411
        PrintWriter out = response.getWriter();
412 1342 tao
        handleValidateAction(out, params);
413 1217 tao
        out.close();
414 1369 tao
      } else if (action.equals("setaccess")) {
415
         PrintWriter out = response.getWriter();
416
         handleSetAccessAction(out, params, username);
417
        out.close();
418 798 jones
      } else if (action.equals("getaccesscontrol")) {
419
        PrintWriter out = response.getWriter();
420 802 bojilova
        handleGetAccessControlAction(out,params,response,username,groupnames);
421 1217 tao
        out.close();
422 798 jones
      } else if (action.equals("getprincipals")) {
423
        PrintWriter out = response.getWriter();
424 1217 tao
        handleGetPrincipalsAction(out, username, password);
425
        out.close();
426 798 jones
      } else if (action.equals("getdoctypes")) {
427
        PrintWriter out = response.getWriter();
428 1217 tao
        handleGetDoctypesAction(out, params, response);
429
        out.close();
430 798 jones
      } else if (action.equals("getdtdschema")) {
431
        PrintWriter out = response.getWriter();
432 1217 tao
        handleGetDTDSchemaAction(out, params, response);
433
        out.close();
434 798 jones
      } else if (action.equals("getlastdocid")) {
435
        PrintWriter out = response.getWriter();
436 1217 tao
        handleGetMaxDocidAction(out, params, response);
437
        out.close();
438 1292 tao
      } else if (action.equals("getrevisionanddoctype")) {
439
        PrintWriter out = response.getWriter();
440
        handleGetRevisionAndDocTypeAction(out, params);
441
        out.close();
442 2079 jones
      } else if (action.equals("getversion")) {
443 2080 jones
          response.setContentType("text/xml");
444 2079 jones
          PrintWriter out = response.getWriter();
445
          out.println(Version.getVersionAsXml());
446
          out.close();
447 798 jones
      } 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 566 jones
          }
480 798 jones
          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 566 jones
        }
489 798 jones
      } 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 1217 tao
        out.close();
496 566 jones
      }
497 1360 tao
498 1217 tao
      //util.closeConnections();
499 798 jones
      // Close the stream to the client
500 1217 tao
      //out.close();
501 46 jones
    }
502
  }
503 1360 tao
504 731 bojilova
  // LOGIN & LOGOUT SECTION
505 1360 tao
  /**
506 509 bojilova
   * Handle the login request. Create a new session object.
507 503 bojilova
   * Do user authentication through the session.
508 210 bojilova
   */
509 1360 tao
  private void handleLoginAction(PrintWriter out, Hashtable params,
510 210 bojilova
               HttpServletRequest request, HttpServletResponse response) {
511 251 bojilova
512 503 bojilova
    AuthSession sess = null;
513 228 bojilova
    String un = ((String[])params.get("username"))[0];
514 2045 tao
    MetaCatUtil.debugMessage("user " + un + " try to login", 20);
515 228 bojilova
    String pw = ((String[])params.get("password"))[0];
516 297 bojilova
    String action = ((String[])params.get("action"))[0];
517 509 bojilova
    String qformat = ((String[])params.get("qformat"))[0];
518 1360 tao
519 297 bojilova
    try {
520 509 bojilova
      sess = new AuthSession();
521 297 bojilova
    } catch (Exception e) {
522 675 berkley
      System.out.println("error in MetacatServlet.handleLoginAction: " +
523
                          e.getMessage());
524 297 bojilova
      out.println(e.getMessage());
525 509 bojilova
      return;
526 297 bojilova
    }
527 509 bojilova
    boolean isValid = sess.authenticate(request, un, pw);
528 2089 tao
529 2045 tao
    //if it is authernticate is true, store the session
530
    if (isValid)
531
    {
532
      HttpSession session = sess.getSessions();
533
      String id = session.getId();
534 2089 tao
      MetaCatUtil.debugMessage("Store session id " + id +
535 2045 tao
               "which has username" + session.getAttribute("username")+
536
               " into hash in login method", 35);
537
      sessionHash.put(id, session);
538
    }
539 2089 tao
540 509 bojilova
    // format and transform the output
541 832 jones
    if (qformat.equals("xml")) {
542
      response.setContentType("text/xml");
543 1360 tao
      out.println(sess.getMessage());
544 832 jones
    } else {
545 1360 tao
546 503 bojilova
      try {
547 1360 tao
548 1217 tao
        DBTransform trans = new DBTransform();
549 509 bojilova
        response.setContentType("text/html");
550 510 bojilova
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
551 1665 tao
                                   "-//W3C//HTML//EN", qformat, out, null);
552 1360 tao
553 509 bojilova
      } catch(Exception e) {
554 1360 tao
555 1217 tao
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
556
                                +e.getMessage(), 30);
557 1360 tao
      }
558
559
    // any output is returned
560 503 bojilova
    }
561 1360 tao
  }
562 509 bojilova
563 1360 tao
  /**
564 509 bojilova
   * Handle the logout request. Close the connection.
565
   */
566 1360 tao
  private void handleLogoutAction(PrintWriter out, Hashtable params,
567 509 bojilova
               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 2045 tao
    MetaCatUtil.debugMessage("After get session in logout request", 40);
574 2089 tao
    if (sess != null)
575 2045 tao
    {
576 2089 tao
     MetaCatUtil.debugMessage("The session id " + sess.getId() +
577 2045 tao
                              " will be invalidate in logout action", 30);
578 2089 tao
     MetaCatUtil.debugMessage("The session contains user " +
579 2045 tao
                               sess.getAttribute("username") +
580
                               " will be invalidate in logout action", 30);
581 2089 tao
      sess.invalidate();
582 2045 tao
    }
583 509 bojilova
584
    // produce output
585
    StringBuffer output = new StringBuffer();
586
    output.append("<?xml version=\"1.0\"?>");
587 510 bojilova
    output.append("<logout>");
588
    output.append("User logged out");
589
    output.append("</logout>");
590 509 bojilova
591
    //format and transform the output
592 832 jones
    if (qformat.equals("xml")) {
593
      response.setContentType("text/xml");
594 1360 tao
      out.println(output.toString());
595 832 jones
    } else {
596 1360 tao
597 509 bojilova
      try {
598 1360 tao
599 1217 tao
        DBTransform trans = new DBTransform();
600 509 bojilova
        response.setContentType("text/html");
601 1360 tao
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
602 1665 tao
                                   "-//W3C//HTML//EN", qformat, out, null);
603 1360 tao
604 509 bojilova
      } catch(Exception e) {
605 1360 tao
606 1217 tao
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
607
                                  +e.getMessage(), 30);
608 1360 tao
      }
609 509 bojilova
    }
610
  }
611 731 bojilova
  // END OF LOGIN & LOGOUT SECTION
612 1360 tao
613 731 bojilova
  // SQUERY & QUERY SECTION
614 1360 tao
  /**
615 380 jones
   * 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 1360 tao
   * @param conn the database connection
622 380 jones
   */
623 1360 tao
  protected void handleSQuery(PrintWriter out, Hashtable params,
624 1716 berkley
                 HttpServletResponse response, String user, String[] groups,
625
                 String sessionid)
626 1360 tao
  {
627 1298 tao
    double startTime = System.currentTimeMillis()/1000;
628 2089 tao
    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 1360 tao
633 341 berkley
  }
634 1298 tao
635 341 berkley
   /**
636 380 jones
    * 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 370 berkley
    * in the squery.
641 380 jones
    * @param response the response object linked to the client
642 1360 tao
    */
643
  protected void handleQuery(PrintWriter out, Hashtable params,
644 1716 berkley
                 HttpServletResponse response, String user, String[] groups,
645
                 String sessionid)
646 341 berkley
  {
647 370 berkley
    //create the query and run it
648 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
649 2089 tao
    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 1360 tao
658 425 bojilova
659 2089 tao
    //handleSQuery(out, params, response,user, groups, sessionid);
660 341 berkley
  }
661 1360 tao
662 731 bojilova
  // END OF SQUERY & QUERY SECTION
663 1360 tao
664 943 tao
 //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 1360 tao
  private void handleExportAction(Hashtable params,
673 1292 tao
    HttpServletResponse response, String user, String[] groups, String passWord)
674 943 tao
  {
675 1292 tao
    // Output stream
676 943 tao
    ServletOutputStream out = null;
677 1292 tao
    // Zip output stream
678 943 tao
    ZipOutputStream zOut = null;
679
    DocumentImpl docImpls=null;
680
    DBQuery queryObj=null;
681 1360 tao
682 943 tao
    String[] docs = new String[10];
683
    String docId = "";
684
685
    try
686
    {
687
      // read the params
688 1360 tao
      if (params.containsKey("docid"))
689 1292 tao
      {
690 943 tao
        docs = (String[])params.get("docid");
691 1292 tao
      }//if
692
      // Create a DBuery to handle export
693
      queryObj = new DBQuery(saxparser);
694
      // Get the docid
695 943 tao
      docId=docs[0];
696 1292 tao
      // 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 1360 tao
        // Close printwriter
708 1292 tao
        pw.close();
709
        return;
710
      }//if
711
      // Get output stream
712 943 tao
      out = response.getOutputStream();
713
      response.setContentType("application/zip"); //MIME type
714
      zOut = new ZipOutputStream(out);
715 1292 tao
      zOut =queryObj.getZippedPackage(docId, out, user, groups, passWord);
716 943 tao
      zOut.finish(); //terminate the zip file
717
      zOut.close();  //close the zip stream
718 1360 tao
719
    }//try
720 943 tao
    catch (Exception e)
721
    {
722
      try
723
      {
724
        response.setContentType("text/xml"); //MIME type
725 1292 tao
        // Send error message back
726 943 tao
        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 1292 tao
            // Close printwriter
734 943 tao
            pw.close();
735 1292 tao
            // Close output stream
736
            out.close();
737
        }//if
738 1360 tao
        // Close zip output stream
739 943 tao
        if ( zOut != null )
740
        {
741
          zOut.close();
742 1292 tao
        }//if
743
      }//try
744 943 tao
      catch (IOException ioe)
745
      {
746 1217 tao
        MetaCatUtil.debugMessage("Problem with the servlet output " +
747 1292 tao
                           "in MetacatServlet.handleExportAction: " +
748 1217 tao
                           ioe.getMessage(), 30);
749 1292 tao
      }//catch
750 943 tao
751 1292 tao
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleExportAction: " +
752 1217 tao
                         e.getMessage(), 30);
753 1292 tao
      e.printStackTrace(System.out);
754 1360 tao
755 943 tao
    }//catch
756 1360 tao
757 943 tao
  }//handleExportAction
758 1360 tao
759 1716 berkley
760 1483 tao
   //read inline data section
761
 /**
762 1716 berkley
   * In eml2 document, the xml can have inline data and data was stripped off
763 1483 tao
   * 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 1490 tao
      if (params.containsKey("inlinedataid"))
783 1483 tao
      {
784 1490 tao
        docs = (String[])params.get("inlinedataid");
785 1483 tao
      }//if
786
      // Get the docid
787
      inlineDataId=docs[0];
788
      // Make sure the client specify docid
789
      if (inlineDataId == null || inlineDataId.equals(""))
790
      {
791 1490 tao
        throw new Exception("You didn't specify requested inlinedataid");
792 1483 tao
      }//if
793 1716 berkley
794 1483 tao
      // check for permission
795 1490 tao
      docId = MetaCatUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
796
      PermissionController controller = new PermissionController(docId);
797
      // check top level read permission
798 1716 berkley
      if (!controller.hasPermission(user, groups,
799 1490 tao
                                    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 1716 berkley
816 1490 tao
      }//else
817 1716 berkley
818 1483 tao
      // 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 1716 berkley
      {
838 1490 tao
        PrintWriter pw = null;
839 1483 tao
        // Send error message back
840
        if (out != null)
841
        {
842 1490 tao
            pw = new PrintWriter(out);
843 1483 tao
        }//if
844 1490 tao
        else
845
        {
846
          pw = response.getWriter();
847 1716 berkley
        }
848 1490 tao
         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 1483 tao
     }//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 1716 berkley
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadInlineDataAction: "
868 1483 tao
                                + e.getMessage(), 30);
869 1716 berkley
870 1483 tao
    }//catch
871
872
  }//handleReadInlineDataAction
873 1716 berkley
874 1490 tao
  /*
875
   * Get the nodeid from xml_nodes for the inlinedataid
876
   */
877 1716 berkley
  private long getInlineDataNodeId(String inLineDataId, String docId)
878 1490 tao
                                   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 1716 berkley
                "(SELECT nodeid FROM xml_nodes WHERE docid=? AND " +
889 1490 tao
                "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
890 1716 berkley
891 1490 tao
    try
892
    {
893
      //check out DBConnection
894
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
895
      serialNumber=conn.getCheckOutSerialNumber();
896 1716 berkley
897 1490 tao
      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 1716 berkley
      // excute query
903 1490 tao
      pStmt.execute();
904
      ResultSet rs = pStmt.getResultSet();
905
      hasRow=rs.next();
906
      // get result
907
      if (hasRow)
908
      {
909 1716 berkley
        nodeId = rs.getLong(1);
910 1490 tao
      }//if
911 1716 berkley
912 1490 tao
    }//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 1716 berkley
933
934
935 731 bojilova
  // READ SECTION
936 1360 tao
  /**
937 731 bojilova
   * 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 802 bojilova
   * @param groups the user's groupnames
946 437 berkley
   */
947 731 bojilova
  private void handleReadAction(Hashtable params, HttpServletResponse response,
948 1360 tao
                                String user, String passWord, String[] groups)
949 437 berkley
  {
950 731 bojilova
    ServletOutputStream out = null;
951
    ZipOutputStream zout = null;
952 1292 tao
    PrintWriter pw = null;
953
    boolean zip = false;
954 1482 tao
    boolean withInlineData = true;
955 1360 tao
956 731 bojilova
    try {
957
      String[] docs = new String[0];
958
      String docid = "";
959
      String qformat = "";
960
      String abstrpath = null;
961 1360 tao
962 731 bojilova
      // read the params
963
      if (params.containsKey("docid")) {
964
        docs = (String[])params.get("docid");
965 437 berkley
      }
966 731 bojilova
      if (params.containsKey("qformat")) {
967
        qformat = ((String[])params.get("qformat"))[0];
968 437 berkley
      }
969 1482 tao
      // the param for only metadata (eml)
970
      if (params.containsKey("inlinedata"))
971
      {
972 1716 berkley
973 1482 tao
        String inlineData = ((String[])params.get("inlinedata"))[0];
974
        if (inlineData.equalsIgnoreCase("false"))
975
        {
976
          withInlineData = false;
977
        }
978 1716 berkley
      }
979 731 bojilova
      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 1360 tao
          // case docid="http://.../?docid=aaa"
992 731 bojilova
          // 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 947 tao
              addDocToZip(docid, zout, user, groups);
998 731 bojilova
            } else {
999
              readFromMetacat(response, docid, qformat, abstrpath,
1000 1665 tao
                              user, groups, zip, zout, withInlineData, params);
1001 731 bojilova
            }
1002
1003
          // case docid="http://.../filename"
1004
          } else {
1005
            docid = docs[i];
1006
            if ( zip ) {
1007 947 tao
              addDocToZip(docid, zout, user, groups);
1008 731 bojilova
            } else {
1009
              readFromURLConnection(response, docid);
1010
            }
1011
          }
1012
1013
        // case docid="ccc"
1014
        } catch (MalformedURLException mue) {
1015
          docid = docs[i];
1016
          if ( zip ) {
1017 947 tao
            addDocToZip(docid, zout, user, groups);
1018 731 bojilova
          } else {
1019
            readFromMetacat(response, docid, qformat, abstrpath,
1020 1665 tao
                            user, groups, zip, zout, withInlineData, params);
1021 731 bojilova
          }
1022
        }
1023 1360 tao
1024 731 bojilova
      } /* end for */
1025 1360 tao
1026 731 bojilova
      if ( zip ) {
1027
        zout.finish(); //terminate the zip file
1028
        zout.close();  //close the zip stream
1029
      }
1030 1360 tao
1031
1032 1292 tao
    }
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 1360 tao
1057 1292 tao
      }//try
1058
      catch ( Exception exc)
1059
      {
1060
        MetaCatUtil.debugMessage("Erorr in MetacatServlet.hanldReadAction: "+
1061
                                      exc.getMessage(), 30);
1062
        try
1063
        {
1064 1360 tao
          if (out != null)
1065 1292 tao
          {
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 1360 tao
1076 1292 tao
          }
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 1360 tao
        if ( zout != null )
1094
        {
1095
          zout.close();
1096 1292 tao
        }
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 1360 tao
    catch (Exception e)
1107 1292 tao
    {
1108 731 bojilova
      try {
1109 1360 tao
1110 845 jones
        if (out != null) {
1111 1292 tao
            response.setContentType("text/xml"); //MIME type
1112
            pw = new PrintWriter(out);
1113 845 jones
            pw.println("<?xml version=\"1.0\"?>");
1114
            pw.println("<error>");
1115
            pw.println(e.getMessage());
1116
            pw.println("</error>");
1117
            pw.close();
1118 1292 tao
            out.close();
1119 845 jones
        }
1120 1292 tao
        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 1360 tao
1134 1292 tao
        }
1135
        // Close zip output stream
1136 731 bojilova
        if ( zout != null ) { zout.close(); }
1137 1360 tao
1138 731 bojilova
      } catch (IOException ioe) {
1139 1292 tao
        MetaCatUtil.debugMessage("Problem with the servlet output " +
1140 731 bojilova
                           "in MetacatServlet.handleReadAction: " +
1141 1292 tao
                           ioe.getMessage(), 30);
1142 731 bojilova
        ioe.printStackTrace(System.out);
1143 1360 tao
1144 731 bojilova
      }
1145
1146 1482 tao
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadAction: " +
1147
                               e.getMessage(), 30);
1148
      //e.printStackTrace(System.out);
1149 437 berkley
    }
1150 1360 tao
1151 437 berkley
  }
1152 1360 tao
1153 731 bojilova
  // read metadata or data from Metacat
1154
  private void readFromMetacat(HttpServletResponse response, String docid,
1155
                               String qformat, String abstrpath, String user,
1156 1716 berkley
                               String[] groups, boolean zip,
1157 1665 tao
                               ZipOutputStream zout, boolean withInlineData,
1158
                               Hashtable params)
1159 1360 tao
               throws ClassNotFoundException, IOException, SQLException,
1160 731 bojilova
                      McdbException, Exception
1161 453 berkley
  {
1162 1360 tao
1163 731 bojilova
    try {
1164 1360 tao
1165
1166 1217 tao
      DocumentImpl doc = new DocumentImpl(docid);
1167 1360 tao
1168 947 tao
      //check the permission for read
1169 1217 tao
      if (!doc.hasReadPermission(user, groups, docid))
1170 947 tao
      {
1171
        Exception e = new Exception("User " + user + " does not have permission"
1172
                       +" to read the document with the docid " + docid);
1173 1360 tao
1174 947 tao
        throw e;
1175
      }
1176 1360 tao
1177 731 bojilova
      if ( doc.getRootNodeID() == 0 ) {
1178
        // this is data file
1179
        String filepath = util.getOption("datafilepath");
1180
        if(!filepath.endsWith("/")) {
1181
          filepath += "/";
1182
        }
1183 1292 tao
        String filename = filepath + docid;
1184
        FileInputStream fin = null;
1185
        fin = new FileInputStream(filename);
1186 1360 tao
1187 1292 tao
        //MIME type
1188 731 bojilova
        String contentType = getServletContext().getMimeType(filename);
1189 1716 berkley
        if (contentType == null)
1190 1556 tao
        {
1191
          ContentTypeProvider provider = new ContentTypeProvider(docid);
1192
          contentType = provider.getContentType();
1193
          MetaCatUtil.debugMessage("Final contenttype is: "+ contentType, 30);
1194 453 berkley
        }
1195 1716 berkley
1196 731 bojilova
        response.setContentType(contentType);
1197 733 bojilova
        // if we decide to use "application/octet-stream" for all data returns
1198
        // response.setContentType("application/octet-stream");
1199 1360 tao
1200 731 bojilova
        try {
1201 1360 tao
1202
          ServletOutputStream out = response.getOutputStream();
1203 731 bojilova
          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 453 berkley
          }
1209 731 bojilova
        } finally {
1210
          if (fin != null) fin.close();
1211 453 berkley
        }
1212 731 bojilova
1213
      } else {
1214
        // this is metadata doc
1215 1360 tao
        if ( qformat.equals("xml") ) {
1216
1217 832 jones
          // set content type first
1218
          response.setContentType("text/xml");   //MIME type
1219
          PrintWriter out = response.getWriter();
1220 1482 tao
          doc.toXml(out, user, groups, withInlineData);
1221 832 jones
        } else {
1222 731 bojilova
          response.setContentType("text/html");  //MIME type
1223
          PrintWriter out = response.getWriter();
1224 1360 tao
1225 731 bojilova
          // Look up the document type
1226
          String doctype = doc.getDoctype();
1227
          // Transform the document to the new doctype
1228 1217 tao
          DBTransform dbt = new DBTransform();
1229 1482 tao
          dbt.transformXMLDocument(doc.toString(user, groups, withInlineData),
1230 1716 berkley
                                   doctype,"-//W3C//HTML//EN",
1231 1665 tao
                                   qformat, out, params);
1232 731 bojilova
        }
1233 1360 tao
1234 453 berkley
      }
1235 1292 tao
    }
1236 1360 tao
    catch (Exception except)
1237 1292 tao
    {
1238 1217 tao
      throw except;
1239 1360 tao
1240 731 bojilova
    }
1241 1360 tao
1242 731 bojilova
  }
1243 1360 tao
1244 731 bojilova
  // read data from URLConnection
1245
  private void readFromURLConnection(HttpServletResponse response, String docid)
1246
               throws IOException, MalformedURLException
1247 566 jones
  {
1248 1360 tao
    ServletOutputStream out = response.getOutputStream();
1249 731 bojilova
    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 733 bojilova
        contentType="text/xml";
1259 731 bojilova
      } else if (docid.endsWith("/")) {
1260 733 bojilova
        contentType="text/html";
1261 731 bojilova
      } else {
1262 733 bojilova
        File f = new File(docid);
1263
        if ( f.isDirectory() ) {
1264
          contentType="text/html";
1265
        } else {
1266
          contentType="application/octet-stream";
1267
        }
1268 731 bojilova
      }
1269
    }
1270
    response.setContentType(contentType);
1271 733 bojilova
    // if we decide to use "application/octet-stream" for all data returns
1272
    // response.setContentType("application/octet-stream");
1273 731 bojilova
1274
    // this is http url
1275
    URL url = new URL(docid);
1276
    BufferedInputStream bis = null;
1277 566 jones
    try {
1278 731 bojilova
      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 636 berkley
      }
1285 731 bojilova
    } finally {
1286
      if (bis != null) bis.close();
1287 566 jones
    }
1288 1360 tao
1289 566 jones
  }
1290 1360 tao
1291 731 bojilova
  // read file/doc and write to ZipOutputStream
1292 1360 tao
  private void addDocToZip(String docid, ZipOutputStream zout,
1293 947 tao
                              String user, String[] groups)
1294 1360 tao
               throws ClassNotFoundException, IOException, SQLException,
1295 731 bojilova
                      McdbException, Exception
1296 636 berkley
  {
1297 731 bojilova
    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 636 berkley
      }
1318 731 bojilova
      zout.closeEntry();
1319
1320
    } catch (MalformedURLException mue) {
1321 1360 tao
1322 731 bojilova
      // this is metacat doc (data file or metadata doc)
1323 1360 tao
1324 731 bojilova
      try {
1325 1360 tao
1326 1217 tao
        DocumentImpl doc = new DocumentImpl(docid);
1327 1360 tao
1328 947 tao
        //check the permission for read
1329 1217 tao
        if (!doc.hasReadPermission(user, groups, docid))
1330 947 tao
        {
1331
          Exception e = new Exception("User " + user + " does not have "
1332
                    +"permission to read the document with the docid " + docid);
1333 1360 tao
1334 947 tao
          throw e;
1335 1360 tao
        }
1336
1337 731 bojilova
        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 1292 tao
          String filename = filepath + docid;
1344 731 bojilova
          FileInputStream fin = null;
1345 1292 tao
          fin = new FileInputStream(filename);
1346 731 bojilova
          try {
1347 1360 tao
1348 1292 tao
            zentry = new ZipEntry(docid);
1349
            zout.putNextEntry(zentry);
1350 731 bojilova
            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 636 berkley
        }
1370 1217 tao
      } catch (Exception except) {
1371
        throw except;
1372 1360 tao
1373 636 berkley
      }
1374 1360 tao
1375 636 berkley
    }
1376 1360 tao
1377 636 berkley
  }
1378 2089 tao
1379 1292 tao
  /**
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 1360 tao
  private void readFromRemoteMetaCat(HttpServletResponse response, String docid,
1384
                     String rev, String user, String password,
1385 1292 tao
                     ServletOutputStream out, boolean zip, ZipOutputStream zout)
1386
                        throws Exception
1387
 {
1388
   // Create a object of RemoteDocument, "" is for zipEntryPath
1389 1360 tao
   RemoteDocument remoteDoc =
1390 1292 tao
                        new RemoteDocument (docid, rev,user, password, "");
1391 1293 tao
   String docType = remoteDoc.getDocType();
1392
   // Only read data file
1393
   if (docType.equals("BIN"))
1394 1292 tao
   {
1395 1293 tao
    // If it is zip format
1396
    if (zip)
1397
    {
1398
      remoteDoc.readDocumentFromRemoteServerByZip(zout);
1399 1360 tao
    }//if
1400 1293 tao
    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 1360 tao
   }//if doctype=bin
1410 1292 tao
   else
1411
   {
1412 1293 tao
     throw new Exception("Docid: "+docid+"."+rev+" couldn't find");
1413 1360 tao
   }//else
1414 1292 tao
 }//readFromRemoteMetaCat
1415 1360 tao
1416 731 bojilova
  // END OF READ SECTION
1417 1716 berkley
1418
1419
1420 731 bojilova
  // INSERT/UPDATE SECTION
1421 1360 tao
  /**
1422
   * Handle the database putdocument request and write an XML document
1423 55 jones
   * to the database connection
1424
   */
1425 1360 tao
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1426 1377 tao
               String user, String[] groups) {
1427 59 jones
1428 1217 tao
    DBConnection dbConn = null;
1429
    int serialNumber = -1;
1430 309 bojilova
1431 204 jones
    try {
1432
      // Get the document indicated
1433
      String[] doctext = (String[])params.get("doctext");
1434 557 bojilova
1435 680 bojilova
      String pub = null;
1436
      if (params.containsKey("public")) {
1437
        pub = ((String[])params.get("public"))[0];
1438 557 bojilova
      }
1439 680 bojilova
1440 598 bojilova
      StringReader dtd = null;
1441 680 bojilova
      if (params.containsKey("dtdtext")) {
1442 598 bojilova
        String[] dtdtext = (String[])params.get("dtdtext");
1443
        try {
1444 619 bojilova
          if ( !dtdtext[0].equals("") ) {
1445
            dtd = new StringReader(dtdtext[0]);
1446
          }
1447 598 bojilova
        } catch (NullPointerException npe) {}
1448
      }
1449 1360 tao
1450 1760 tao
      StringReader xml = new StringReader(doctext[0]);
1451 695 bojilova
      boolean validate = false;
1452 1384 tao
      DocumentImplWrapper documentWrapper = null;
1453 204 jones
      try {
1454 1360 tao
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1455 695 bojilova
        // in order to decide whether to use validation parser
1456 1760 tao
        validate = needDTDValidation(xml);
1457 1384 tao
        if (validate)
1458
        {
1459
          // set a dtd base validation parser
1460
          String rule = DocumentImpl.DTD;
1461
          documentWrapper = new DocumentImplWrapper(rule, validate);
1462
        }
1463 1760 tao
        else if (needSchemaValidation(xml))
1464 1384 tao
        {
1465 1409 tao
          // for eml2
1466 1760 tao
          if (needEml2Validation(xml))
1467 1409 tao
          {
1468
             // set eml2 base validation parser
1469
            String rule = DocumentImpl.EML2;
1470 1471 tao
            // using emlparser to check id validation
1471
            EMLParser parser = new EMLParser(doctext[0]);
1472 1409 tao
            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 1384 tao
        }
1481
        else
1482
        {
1483
          documentWrapper = new DocumentImplWrapper("", false);
1484
        }
1485 1716 berkley
1486 204 jones
        String[] action = (String[])params.get("action");
1487
        String[] docid = (String[])params.get("docid");
1488
        String newdocid = null;
1489 203 jones
1490 204 jones
        String doAction = null;
1491
        if (action[0].equals("insert")) {
1492
          doAction = "INSERT";
1493
        } else if (action[0].equals("update")) {
1494
          doAction = "UPDATE";
1495
        }
1496 1360 tao
1497
        try
1498 1217 tao
        {
1499 680 bojilova
          // get a connection from the pool
1500 1217 tao
          dbConn=DBConnectionPool.
1501
                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1502
          serialNumber=dbConn.getCheckOutSerialNumber();
1503 1360 tao
1504 1760 tao
           // write the document to the database
1505 1360 tao
          try
1506 1217 tao
          {
1507 680 bojilova
            String accNumber = docid[0];
1508 1292 tao
            MetaCatUtil.debugMessage(""+ doAction + " " + accNumber +"...", 10);
1509 1360 tao
            if (accNumber.equals(""))
1510 1217 tao
            {
1511 680 bojilova
              accNumber = null;
1512 1217 tao
            }//if
1513 1384 tao
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1514
                                          accNumber, user, groups);
1515 1360 tao
1516
          }//try
1517
          catch (NullPointerException npe)
1518 1217 tao
          {
1519 1384 tao
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1520
                                          null, user, groups);
1521 1217 tao
          }//catch
1522 1716 berkley
1523 1360 tao
        }//try
1524
        finally
1525 1217 tao
        {
1526
          // Return db connection
1527
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1528 1360 tao
        }
1529 309 bojilova
1530 204 jones
        // set content type and other response header fields first
1531 1377 tao
        //response.setContentType("text/xml");
1532 204 jones
        out.println("<?xml version=\"1.0\"?>");
1533
        out.println("<success>");
1534 1360 tao
        out.println("<docid>" + newdocid + "</docid>");
1535 204 jones
        out.println("</success>");
1536
1537 1716 berkley
      }
1538
      catch (NullPointerException npe)
1539 1466 tao
      {
1540 1377 tao
        //response.setContentType("text/xml");
1541 204 jones
        out.println("<?xml version=\"1.0\"?>");
1542
        out.println("<error>");
1543 1360 tao
        out.println(npe.getMessage());
1544 204 jones
        out.println("</error>");
1545 55 jones
      }
1546 1716 berkley
    }
1547
    catch (Exception e)
1548 1466 tao
    {
1549 1377 tao
      //response.setContentType("text/xml");
1550 204 jones
      out.println("<?xml version=\"1.0\"?>");
1551
      out.println("<error>");
1552 1360 tao
      out.println(e.getMessage());
1553 204 jones
      out.println("</error>");
1554 203 jones
    }
1555 55 jones
  }
1556 203 jones
1557 1360 tao
  /**
1558
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1559 695 bojilova
   * in order to decide whether to use validation parser
1560
   */
1561 2089 tao
  private static boolean needDTDValidation(StringReader xmlreader) throws
1562
                                                             IOException
1563 1760 tao
  {
1564 1360 tao
1565 2089 tao
1566 695 bojilova
    StringBuffer cbuff = new StringBuffer();
1567
    java.util.Stack st = new java.util.Stack();
1568
    boolean validate = false;
1569
    int c;
1570
    int inx;
1571 1360 tao
1572 695 bojilova
    // 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 1360 tao
      // ">" is found twice: fisrt from <?xml ...?>
1593 695 bojilova
      // 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 1760 tao
    xmlreader.reset();
1602 695 bojilova
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 1384 tao
    MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1615 695 bojilova
    return validate;
1616
  }
1617 731 bojilova
  // END OF INSERT/UPDATE SECTION
1618 1716 berkley
1619 1384 tao
  /* check if the xml string contains key words to specify schema loocation*/
1620 1760 tao
  private boolean needSchemaValidation(StringReader xml) throws IOException
1621 1384 tao
  {
1622
    boolean needSchemaValidate =false;
1623
    if (xml == null)
1624
    {
1625
      MetaCatUtil.debugMessage("Validation for schema is " +
1626
                               needSchemaValidate, 10);
1627
      return needSchemaValidate;
1628
    }
1629 1760 tao
    System.out.println("before get target line");
1630 1629 tao
    String targetLine = getSchemaLine(xml);
1631 1760 tao
    System.out.println("before get target line");
1632 1716 berkley
    // to see if the second line contain some keywords
1633 1629 tao
    if (targetLine != null && (targetLine.indexOf(SCHEMALOCATIONKEYWORD) != -1||
1634
             targetLine.indexOf(NONAMESPACELOCATION) != -1 ))
1635 1384 tao
    {
1636
      // if contains schema location key word, should be validate
1637
      needSchemaValidate = true;
1638
    }
1639 1716 berkley
1640
    MetaCatUtil.debugMessage("Validation for schema is " +
1641 1384 tao
                             needSchemaValidate, 10);
1642
    return needSchemaValidate;
1643 1716 berkley
1644 1384 tao
  }
1645 1716 berkley
1646 1409 tao
   /* check if the xml string contains key words to specify schema loocation*/
1647 1760 tao
  private boolean needEml2Validation(StringReader xml) throws IOException
1648 1409 tao
  {
1649
    boolean needEml2Validate =false;
1650 1760 tao
    String emlNameSpace =DocumentImpl.EMLNAMESPACE;
1651
    String schemaLocationContent = null;
1652 1409 tao
    if (xml == null)
1653
    {
1654
      MetaCatUtil.debugMessage("Validation for schema is " +
1655
                               needEml2Validate, 10);
1656
      return needEml2Validate;
1657
    }
1658 1629 tao
    String targetLine = getSchemaLine(xml);
1659 1716 berkley
1660 1760 tao
    if (targetLine != null)
1661 1409 tao
    {
1662 2089 tao
1663 1760 tao
      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 1409 tao
    }
1694 1716 berkley
1695
    MetaCatUtil.debugMessage("Validation for eml is " +
1696 1409 tao
                             needEml2Validate, 10);
1697
    return needEml2Validate;
1698 1716 berkley
1699 1409 tao
  }
1700 1716 berkley
1701 1760 tao
  private String getSchemaLine(StringReader xml) throws IOException
1702 1629 tao
  {
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 1760 tao
    StringBuffer buffer = new StringBuffer();
1710
    boolean comment =false;
1711
    char thirdPreviousCharacter = '?';
1712
    char secondPreviousCharacter ='?';
1713
    char previousCharacter = '?';
1714
    char currentCharacter = '?';
1715 2089 tao
1716 1760 tao
    while ( (currentCharacter = (char) xml.read()) != -1)
1717 1629 tao
    {
1718 1760 tao
      //in a comment
1719 2089 tao
      if (currentCharacter =='-' && previousCharacter == '-'  &&
1720 1760 tao
          secondPreviousCharacter =='!' && thirdPreviousCharacter == '<')
1721 1629 tao
      {
1722 1760 tao
        comment = true;
1723
      }
1724
      //out of comment
1725 2089 tao
      if (comment && currentCharacter == '>' && previousCharacter == '-' &&
1726 1760 tao
          secondPreviousCharacter =='-')
1727
      {
1728
         comment = false;
1729
      }
1730 2089 tao
1731 1760 tao
      //this is not comment
1732
      if (currentCharacter !='!' && previousCharacter == '<' && !comment)
1733
      {
1734 1629 tao
        count ++;
1735 1760 tao
      }
1736
      // get target line
1737
      if (count == TARGETNUM && currentCharacter !='>')
1738 1629 tao
      {
1739 1760 tao
        buffer.append(currentCharacter);
1740
      }
1741
      if (count == TARGETNUM && currentCharacter == '>')
1742
      {
1743
          break;
1744
      }
1745
      thirdPreviousCharacter = secondPreviousCharacter;
1746
      secondPreviousCharacter = previousCharacter;
1747
      previousCharacter = currentCharacter;
1748 2089 tao
1749 1760 tao
    }
1750
    secondLine = buffer.toString();
1751 1629 tao
    MetaCatUtil.debugMessage("the second line string is: "+secondLine, 25);
1752 1760 tao
    xml.reset();
1753 1629 tao
    return secondLine;
1754
  }
1755 1716 berkley
1756 731 bojilova
  // DELETE SECTION
1757 1360 tao
  /**
1758
   * Handle the database delete request and delete an XML document
1759 203 jones
   * from the database connection
1760
   */
1761 1360 tao
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1762 802 bojilova
               HttpServletResponse response, String user, String[] groups) {
1763 203 jones
1764
    String[] docid = (String[])params.get("docid");
1765 1360 tao
1766 203 jones
    // delete the document from the database
1767
    try {
1768 1360 tao
1769 203 jones
                                      // NOTE -- NEED TO TEST HERE
1770 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
1771 203 jones
                                      // BEFORE ACCESSING ARRAY
1772 1360 tao
      try {
1773 1217 tao
        DocumentImpl.delete(docid[0], user, groups);
1774 204 jones
        response.setContentType("text/xml");
1775
        out.println("<?xml version=\"1.0\"?>");
1776
        out.println("<success>");
1777 1360 tao
        out.println("Document deleted.");
1778 204 jones
        out.println("</success>");
1779 203 jones
      } catch (AccessionNumberException ane) {
1780 204 jones
        response.setContentType("text/xml");
1781
        out.println("<?xml version=\"1.0\"?>");
1782
        out.println("<error>");
1783
        out.println("Error deleting document!!!");
1784 1360 tao
        out.println(ane.getMessage());
1785 204 jones
        out.println("</error>");
1786 203 jones
      }
1787 204 jones
    } catch (Exception e) {
1788
      response.setContentType("text/xml");
1789
      out.println("<?xml version=\"1.0\"?>");
1790
      out.println("<error>");
1791 1360 tao
      out.println(e.getMessage());
1792 204 jones
      out.println("</error>");
1793 1360 tao
    }
1794 203 jones
  }
1795 731 bojilova
  // END OF DELETE SECTION
1796 1360 tao
1797 731 bojilova
  // VALIDATE SECTION
1798 1360 tao
  /**
1799 380 jones
   * Handle the validation request and return the results to the requestor
1800 68 higgins
   */
1801 1342 tao
  private void handleValidateAction(PrintWriter out, Hashtable params) {
1802 68 higgins
1803 103 jones
    // Get the document indicated
1804
    String valtext = null;
1805 1217 tao
    DBConnection dbConn = null;
1806
    int serialNumber = -1;
1807 1360 tao
1808 103 jones
    try {
1809
      valtext = ((String[])params.get("valtext"))[0];
1810
    } catch (Exception nullpe) {
1811 68 higgins
1812 1360 tao
1813 162 bojilova
      String docid = null;
1814 103 jones
      try {
1815
        // Find the document id number
1816 1360 tao
        docid = ((String[])params.get("docid"))[0];
1817 309 bojilova
1818 1360 tao
1819 309 bojilova
        // Get the document indicated from the db
1820 1217 tao
        DocumentImpl xmldoc = new DocumentImpl(docid);
1821 393 jones
        valtext = xmldoc.toString();
1822 185 jones
1823 103 jones
      } catch (NullPointerException npe) {
1824 1360 tao
1825 253 jones
        out.println("<error>Error getting document ID: " + docid + "</error>");
1826 1217 tao
        //if ( conn != null ) { util.returnConnection(conn); }
1827 380 jones
        return;
1828 309 bojilova
      } catch (Exception e) {
1829 1360 tao
1830
        out.println(e.getMessage());
1831
      }
1832 103 jones
    }
1833 68 higgins
1834 1360 tao
1835 103 jones
    try {
1836 309 bojilova
      // get a connection from the pool
1837 1217 tao
      dbConn=DBConnectionPool.
1838
                  getDBConnection("MetaCatServlet.handleValidateAction");
1839
      serialNumber=dbConn.getCheckOutSerialNumber();
1840
      DBValidate valobj = new DBValidate(saxparser,dbConn);
1841 185 jones
      boolean valid = valobj.validateString(valtext);
1842 68 higgins
1843
      // set content type and other response header fields first
1844 1360 tao
1845 253 jones
      out.println(valobj.returnErrors());
1846
1847 103 jones
    } catch (NullPointerException npe2) {
1848
      // set content type and other response header fields first
1849 1360 tao
1850
      out.println("<error>Error validating document.</error>");
1851 309 bojilova
    } catch (Exception e) {
1852 1360 tao
1853
      out.println(e.getMessage());
1854 309 bojilova
    } finally {
1855 1217 tao
      // Return db connection
1856
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1857 1360 tao
    }
1858 103 jones
  }
1859 731 bojilova
  // END OF VALIDATE SECTION
1860 1360 tao
1861 731 bojilova
  // OTHER ACTION HANDLERS
1862 1360 tao
1863 1292 tao
  /**
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 1360 tao
  private void handleGetRevisionAndDocTypeAction(PrintWriter out,
1869 1292 tao
                                                              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 1360 tao
    if (params.containsKey("docid"))
1877 1292 tao
    {
1878
      docs = (String[])params.get("docid");
1879
    }
1880
    // Get first docid form string array
1881
    givenDocId = docs[0];
1882 1360 tao
1883
    try
1884 1292 tao
    {
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 1360 tao
1891 1292 tao
      // Create a DBUtil object
1892
      DBUtil dbutil = new DBUtil();
1893
      // Get a rev and doctype
1894 1360 tao
      String revAndDocType =
1895 1292 tao
                dbutil.getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1896
      out.println(revAndDocType);
1897
1898 1360 tao
    }//try
1899
    catch (Exception e)
1900 1292 tao
    {
1901
      // Handle exception
1902
      out.println("<?xml version=\"1.0\"?>");
1903
      out.println("<error>");
1904
      out.println(e.getMessage());
1905
      out.println("</error>");
1906 1360 tao
    }//catch
1907
1908 1292 tao
  }//handleGetRevisionAndDocTypeAction
1909 1360 tao
1910
  /**
1911 688 bojilova
   * Handle "getaccesscontrol" action.
1912
   * Read Access Control List from db connection in XML format
1913
   */
1914 1360 tao
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
1915
                                       HttpServletResponse response,
1916 802 bojilova
                                       String username, String[] groupnames) {
1917 688 bojilova
1918 1217 tao
    DBConnection dbConn = null;
1919
    int serialNumber = -1;
1920 688 bojilova
    String docid = ((String[])params.get("docid"))[0];
1921 1360 tao
1922 688 bojilova
    try {
1923
1924
        // get connection from the pool
1925 1217 tao
        dbConn=DBConnectionPool.
1926
                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
1927
        serialNumber=dbConn.getCheckOutSerialNumber();
1928
        AccessControlList aclobj = new AccessControlList(dbConn);
1929 802 bojilova
        String acltext = aclobj.getACL(docid, username, groupnames);
1930 688 bojilova
        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 1217 tao
      // Retrun db connection to pool
1939
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1940 1360 tao
    }
1941
1942 688 bojilova
  }
1943
1944 1360 tao
  /**
1945 731 bojilova
   * 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 1360 tao
1952 731 bojilova
    try {
1953
1954 1360 tao
1955 731 bojilova
        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 1360 tao
    }
1965
1966 731 bojilova
  }
1967
1968 1360 tao
  /**
1969 688 bojilova
   * Handle "getdoctypes" action.
1970 302 bojilova
   * Read all doctypes from db connection in XML format
1971
   */
1972 1360 tao
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1973 302 bojilova
                                       HttpServletResponse response) {
1974
1975 1360 tao
1976 302 bojilova
    try {
1977
1978 1360 tao
1979 1217 tao
        DBUtil dbutil = new DBUtil();
1980 302 bojilova
        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 1360 tao
    }
1989
1990 302 bojilova
  }
1991
1992 1360 tao
  /**
1993 699 bojilova
   * 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 1360 tao
2000 699 bojilova
    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 1360 tao
        doctype = ((String[])params.get("doctype"))[0];
2007 699 bojilova
    }
2008
2009
    try {
2010
2011 1360 tao
2012 1217 tao
        DBUtil dbutil = new DBUtil();
2013 699 bojilova
        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 1360 tao
    }
2022
2023 699 bojilova
  }
2024
2025 1360 tao
  /**
2026 793 bojilova
   * Handle the "getlastdocid" action.
2027
   * Get the latest docid with rev number from db connection in XML format
2028
   */
2029 1360 tao
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2030 793 bojilova
                                        HttpServletResponse response) {
2031
2032 1217 tao
2033 847 jones
    String scope = ((String[])params.get("scope"))[0];
2034
    if (scope == null) {
2035
        scope = ((String[])params.get("username"))[0];
2036
    }
2037 793 bojilova
2038
    try {
2039
2040 1360 tao
2041 1217 tao
        DBUtil dbutil = new DBUtil();
2042 847 jones
        String lastDocid = dbutil.getMaxDocid(scope);
2043 793 bojilova
        out.println("<?xml version=\"1.0\"?>");
2044
        out.println("<lastDocid>");
2045 847 jones
        out.println("  <scope>" + scope + "</scope>");
2046 793 bojilova
        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 1217 tao
    }
2055 1360 tao
2056 793 bojilova
  }
2057
2058 1360 tao
  /**
2059
   * Handle documents passed to metacat that are encoded using the
2060 798 jones
   * "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 1360 tao
                                   HttpServletResponse response)
2065 798 jones
  {
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 1617 tao
    int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2075
                                                                   .intValue();
2076
    MetaCatUtil.debugMessage("The limit size of data file is: "+sizeLimit, 50);
2077 798 jones
2078
    try {
2079
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
2080 1716 berkley
      MultipartParser mp = new MultipartParser(request, sizeLimit*1024*1024);
2081 798 jones
      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 802 bojilova
    String[] groupnames = null;
2120 798 jones
    String sess_id = null;
2121
2122 1360 tao
    // be aware of session expiration on every request
2123 798 jones
    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 802 bojilova
      groupnames = (String[])sess.getAttribute("groupnames");
2132 798 jones
      try {
2133
        sess_id = (String)sess.getId();
2134
      } catch(IllegalStateException ise) {
2135
        System.out.println("error in  handleMultipartForm: this shouldn't " +
2136 1360 tao
                           "happen: the session should be valid: " +
2137 798 jones
                           ise.getMessage());
2138
      }
2139 1360 tao
    }
2140
2141 1292 tao
    // Get the out stream
2142
    try {
2143 798 jones
          out = response.getWriter();
2144
        } catch (IOException ioe2) {
2145 943 tao
          util.debugMessage("Fatal Error: couldn't get response "+
2146 1490 tao
                             "output stream.", 30);
2147 798 jones
        }
2148 1360 tao
2149 1292 tao
    if ( action.equals("upload")) {
2150
      if (username != null &&  !username.equals("public")) {
2151 1360 tao
        handleUploadAction(request, out, params, fileList,
2152 1292 tao
                           username, groupnames);
2153
      } else {
2154 1360 tao
2155 798 jones
        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 1292 tao
      /*try {
2162 798 jones
        out = response.getWriter();
2163
      } catch (IOException ioe2) {
2164
        System.err.println("Fatal Error: couldn't get response output stream.");
2165 1292 tao
      }*/
2166 798 jones
      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 1217 tao
    out.close();
2172 798 jones
  }
2173
2174 1360 tao
  /**
2175
   * Handle the upload action by saving the attached file to disk and
2176 798 jones
   * registering it in the Metacat db
2177
   */
2178
  private void handleUploadAction(HttpServletRequest request,
2179 1360 tao
                                  PrintWriter out,
2180
                                  Hashtable params, Hashtable fileList,
2181 802 bojilova
                                  String username, String[] groupnames)
2182 798 jones
  {
2183 1292 tao
    //PrintWriter out = null;
2184 1217 tao
    //Connection conn = null;
2185 798 jones
    String action = null;
2186
    String docid = null;
2187 1360 tao
2188 1292 tao
    /*response.setContentType("text/xml");
2189 1360 tao
    try
2190 1041 tao
    {
2191 798 jones
      out = response.getWriter();
2192 1360 tao
    }
2193
    catch (IOException ioe2)
2194 1041 tao
    {
2195 798 jones
      System.err.println("Fatal Error: couldn't get response output stream.");
2196 1292 tao
    }*/
2197 798 jones
2198 1360 tao
    if (params.containsKey("docid"))
2199 1041 tao
    {
2200 798 jones
      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 1056 tao
      MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2210 798 jones
2211
      // Check if the right file existed in the uploaded data
2212
      if (fileName != null) {
2213 1360 tao
2214
        try
2215 1028 tao
        {
2216 1292 tao
           //MetaCatUtil.debugMessage("Upload datafile " + docid +"...", 10);
2217 1028 tao
           //If document get lock data file grant
2218 1070 tao
           if (DocumentImpl.getDataFileLockGrant(docid))
2219
           {
2220 1064 tao
              // register the file in the database (which generates an exception
2221 1028 tao
              //if the docid is not acceptable or other untoward things happen
2222
              DocumentImpl.registerDocument(fileName, "BIN", docid, username);
2223 1360 tao
2224 1028 tao
              // 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 1360 tao
2229 1292 tao
              // Force replication this data file
2230
              // To data file, "insert" and update is same
2231 1360 tao
              // The fourth parameter is null. Because it is notification server
2232
              // and this method is in MetaCatServerlet. It is original command,
2233 1292 tao
              // not get force replication info from another metacat
2234
              ForceReplicationHandler frh = new ForceReplicationHandler
2235
                                                (docid, "insert", false, null);
2236 1360 tao
2237 1028 tao
              // set content type and other response header fields first
2238
              out.println("<?xml version=\"1.0\"?>");
2239
              out.println("<success>");
2240 1360 tao
              out.println("<docid>" + docid + "</docid>");
2241
              out.println("<size>" + size + "</size>");
2242 1028 tao
              out.println("</success>");
2243 1070 tao
          }//if
2244 1360 tao
2245 1028 tao
        } //try
2246 1360 tao
        catch (Exception e)
2247 1041 tao
        {
2248 798 jones
          out.println("<?xml version=\"1.0\"?>");
2249
          out.println("<error>");
2250 1360 tao
          out.println(e.getMessage());
2251 798 jones
          out.println("</error>");
2252
        }
2253 1360 tao
2254 1041 tao
      }
2255 1360 tao
      else
2256 1041 tao
      {
2257 798 jones
        // the field did not contain a file
2258
        out.println("<?xml version=\"1.0\"?>");
2259
        out.println("<error>");
2260 1360 tao
        out.println("The uploaded data did not contain a valid file.");
2261 798 jones
        out.println("</error>");
2262
      }
2263 1360 tao
    }
2264
    else
2265 1041 tao
    {
2266 798 jones
      // 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 1360 tao
                  "or valid file.");
2271 798 jones
      out.println("</error>");
2272
    }
2273
  }
2274 1716 berkley
2275 1369 tao
  /*
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 1716 berkley
2295
2296 1369 tao
    // Get parameters
2297 1716 berkley
    if (params.containsKey("docid"))
2298 1369 tao
    {
2299
      docList = (String[])params.get("docid");
2300
    }
2301
    if (params.containsKey("principal"))
2302
    {
2303 1716 berkley
      principalList = (String[])params.get("principal");
2304 1369 tao
    }
2305
    if (params.containsKey("permission"))
2306
    {
2307
      permissionList = (String[])params.get("permission");
2308 1716 berkley
2309 1369 tao
    }
2310
    if (params.containsKey("permType"))
2311
    {
2312
      permTypeList = (String[])params.get("permType");
2313 1716 berkley
2314 1369 tao
    }
2315
    if (params.containsKey("permOrder"))
2316
    {
2317
      permOrderList = (String[])params.get("permOrder");
2318 1716 berkley
2319 1369 tao
    }
2320 1716 berkley
2321 1369 tao
    // 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 1716 berkley
2333 1369 tao
    // 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 1716 berkley
2341 1369 tao
    // 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 1716 berkley
        MetaCatUtil.debugMessage("doctype in package set: " +
2350 1369 tao
                              (String)packageSet.elementAt(i), 34);
2351
      }
2352
    }//if
2353 1716 berkley
2354 1369 tao
    // 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 1716 berkley
      //check if user is the owner. Only owner can do owner
2376 1369 tao
      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 1716 berkley
2384 1369 tao
      // 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 1716 berkley
2395 1369 tao
      // 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 1716 berkley
          AccessControlForSingleFile accessControl = new
2403 1369 tao
                           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 1716 berkley
          error = "Faild to set access control for document " +
2415 1369 tao
                  accessionNumber + " because " + ee.getMessage();
2416
          errorList.addElement(error);
2417
          continue;
2418
        }
2419
      }//for every principle
2420 1716 berkley
    }//for every document
2421 1369 tao
    outputResponse(successList, errorList, out);
2422
  }//handleSetAccessAction
2423 1716 berkley
2424
2425 1369 tao
  /*
2426
   * A method try to determin a docid's public id, if couldn't find null
2427
   * will be returned.
2428
   */
2429 1716 berkley
  private String getFieldValueForDoc(String accessionNumber, String fieldName)
2430 1369 tao
                                      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 1716 berkley
2438 1369 tao
    PreparedStatement pstmt = null;
2439
    ResultSet rs = null;
2440
    String fieldValue = null;
2441
    String docId = null;
2442
    DBConnection conn = null;
2443
    int serialNumber = -1;
2444 1716 berkley
2445 1369 tao
    // 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 1716 berkley
2456 1369 tao
      pstmt.setString(1, docId);
2457
      pstmt.execute();
2458
      rs = pstmt.getResultSet();
2459
      boolean hasRow = rs.next();
2460
      int perm = 0;
2461 1716 berkley
      if ( hasRow )
2462 1369 tao
      {
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 1716 berkley
2483 1369 tao
      }
2484
      finally
2485
      {
2486
        DBConnectionPool.returnDBConnection(conn, serialNumber);
2487
      }
2488
    }
2489
    return fieldValue;
2490
  }//getFieldValueForDoc
2491 1716 berkley
2492 1369 tao
  /*
2493
   * A method to output setAccess action result
2494
   */
2495 1716 berkley
  private void outputResponse(Vector successList,
2496 1369 tao
                              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 1716 berkley
2526 1369 tao
    // 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 1716 berkley
2534 1369 tao
  }//outputResponse
2535 46 jones
}