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 1951 jones
  private static final String CONFIG_DIR  = "WEB-INF";
131
  private static final String CONFIG_NAME = "metacat.properties";
132 380 jones
133 50 jones
  /**
134
   * Initialize the servlet by creating appropriate database connections
135
   */
136 46 jones
  public void init( ServletConfig config ) throws ServletException {
137
    try {
138
      super.init( config );
139
      this.config = config;
140 1360 tao
      this.context = config.getServletContext();
141 184 jones
      System.out.println("MetaCatServlet Initialize");
142 82 jones
143 1951 jones
      // Initialize the properties file for our options
144
      String dirPath = context.getRealPath(CONFIG_DIR);
145
      File propertyFile = new File(dirPath,CONFIG_NAME);
146
      Options options = null;
147
      try {
148
          options = Options.initialize(propertyFile);
149
          MetaCatUtil.debugMessage("Options configured: " +
150
            options.getOption("configured"), 20);
151
      } catch (IOException ioe) {
152
        MetaCatUtil.debugMessage("Error in loading options: "
153
           +ioe.getMessage(), 20);
154
      }
155
156 184 jones
      util = new MetaCatUtil();
157 1360 tao
158 1217 tao
      //initial DBConnection pool
159
      connPool = DBConnectionPool.getInstance();
160 184 jones
161 83 jones
      // Get the configuration file information
162 184 jones
      resultStyleURL = util.getOption("resultStyleURL");
163
      xmlcatalogfile = util.getOption("xmlcatalogfile");
164
      saxparser = util.getOption("saxparser");
165 798 jones
      datafilepath = util.getOption("datafilepath");
166
      dataDirectory = new File(datafilepath);
167 360 bojilova
      servletpath = util.getOption("servletpath");
168
      htmlpath = util.getOption("htmlpath");
169 598 bojilova
170 1217 tao
171 46 jones
    } catch ( ServletException ex ) {
172
      throw ex;
173 1217 tao
    } catch (SQLException e) {
174
      MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
175
                                          +e.getMessage(), 20);
176 46 jones
    }
177
  }
178
179 320 bojilova
  /**
180
   * Close all db connections from the pool
181
   */
182
  public void destroy() {
183 1360 tao
      // Close all db connection
184
      System.out.println("Destroying MetacatServlet");
185 1217 tao
      connPool.release();
186 320 bojilova
  }
187
188 50 jones
  /** Handle "GET" method requests from HTTP clients */
189 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
190
    throws ServletException, IOException {
191
192 48 jones
    // Process the data and send back the response
193 59 jones
    handleGetOrPost(request, response);
194 48 jones
  }
195
196 50 jones
  /** Handle "POST" method requests from HTTP clients */
197 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
198
    throws ServletException, IOException {
199
200
    // Process the data and send back the response
201 59 jones
    handleGetOrPost(request, response);
202 48 jones
  }
203
204 49 jones
  /**
205 50 jones
   * Control servlet response depending on the action parameter specified
206 49 jones
   */
207 1360 tao
  private void handleGetOrPost(HttpServletRequest request,
208
                               HttpServletResponse response)
209
                               throws ServletException, IOException
210 798 jones
  {
211 48 jones
212 309 bojilova
    if ( util == null ) {
213 1360 tao
        util = new MetaCatUtil();
214 309 bojilova
    }
215 1221 tao
    /*MetaCatUtil.debugMessage("Connection pool size: "
216 1217 tao
                                     +connPool.getSizeOfDBConnectionPool(),10);
217
    MetaCatUtil.debugMessage("Free DBConnection number: "
218 1221 tao
                                  +connPool.getFreeDBConnectionNumber(), 10);*/
219 1360 tao
    //If all DBConnection in the pool are free and DBConnection pool
220
    //size is greater than initial value, shrink the connection pool
221 1221 tao
    //size to initial value
222
    DBConnectionPool.shrinkDBConnectionPoolSize();
223 1360 tao
224 1217 tao
    //Debug message to print out the method which have a busy DBConnection
225
    connPool.printMethodNameHavingBusyDBConnection();
226 1360 tao
227 800 jones
    String ctype = request.getContentType();
228
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
229 798 jones
      handleMultipartForm(request, response);
230
    } else {
231 1360 tao
232
233 798 jones
      String name = null;
234
      String[] value = null;
235
      String[] docid = new String[3];
236
      Hashtable params = new Hashtable();
237
      Enumeration paramlist = request.getParameterNames();
238 1360 tao
239
240 798 jones
      while (paramlist.hasMoreElements()) {
241 1360 tao
242 798 jones
        name = (String)paramlist.nextElement();
243
        value = request.getParameterValues(name);
244 1360 tao
245 798 jones
        // Decode the docid and mouse click information
246
        if (name.endsWith(".y")) {
247
          docid[0] = name.substring(0,name.length()-2);
248
          params.put("docid", docid);
249
          name = "ypos";
250 648 berkley
        }
251 798 jones
        if (name.endsWith(".x")) {
252
          name = "xpos";
253 1360 tao
        }
254
255
        params.put(name,value);
256
      }
257
258
259 1217 tao
      //handle param is emptpy
260
      if (params.isEmpty() || params == null)
261
      {
262
        return;
263
      }
264 1716 berkley
265 798 jones
      //if the user clicked on the input images, decode which image
266
      //was clicked then set the action.
267 1360 tao
      String action = ((String[])params.get("action"))[0];
268 1217 tao
      util.debugMessage("Line 230: Action is: " + action, 1);
269 1360 tao
270 798 jones
      // This block handles session management for the servlet
271
      // by looking up the current session information for all actions
272
      // other than "login" and "logout"
273
      String username = null;
274
      String password = null;
275 802 bojilova
      String[] groupnames = null;
276 798 jones
      String sess_id = null;
277 1360 tao
278 798 jones
      // handle login action
279
      if (action.equals("login")) {
280 1217 tao
        PrintWriter out = response.getWriter();
281
        handleLoginAction(out, params, request, response);
282
        out.close();
283 1360 tao
284
      // handle logout action
285 798 jones
      } else if (action.equals("logout")) {
286 1217 tao
        PrintWriter out = response.getWriter();
287
        handleLogoutAction(out, params, request, response);
288
        out.close();
289 1360 tao
290 1221 tao
      // handle shrink DBConnection request
291
      } else if (action.equals("shrink")) {
292
        PrintWriter out = response.getWriter();
293
        boolean success = false;
294 1360 tao
        //If all DBConnection in the pool are free and DBConnection pool
295
        //size is greater than initial value, shrink the connection pool
296 1221 tao
        //size to initial value
297
        success = DBConnectionPool.shrinkConnectionPoolSize();
298
        if (success)
299
        {
300
          //if successfully shrink the pool size to initial value
301
          out.println("DBConnection Pool shrink successfully");
302
        }//if
303
        else
304
        {
305
          out.println("DBConnection pool couldn't shrink successfully");
306
        }
307
       //close out put
308
        out.close();
309 1360 tao
310
      // aware of session expiration on every request
311 1723 berkley
      }
312
      else
313
      {
314 798 jones
        HttpSession sess = request.getSession(true);
315 1723 berkley
        if (sess.isNew() && !params.containsKey("sessionid")) {
316 798 jones
          // session expired or has not been stored b/w user requests
317 2045 tao
          MetaCatUtil.debugMessage("in session is new or no sessionid", 40);
318 798 jones
          username = "public";
319
          sess.setAttribute("username", username);
320 1723 berkley
        }
321
        else
322
        {
323 2045 tao
          MetaCatUtil.debugMessage("in session is not new or " +
324
                                    " has sessionid parameter", 40);
325 1723 berkley
          try
326
          {
327 1716 berkley
            if(params.containsKey("sessionid"))
328
            {
329 1723 berkley
              sess_id = ((String[])params.get("sessionid"))[0];
330 2045 tao
              MetaCatUtil.debugMessage("in has sessionid " + sess_id, 40);
331 1723 berkley
              if(sessionHash.containsKey(sess_id))
332
              {
333 2045 tao
                MetaCatUtil.debugMessage("find the id " + sess_id +
334
                                         " in hash table", 40);
335 1723 berkley
                sess = (HttpSession)sessionHash.get(sess_id);
336
              }
337 1716 berkley
            }
338
            else
339
            {
340 2045 tao
              // we already store the session in login, so we don't need here
341
              /*MetaCatUtil.debugMessage("in no sessionid parameter ", 40);
342 1716 berkley
              sess_id = (String)sess.getId();
343 2045 tao
              MetaCatUtil.debugMessage("storing the session id "+ sess_id +
344
                  " which has username " + sess.getAttribute("username") +
345
                 " into session hash in handleGetOrPost method", 35);
346
              sessionHash.put(sess_id, sess);*/
347 1716 berkley
            }
348 1723 berkley
          }
349
          catch(IllegalStateException ise)
350
          {
351 798 jones
            System.out.println("error in handleGetOrPost: this shouldn't " +
352 1360 tao
                               "happen: the session should be valid: " +
353 798 jones
                               ise.getMessage());
354
          }
355 1723 berkley
356
          username = (String)sess.getAttribute("username");
357 2045 tao
          MetaCatUtil.debugMessage("The user name from session is: "+
358
                                   username, 20);
359 1723 berkley
          password = (String)sess.getAttribute("password");
360
          groupnames = (String[])sess.getAttribute("groupnames");
361 1360 tao
        }
362 1906 tao
363 2045 tao
        //make user user username should be public
364
        if (username == null || (username.trim().equals("")))
365
        {
366
          username = "public";
367
        }
368
        MetaCatUtil.debugMessage("The user is : "+ username, 5);
369 1906 tao
      }
370 947 tao
       // Now that we know the session is valid, we can delegate the request
371 798 jones
      // to a particular action handler
372
      if(action.equals("query")) {
373 1217 tao
        PrintWriter out = response.getWriter();
374 1716 berkley
        handleQuery(out,params,response,username,groupnames,sess_id);
375 1217 tao
        out.close();
376 798 jones
      } else if(action.equals("squery")) {
377 1217 tao
        PrintWriter out = response.getWriter();
378 798 jones
        if(params.containsKey("query")) {
379 1716 berkley
         handleSQuery(out, params,response,username,groupnames,sess_id);
380 1217 tao
         out.close();
381 798 jones
        } else {
382
          out.println("Illegal action squery without \"query\" parameter");
383 1217 tao
          out.close();
384 798 jones
        }
385 943 tao
      } else if (action.equals("export")) {
386 1360 tao
387 1292 tao
        handleExportAction(params, response, username, groupnames, password);
388 798 jones
      } else if (action.equals("read")) {
389 1292 tao
        handleReadAction(params, response, username,password, groupnames);
390 1483 tao
      } else if (action.equals("readinlinedata")) {
391 1716 berkley
        handleReadInlineDataAction(params, response, username,
392 1483 tao
                                   password, groupnames);
393 798 jones
      } else if (action.equals("insert") || action.equals("update")) {
394 458 berkley
        PrintWriter out = response.getWriter();
395 1444 tao
        if ( (username != null) &&  !username.equals("public") ) {
396 1377 tao
          handleInsertOrUpdateAction(out,params,username,groupnames);
397 1444 tao
        } else {
398 1556 tao
          out.println("Permission denied for user "+username +" " + action);
399
       }
400 1217 tao
        out.close();
401 798 jones
      } else if (action.equals("delete")) {
402
        PrintWriter out = response.getWriter();
403
        if ( (username != null) &&  !username.equals("public") ) {
404 802 bojilova
          handleDeleteAction(out, params, response, username, groupnames);
405 1360 tao
        } else {
406 798 jones
          out.println("Permission denied for " + action);
407 1217 tao
        }
408
        out.close();
409 798 jones
      } else if (action.equals("validate")) {
410
        PrintWriter out = response.getWriter();
411 1342 tao
        handleValidateAction(out, params);
412 1217 tao
        out.close();
413 1369 tao
      } else if (action.equals("setaccess")) {
414
         PrintWriter out = response.getWriter();
415
         handleSetAccessAction(out, params, username);
416
        out.close();
417 798 jones
      } else if (action.equals("getaccesscontrol")) {
418
        PrintWriter out = response.getWriter();
419 802 bojilova
        handleGetAccessControlAction(out,params,response,username,groupnames);
420 1217 tao
        out.close();
421 798 jones
      } else if (action.equals("getprincipals")) {
422
        PrintWriter out = response.getWriter();
423 1217 tao
        handleGetPrincipalsAction(out, username, password);
424
        out.close();
425 798 jones
      } else if (action.equals("getdoctypes")) {
426
        PrintWriter out = response.getWriter();
427 1217 tao
        handleGetDoctypesAction(out, params, response);
428
        out.close();
429 798 jones
      } else if (action.equals("getdtdschema")) {
430
        PrintWriter out = response.getWriter();
431 1217 tao
        handleGetDTDSchemaAction(out, params, response);
432
        out.close();
433 798 jones
      } else if (action.equals("getlastdocid")) {
434
        PrintWriter out = response.getWriter();
435 1217 tao
        handleGetMaxDocidAction(out, params, response);
436
        out.close();
437 1292 tao
      } else if (action.equals("getrevisionanddoctype")) {
438
        PrintWriter out = response.getWriter();
439
        handleGetRevisionAndDocTypeAction(out, params);
440
        out.close();
441 2079 jones
      } else if (action.equals("getversion")) {
442 2080 jones
          response.setContentType("text/xml");
443 2079 jones
          PrintWriter out = response.getWriter();
444
          out.println(Version.getVersionAsXml());
445
          out.close();
446 798 jones
      } else if (action.equals("login") || action.equals("logout")) {
447
      } else if (action.equals("protocoltest")) {
448
        String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
449
        try {
450
          testURL = ((String[])params.get("url"))[0];
451
        } catch (Throwable t) {
452
        }
453
        String phandler = System.getProperty("java.protocol.handler.pkgs");
454
        response.setContentType("text/html");
455
        PrintWriter out = response.getWriter();
456
        out.println("<body bgcolor=\"white\">");
457
        out.println("<p>Handler property: <code>" + phandler + "</code></p>");
458
        out.println("<p>Starting test for:<br>");
459
        out.println("    " + testURL + "</p>");
460
        try {
461
          URL u = new URL(testURL);
462
          out.println("<pre>");
463
          out.println("Protocol: " + u.getProtocol());
464
          out.println("    Host: " + u.getHost());
465
          out.println("    Port: " + u.getPort());
466
          out.println("    Path: " + u.getPath());
467
          out.println("     Ref: " + u.getRef());
468
          String pquery = u.getQuery();
469
          out.println("   Query: " + pquery);
470
          out.println("  Params: ");
471
          if (pquery != null) {
472
            Hashtable qparams = util.parseQuery(u.getQuery());
473
            for (Enumeration en = qparams.keys(); en.hasMoreElements(); ) {
474
              String pname = (String)en.nextElement();
475
              String pvalue = (String)qparams.get(pname);
476
              out.println("    " + pname + ": " + pvalue);
477
            }
478 566 jones
          }
479 798 jones
          out.println("</pre>");
480
          out.println("</body>");
481
          out.close();
482
        } catch (MalformedURLException mue) {
483
          System.out.println("bad url from MetacatServlet.handleGetOrPost");
484
          out.println(mue.getMessage());
485
          mue.printStackTrace(out);
486
          out.close();
487 566 jones
        }
488 798 jones
      } else {
489
        PrintWriter out = response.getWriter();
490
        out.println("<?xml version=\"1.0\"?>");
491
        out.println("<error>");
492
        out.println("Error: action not registered.  Please report this error.");
493
        out.println("</error>");
494 1217 tao
        out.close();
495 566 jones
      }
496 1360 tao
497 1217 tao
      //util.closeConnections();
498 798 jones
      // Close the stream to the client
499 1217 tao
      //out.close();
500 46 jones
    }
501
  }
502 1360 tao
503 731 bojilova
  // LOGIN & LOGOUT SECTION
504 1360 tao
  /**
505 509 bojilova
   * Handle the login request. Create a new session object.
506 503 bojilova
   * Do user authentication through the session.
507 210 bojilova
   */
508 1360 tao
  private void handleLoginAction(PrintWriter out, Hashtable params,
509 210 bojilova
               HttpServletRequest request, HttpServletResponse response) {
510 251 bojilova
511 503 bojilova
    AuthSession sess = null;
512 228 bojilova
    String un = ((String[])params.get("username"))[0];
513 2045 tao
    MetaCatUtil.debugMessage("user " + un + " try to login", 20);
514 228 bojilova
    String pw = ((String[])params.get("password"))[0];
515 297 bojilova
    String action = ((String[])params.get("action"))[0];
516 509 bojilova
    String qformat = ((String[])params.get("qformat"))[0];
517 1360 tao
518 297 bojilova
    try {
519 509 bojilova
      sess = new AuthSession();
520 297 bojilova
    } catch (Exception e) {
521 675 berkley
      System.out.println("error in MetacatServlet.handleLoginAction: " +
522
                          e.getMessage());
523 297 bojilova
      out.println(e.getMessage());
524 509 bojilova
      return;
525 297 bojilova
    }
526 509 bojilova
    boolean isValid = sess.authenticate(request, un, pw);
527 2045 tao
528
    //if it is authernticate is true, store the session
529
    if (isValid)
530
    {
531
      HttpSession session = sess.getSessions();
532
      String id = session.getId();
533
      MetaCatUtil.debugMessage("Store session id " + id +
534
               "which has username" + session.getAttribute("username")+
535
               " into hash in login method", 35);
536
      sessionHash.put(id, session);
537
    }
538
539 509 bojilova
    // format and transform the output
540 832 jones
    if (qformat.equals("xml")) {
541
      response.setContentType("text/xml");
542 1360 tao
      out.println(sess.getMessage());
543 832 jones
    } else {
544 1360 tao
545 503 bojilova
      try {
546 1360 tao
547 1217 tao
        DBTransform trans = new DBTransform();
548 509 bojilova
        response.setContentType("text/html");
549 510 bojilova
        trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
550 1665 tao
                                   "-//W3C//HTML//EN", qformat, out, null);
551 1360 tao
552 509 bojilova
      } catch(Exception e) {
553 1360 tao
554 1217 tao
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
555
                                +e.getMessage(), 30);
556 1360 tao
      }
557
558
    // any output is returned
559 503 bojilova
    }
560 1360 tao
  }
561 509 bojilova
562 1360 tao
  /**
563 509 bojilova
   * Handle the logout request. Close the connection.
564
   */
565 1360 tao
  private void handleLogoutAction(PrintWriter out, Hashtable params,
566 509 bojilova
               HttpServletRequest request, HttpServletResponse response) {
567
568
    String qformat = ((String[])params.get("qformat"))[0];
569
570
    // close the connection
571
    HttpSession sess = request.getSession(false);
572 2045 tao
    MetaCatUtil.debugMessage("After get session in logout request", 40);
573
    if (sess != null)
574
    {
575
     MetaCatUtil.debugMessage("The session id " + sess.getId() +
576
                              " will be invalidate in logout action", 30);
577
     MetaCatUtil.debugMessage("The session contains user " +
578
                               sess.getAttribute("username") +
579
                               " will be invalidate in logout action", 30);
580
      sess.invalidate();
581
    }
582 509 bojilova
583
    // produce output
584
    StringBuffer output = new StringBuffer();
585
    output.append("<?xml version=\"1.0\"?>");
586 510 bojilova
    output.append("<logout>");
587
    output.append("User logged out");
588
    output.append("</logout>");
589 509 bojilova
590
    //format and transform the output
591 832 jones
    if (qformat.equals("xml")) {
592
      response.setContentType("text/xml");
593 1360 tao
      out.println(output.toString());
594 832 jones
    } else {
595 1360 tao
596 509 bojilova
      try {
597 1360 tao
598 1217 tao
        DBTransform trans = new DBTransform();
599 509 bojilova
        response.setContentType("text/html");
600 1360 tao
        trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN",
601 1665 tao
                                   "-//W3C//HTML//EN", qformat, out, null);
602 1360 tao
603 509 bojilova
      } catch(Exception e) {
604 1360 tao
605 1217 tao
        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
606
                                  +e.getMessage(), 30);
607 1360 tao
      }
608 509 bojilova
    }
609
  }
610 731 bojilova
  // END OF LOGIN & LOGOUT SECTION
611 1360 tao
612 731 bojilova
  // SQUERY & QUERY SECTION
613 1360 tao
  /**
614 380 jones
   * Retreive the squery xml, execute it and display it
615
   *
616
   * @param out the output stream to the client
617
   * @param params the Hashtable of parameters that should be included
618
   * in the squery.
619
   * @param response the response object linked to the client
620 1360 tao
   * @param conn the database connection
621 380 jones
   */
622 1360 tao
  protected void handleSQuery(PrintWriter out, Hashtable params,
623 1716 berkley
                 HttpServletResponse response, String user, String[] groups,
624
                 String sessionid)
625 1360 tao
  {
626 380 jones
    String xmlquery = ((String[])params.get("query"))[0];
627
    String qformat = ((String[])params.get("qformat"))[0];
628 465 berkley
    String resultdoc = null;
629 1298 tao
    MetaCatUtil.debugMessage("xmlquery: "+xmlquery, 30);
630
    double startTime = System.currentTimeMillis()/1000;
631 802 bojilova
    Hashtable doclist = runQuery(xmlquery, user, groups);
632 1360 tao
    double docListTime = System.currentTimeMillis()/1000;
633 1298 tao
    MetaCatUtil.debugMessage("Time for getting doc list: "
634
                                            +(docListTime-startTime), 30);
635 1360 tao
636 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(xmlquery));
637 1298 tao
    double toStringTime = System.currentTimeMillis()/1000;
638
    MetaCatUtil.debugMessage("Time to create xml string: "
639
                              +(toStringTime-docListTime), 30);
640
    //format and transform the results
641 1360 tao
    double outPutTime = 0;
642 832 jones
    if(qformat.equals("xml")) {
643 380 jones
      response.setContentType("text/xml");
644
      out.println(resultdoc);
645 1298 tao
      outPutTime = System.currentTimeMillis()/1000;
646
      MetaCatUtil.debugMessage("Output time: "+(outPutTime-toStringTime), 30);
647 380 jones
    } else {
648 1956 jones
      transformResultset(resultdoc, response, out, qformat, sessionid, params);
649 1298 tao
      outPutTime = System.currentTimeMillis()/1000;
650
      MetaCatUtil.debugMessage("Output time: "+(outPutTime-toStringTime), 30);
651 380 jones
    }
652 341 berkley
  }
653 1298 tao
654 341 berkley
   /**
655 380 jones
    * Create the xml query, execute it and display the results.
656
    *
657
    * @param out the output stream to the client
658
    * @param params the Hashtable of parameters that should be included
659 370 berkley
    * in the squery.
660 380 jones
    * @param response the response object linked to the client
661 1360 tao
    */
662
  protected void handleQuery(PrintWriter out, Hashtable params,
663 1716 berkley
                 HttpServletResponse response, String user, String[] groups,
664
                 String sessionid)
665 341 berkley
  {
666 370 berkley
    //create the query and run it
667 373 berkley
    String xmlquery = DBQuery.createSQuery(params);
668 802 bojilova
    Hashtable doclist = runQuery(xmlquery, user, groups);
669 465 berkley
    String qformat = ((String[])params.get("qformat"))[0];
670
    String resultdoc = null;
671 1360 tao
672 465 berkley
    resultdoc = createResultDocument(doclist, transformQuery(params));
673 425 bojilova
674 1360 tao
    //format and transform the results
675 832 jones
    if(qformat.equals("xml")) {
676 370 berkley
      response.setContentType("text/xml");
677
      out.println(resultdoc);
678 1360 tao
    } else {
679 1956 jones
      transformResultset(resultdoc, response, out, qformat, sessionid, params);
680 370 berkley
    }
681 341 berkley
  }
682 1360 tao
683 341 berkley
  /**
684 384 berkley
   * Removes the <?xml version="x"?> tag from the beginning of xmlquery
685
   * so it can properly be placed in the <query> tag of the resultset.
686
   * This method is overwritable so that other applications can customize
687
   * the structure of what is in the <query> tag.
688 1360 tao
   *
689 384 berkley
   * @param xmlquery is the query to remove the <?xml version="x"?> tag from.
690
   */
691
  protected String transformQuery(Hashtable params)
692
  {
693 1360 tao
    //DBQuery.createSQuery is a re-calling of a previously called
694 384 berkley
    //function but it is necessary
695
    //so that overriding methods have access to the params hashtable
696
    String xmlquery = DBQuery.createSQuery(params);
697
    //the <?xml version="1.0"?> tag is the first 22 characters of the
698
    xmlquery = xmlquery.trim();
699
    int index = xmlquery.indexOf("?>");
700 1816 tao
    if ( index != -1 )
701
    {
702
      //have <?xml version="1.0"?>
703
      return xmlquery.substring(index + 2, xmlquery.length());
704
    }
705
    else
706
    {
707
      // don't have <?xml version="1.0"?>
708
      return xmlquery;
709
    }
710 384 berkley
  }
711 1360 tao
712 384 berkley
  /**
713 443 berkley
   * removes the <?xml version="1.0"?> tag from the beginning.  This takes a
714
   * string as a param instead of a hashtable.
715 1360 tao
   *
716 443 berkley
   * @param xmlquery a string representing a query.
717
   */
718
  protected String transformQuery(String xmlquery)
719
  {
720
    xmlquery = xmlquery.trim();
721
    int index = xmlquery.indexOf("?>");
722 1816 tao
    if (index != -1)
723
    {
724
      return xmlquery.substring(index + 2, xmlquery.length());
725
    }
726
    else
727
    {
728
      return xmlquery;
729
    }
730 443 berkley
  }
731 1360 tao
732 443 berkley
  /**
733 380 jones
   * Run the query and return a hashtable of results.
734
   *
735
   * @param xmlquery the query to run
736
   */
737 802 bojilova
  private Hashtable runQuery(String xmlquery, String user, String[] groups)
738 341 berkley
  {
739
    Hashtable doclist=null;
740 1360 tao
741 341 berkley
    try
742
    {
743 1360 tao
744 1217 tao
      DBQuery queryobj = new DBQuery(saxparser);
745 802 bojilova
      doclist = queryobj.findDocuments(new StringReader(xmlquery),user,groups);
746 1360 tao
747 441 bojilova
      return doclist;
748 1360 tao
    }
749
    catch (Exception e)
750 341 berkley
    {
751 1360 tao
752
      MetaCatUtil.debugMessage("Error in MetacatServlet.runQuery: "
753 1217 tao
                                                      + e.getMessage(), 30);
754 341 berkley
      doclist = null;
755
      return doclist;
756 1360 tao
    }
757 341 berkley
  }
758 1360 tao
759 380 jones
  /**
760 370 berkley
   * Transorms an xml resultset document to html and sends it to the browser
761 380 jones
   *
762 370 berkley
   * @param resultdoc the string representation of the document that needs
763
   * to be transformed.
764
   * @param response the HttpServletResponse object bound to the client.
765
   * @param out the output stream to the client
766 832 jones
   * @param qformat the name of the style-set to use for transformations
767 1360 tao
   */
768
  protected void transformResultset(String resultdoc,
769 380 jones
                                    HttpServletResponse response,
770 1716 berkley
                                    PrintWriter out, String qformat,
771 1956 jones
                                    String sessionid, Hashtable params)
772 370 berkley
  {
773 1360 tao
774 380 jones
    try {
775 1360 tao
776 1217 tao
      DBTransform trans = new DBTransform();
777 370 berkley
      response.setContentType("text/html");
778 1360 tao
      trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN",
779 1956 jones
                                 "-//W3C//HTML//EN", qformat, out, params,
780 1717 berkley
                                 sessionid);
781 1360 tao
782 382 berkley
    }
783
    catch(Exception e)
784
    {
785 1360 tao
786 1217 tao
      MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
787
                                +e.getMessage(), 30);
788 1360 tao
    }
789 370 berkley
  }
790 1360 tao
791 355 berkley
  /**
792
   * Transforms a hashtable of documents to an xml or html result.
793 380 jones
   *
794 355 berkley
   * @param doclist- the hashtable to transform
795 744 jones
   * @param xmlquery- the query that returned the doclist result
796 355 berkley
   */
797 375 berkley
  protected String createResultDocument(Hashtable doclist, String xmlquery)
798 341 berkley
  {
799
    // Create a buffer to hold the xml result
800
    StringBuffer resultset = new StringBuffer();
801 1360 tao
802
    // Print the resulting root nodes
803 341 berkley
    String docid = null;
804
    String document = null;
805
    resultset.append("<?xml version=\"1.0\"?>\n");
806
    resultset.append("<resultset>\n");
807 478 berkley
808 1360 tao
    resultset.append("  <query>" + xmlquery + "</query>");
809
810 478 berkley
    if(doclist != null)
811 341 berkley
    {
812 1360 tao
      Enumeration doclistkeys = doclist.keys();
813
      while (doclistkeys.hasMoreElements())
814 478 berkley
      {
815
        docid = (String)doclistkeys.nextElement();
816
        document = (String)doclist.get(docid);
817
        resultset.append("  <document>" + document + "</document>");
818
      }
819
    }
820
821 341 berkley
    resultset.append("</resultset>");
822 370 berkley
    return resultset.toString();
823 341 berkley
  }
824 731 bojilova
  // END OF SQUERY & QUERY SECTION
825 1360 tao
826 943 tao
 //Exoport section
827
 /**
828
   * Handle the "export" request of data package from Metacat in zip format
829
   * @param params the Hashtable of HTTP request parameters
830
   * @param response the HTTP response object linked to the client
831
   * @param user the username sent the request
832
   * @param groups the user's groupnames
833
   */
834 1360 tao
  private void handleExportAction(Hashtable params,
835 1292 tao
    HttpServletResponse response, String user, String[] groups, String passWord)
836 943 tao
  {
837 1292 tao
    // Output stream
838 943 tao
    ServletOutputStream out = null;
839 1292 tao
    // Zip output stream
840 943 tao
    ZipOutputStream zOut = null;
841
    DocumentImpl docImpls=null;
842
    DBQuery queryObj=null;
843 1360 tao
844 943 tao
    String[] docs = new String[10];
845
    String docId = "";
846
847
    try
848
    {
849
      // read the params
850 1360 tao
      if (params.containsKey("docid"))
851 1292 tao
      {
852 943 tao
        docs = (String[])params.get("docid");
853 1292 tao
      }//if
854
      // Create a DBuery to handle export
855
      queryObj = new DBQuery(saxparser);
856
      // Get the docid
857 943 tao
      docId=docs[0];
858 1292 tao
      // Make sure the client specify docid
859
      if (docId == null || docId.equals(""))
860
      {
861
        response.setContentType("text/xml"); //MIME type
862
        // Get a printwriter
863
        PrintWriter pw = response.getWriter();
864
        // Send back message
865
        pw.println("<?xml version=\"1.0\"?>");
866
        pw.println("<error>");
867
        pw.println("You didn't specify requested docid");
868
        pw.println("</error>");
869 1360 tao
        // Close printwriter
870 1292 tao
        pw.close();
871
        return;
872
      }//if
873
      // Get output stream
874 943 tao
      out = response.getOutputStream();
875
      response.setContentType("application/zip"); //MIME type
876
      zOut = new ZipOutputStream(out);
877 1292 tao
      zOut =queryObj.getZippedPackage(docId, out, user, groups, passWord);
878 943 tao
      zOut.finish(); //terminate the zip file
879
      zOut.close();  //close the zip stream
880 1360 tao
881
    }//try
882 943 tao
    catch (Exception e)
883
    {
884
      try
885
      {
886
        response.setContentType("text/xml"); //MIME type
887 1292 tao
        // Send error message back
888 943 tao
        if (out != null)
889
        {
890
            PrintWriter pw = new PrintWriter(out);
891
            pw.println("<?xml version=\"1.0\"?>");
892
            pw.println("<error>");
893
            pw.println(e.getMessage());
894
            pw.println("</error>");
895 1292 tao
            // Close printwriter
896 943 tao
            pw.close();
897 1292 tao
            // Close output stream
898
            out.close();
899
        }//if
900 1360 tao
        // Close zip output stream
901 943 tao
        if ( zOut != null )
902
        {
903
          zOut.close();
904 1292 tao
        }//if
905
      }//try
906 943 tao
      catch (IOException ioe)
907
      {
908 1217 tao
        MetaCatUtil.debugMessage("Problem with the servlet output " +
909 1292 tao
                           "in MetacatServlet.handleExportAction: " +
910 1217 tao
                           ioe.getMessage(), 30);
911 1292 tao
      }//catch
912 943 tao
913 1292 tao
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleExportAction: " +
914 1217 tao
                         e.getMessage(), 30);
915 1292 tao
      e.printStackTrace(System.out);
916 1360 tao
917 943 tao
    }//catch
918 1360 tao
919 943 tao
  }//handleExportAction
920 1360 tao
921 1716 berkley
922 1483 tao
   //read inline data section
923
 /**
924 1716 berkley
   * In eml2 document, the xml can have inline data and data was stripped off
925 1483 tao
   * and store in file system. This action can be used to read inline data only
926
   * @param params the Hashtable of HTTP request parameters
927
   * @param response the HTTP response object linked to the client
928
   * @param user the username sent the request
929
   * @param groups the user's groupnames
930
   */
931
  private void handleReadInlineDataAction(Hashtable params,
932
                                          HttpServletResponse response,
933
                                          String user, String passWord,
934
                                          String[] groups)
935
  {
936
    String[] docs = new String[10];
937
    String inlineDataId = null;
938
    String docId = "";
939
    ServletOutputStream out = null;
940
941
    try
942
    {
943
      // read the params
944 1490 tao
      if (params.containsKey("inlinedataid"))
945 1483 tao
      {
946 1490 tao
        docs = (String[])params.get("inlinedataid");
947 1483 tao
      }//if
948
      // Get the docid
949
      inlineDataId=docs[0];
950
      // Make sure the client specify docid
951
      if (inlineDataId == null || inlineDataId.equals(""))
952
      {
953 1490 tao
        throw new Exception("You didn't specify requested inlinedataid");
954 1483 tao
      }//if
955 1716 berkley
956 1483 tao
      // check for permission
957 1490 tao
      docId = MetaCatUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
958
      PermissionController controller = new PermissionController(docId);
959
      // check top level read permission
960 1716 berkley
      if (!controller.hasPermission(user, groups,
961 1490 tao
                                    AccessControlInterface.READSTRING))
962
      {
963
          throw new Exception("User "+ user + " doesn't have permission "+
964
                              " to read document " + docId);
965
      }//if
966
      // if the document has subtree control, we need to check subtree control
967
      else if(controller.hasSubTreeAccessControl())
968
      {
969
        // get node id for inlinedata
970
        long nodeId=getInlineDataNodeId(inlineDataId, docId);
971
        if (!controller.hasPermissionForSubTreeNode(user, groups,
972
                                     AccessControlInterface.READSTRING, nodeId))
973
        {
974
           throw new Exception("User "+ user + " doesn't have permission "+
975
                              " to read inlinedata " + inlineDataId);
976
        }//if
977 1716 berkley
978 1490 tao
      }//else
979 1716 berkley
980 1483 tao
      // Get output stream
981
      out = response.getOutputStream();
982
      // read the inline data from the file
983
      String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
984
      File lineData = new File(inlinePath, inlineDataId);
985
      FileInputStream input = new FileInputStream(lineData);
986
      byte [] buffer = new byte[4*1024];
987
      int bytes = input.read(buffer);
988
      while (bytes != -1)
989
      {
990
        out.write(buffer, 0, bytes);
991
        bytes = input.read(buffer);
992
      }
993
      out.close();
994
995
    }//try
996
    catch (Exception e)
997
    {
998
      try
999 1716 berkley
      {
1000 1490 tao
        PrintWriter pw = null;
1001 1483 tao
        // Send error message back
1002
        if (out != null)
1003
        {
1004 1490 tao
            pw = new PrintWriter(out);
1005 1483 tao
        }//if
1006 1490 tao
        else
1007
        {
1008
          pw = response.getWriter();
1009 1716 berkley
        }
1010 1490 tao
         pw.println("<?xml version=\"1.0\"?>");
1011
         pw.println("<error>");
1012
         pw.println(e.getMessage());
1013
         pw.println("</error>");
1014
         // Close printwriter
1015
         pw.close();
1016
         // Close output stream if out is not null
1017
         if (out != null)
1018
         {
1019
           out.close();
1020
         }
1021 1483 tao
     }//try
1022
     catch (IOException ioe)
1023
     {
1024
        MetaCatUtil.debugMessage("Problem with the servlet output " +
1025
                           "in MetacatServlet.handleExportAction: " +
1026
                           ioe.getMessage(), 30);
1027
     }//catch
1028
1029 1716 berkley
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadInlineDataAction: "
1030 1483 tao
                                + e.getMessage(), 30);
1031 1716 berkley
1032 1483 tao
    }//catch
1033
1034
  }//handleReadInlineDataAction
1035 1716 berkley
1036 1490 tao
  /*
1037
   * Get the nodeid from xml_nodes for the inlinedataid
1038
   */
1039 1716 berkley
  private long getInlineDataNodeId(String inLineDataId, String docId)
1040 1490 tao
                                   throws SQLException
1041
  {
1042
    long nodeId = 0;
1043
    String INLINE = "inline";
1044
    boolean hasRow;
1045
    PreparedStatement pStmt = null;
1046
    DBConnection conn = null;
1047
    int serialNumber = -1;
1048
    String sql ="SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? " +
1049
                "AND nodetype='TEXT' AND parentnodeid IN " +
1050 1716 berkley
                "(SELECT nodeid FROM xml_nodes WHERE docid=? AND " +
1051 1490 tao
                "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
1052 1716 berkley
1053 1490 tao
    try
1054
    {
1055
      //check out DBConnection
1056
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
1057
      serialNumber=conn.getCheckOutSerialNumber();
1058 1716 berkley
1059 1490 tao
      pStmt = conn.prepareStatement(sql);
1060
      //bind value
1061
      pStmt.setString(1, docId);//docid
1062
      pStmt.setString(2, inLineDataId);//inlinedataid
1063
      pStmt.setString(3, docId);
1064 1716 berkley
      // excute query
1065 1490 tao
      pStmt.execute();
1066
      ResultSet rs = pStmt.getResultSet();
1067
      hasRow=rs.next();
1068
      // get result
1069
      if (hasRow)
1070
      {
1071 1716 berkley
        nodeId = rs.getLong(1);
1072 1490 tao
      }//if
1073 1716 berkley
1074 1490 tao
    }//try
1075
    catch (SQLException e)
1076
    {
1077
      throw e;
1078
    }
1079
    finally
1080
    {
1081
      try
1082
      {
1083
        pStmt.close();
1084
      }
1085
      finally
1086
      {
1087
        DBConnectionPool.returnDBConnection(conn, serialNumber);
1088
      }
1089
    }
1090
    MetaCatUtil.debugMessage("The nodeid for inlinedataid " + inLineDataId +
1091
                             " is: "+nodeId, 35);
1092
    return nodeId;
1093
  }
1094 1716 berkley
1095
1096
1097 731 bojilova
  // READ SECTION
1098 1360 tao
  /**
1099 731 bojilova
   * Handle the "read" request of metadata/data files from Metacat
1100
   * or any files from Internet;
1101
   * transformed metadata XML document into HTML presentation if requested;
1102
   * zip files when more than one were requested.
1103
   *
1104
   * @param params the Hashtable of HTTP request parameters
1105
   * @param response the HTTP response object linked to the client
1106
   * @param user the username sent the request
1107 802 bojilova
   * @param groups the user's groupnames
1108 437 berkley
   */
1109 731 bojilova
  private void handleReadAction(Hashtable params, HttpServletResponse response,
1110 1360 tao
                                String user, String passWord, String[] groups)
1111 437 berkley
  {
1112 731 bojilova
    ServletOutputStream out = null;
1113
    ZipOutputStream zout = null;
1114 1292 tao
    PrintWriter pw = null;
1115
    boolean zip = false;
1116 1482 tao
    boolean withInlineData = true;
1117 1360 tao
1118 731 bojilova
    try {
1119
      String[] docs = new String[0];
1120
      String docid = "";
1121
      String qformat = "";
1122
      String abstrpath = null;
1123 1360 tao
1124 731 bojilova
      // read the params
1125
      if (params.containsKey("docid")) {
1126
        docs = (String[])params.get("docid");
1127 437 berkley
      }
1128 731 bojilova
      if (params.containsKey("qformat")) {
1129
        qformat = ((String[])params.get("qformat"))[0];
1130 437 berkley
      }
1131 1482 tao
      // the param for only metadata (eml)
1132
      if (params.containsKey("inlinedata"))
1133
      {
1134 1716 berkley
1135 1482 tao
        String inlineData = ((String[])params.get("inlinedata"))[0];
1136
        if (inlineData.equalsIgnoreCase("false"))
1137
        {
1138
          withInlineData = false;
1139
        }
1140 1716 berkley
      }
1141 731 bojilova
      if ( (docs.length > 1) || qformat.equals("zip") ) {
1142
        zip = true;
1143
        out = response.getOutputStream();
1144
        response.setContentType("application/zip"); //MIME type
1145
        zout = new ZipOutputStream(out);
1146
      }
1147
      // go through the list of docs to read
1148
      for (int i=0; i < docs.length; i++ ) {
1149
        try {
1150
1151
          URL murl = new URL(docs[i]);
1152
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
1153 1360 tao
          // case docid="http://.../?docid=aaa"
1154 731 bojilova
          // or docid="metacat://.../?docid=bbb"
1155
          if (murlQueryStr.containsKey("docid")) {
1156
            // get only docid, eliminate the rest
1157
            docid = (String)murlQueryStr.get("docid");
1158
            if ( zip ) {
1159 947 tao
              addDocToZip(docid, zout, user, groups);
1160 731 bojilova
            } else {
1161
              readFromMetacat(response, docid, qformat, abstrpath,
1162 1665 tao
                              user, groups, zip, zout, withInlineData, params);
1163 731 bojilova
            }
1164
1165
          // case docid="http://.../filename"
1166
          } else {
1167
            docid = docs[i];
1168
            if ( zip ) {
1169 947 tao
              addDocToZip(docid, zout, user, groups);
1170 731 bojilova
            } else {
1171
              readFromURLConnection(response, docid);
1172
            }
1173
          }
1174
1175
        // case docid="ccc"
1176
        } catch (MalformedURLException mue) {
1177
          docid = docs[i];
1178
          if ( zip ) {
1179 947 tao
            addDocToZip(docid, zout, user, groups);
1180 731 bojilova
          } else {
1181
            readFromMetacat(response, docid, qformat, abstrpath,
1182 1665 tao
                            user, groups, zip, zout, withInlineData, params);
1183 731 bojilova
          }
1184
        }
1185 1360 tao
1186 731 bojilova
      } /* end for */
1187 1360 tao
1188 731 bojilova
      if ( zip ) {
1189
        zout.finish(); //terminate the zip file
1190
        zout.close();  //close the zip stream
1191
      }
1192 1360 tao
1193
1194 1292 tao
    }
1195
    // To handle doc not found exception
1196
    catch (McdbDocNotFoundException notFoundE)
1197
    {
1198
      // the docid which didn't be found
1199
      String notFoundDocId = notFoundE.getUnfoundDocId();
1200
      String notFoundRevision = notFoundE.getUnfoundRevision();
1201
      MetaCatUtil.debugMessage("Missed id: "+ notFoundDocId, 30);
1202
      MetaCatUtil.debugMessage("Missed rev: "+ notFoundRevision, 30);
1203
      try
1204
      {
1205
        // read docid from remote server
1206
        readFromRemoteMetaCat(response, notFoundDocId, notFoundRevision,
1207
                                              user, passWord, out, zip, zout);
1208
        // Close zout outputstream
1209
        if ( zout != null)
1210
        {
1211
          zout.close();
1212
        }
1213
        // close output stream
1214
        if (out != null)
1215
        {
1216
          out.close();
1217
        }
1218 1360 tao
1219 1292 tao
      }//try
1220
      catch ( Exception exc)
1221
      {
1222
        MetaCatUtil.debugMessage("Erorr in MetacatServlet.hanldReadAction: "+
1223
                                      exc.getMessage(), 30);
1224
        try
1225
        {
1226 1360 tao
          if (out != null)
1227 1292 tao
          {
1228
            response.setContentType("text/xml");
1229
            // Send back error message by printWriter
1230
            pw = new PrintWriter(out);
1231
            pw.println("<?xml version=\"1.0\"?>");
1232
            pw.println("<error>");
1233
            pw.println(notFoundE.getMessage());
1234
            pw.println("</error>");
1235
            pw.close();
1236
            out.close();
1237 1360 tao
1238 1292 tao
          }
1239
          else
1240
          {
1241
           response.setContentType("text/xml"); //MIME type
1242
           // Send back error message if out = null
1243
           if (pw == null)
1244
           {
1245
             // If pw is null, open the respnose
1246
            pw = response.getWriter();
1247
           }
1248
           pw.println("<?xml version=\"1.0\"?>");
1249
           pw.println("<error>");
1250
           pw.println(notFoundE.getMessage());
1251
           pw.println("</error>");
1252
           pw.close();
1253
        }
1254
        // close zout
1255 1360 tao
        if ( zout != null )
1256
        {
1257
          zout.close();
1258 1292 tao
        }
1259
        }//try
1260
        catch (IOException ie)
1261
        {
1262
          MetaCatUtil.debugMessage("Problem with the servlet output " +
1263
                           "in MetacatServlet.handleReadAction: " +
1264
                           ie.getMessage(), 30);
1265
        }//cathch
1266
      }//catch
1267
    }// catch McdbDocNotFoundException
1268 1360 tao
    catch (Exception e)
1269 1292 tao
    {
1270 731 bojilova
      try {
1271 1360 tao
1272 845 jones
        if (out != null) {
1273 1292 tao
            response.setContentType("text/xml"); //MIME type
1274
            pw = new PrintWriter(out);
1275 845 jones
            pw.println("<?xml version=\"1.0\"?>");
1276
            pw.println("<error>");
1277
            pw.println(e.getMessage());
1278
            pw.println("</error>");
1279
            pw.close();
1280 1292 tao
            out.close();
1281 845 jones
        }
1282 1292 tao
        else
1283
        {
1284
           response.setContentType("text/xml"); //MIME type
1285
           // Send back error message if out = null
1286
           if ( pw == null)
1287
           {
1288
            pw = response.getWriter();
1289
           }
1290
           pw.println("<?xml version=\"1.0\"?>");
1291
           pw.println("<error>");
1292
           pw.println(e.getMessage());
1293
           pw.println("</error>");
1294
           pw.close();
1295 1360 tao
1296 1292 tao
        }
1297
        // Close zip output stream
1298 731 bojilova
        if ( zout != null ) { zout.close(); }
1299 1360 tao
1300 731 bojilova
      } catch (IOException ioe) {
1301 1292 tao
        MetaCatUtil.debugMessage("Problem with the servlet output " +
1302 731 bojilova
                           "in MetacatServlet.handleReadAction: " +
1303 1292 tao
                           ioe.getMessage(), 30);
1304 731 bojilova
        ioe.printStackTrace(System.out);
1305 1360 tao
1306 731 bojilova
      }
1307
1308 1482 tao
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadAction: " +
1309
                               e.getMessage(), 30);
1310
      //e.printStackTrace(System.out);
1311 437 berkley
    }
1312 1360 tao
1313 437 berkley
  }
1314 1360 tao
1315 731 bojilova
  // read metadata or data from Metacat
1316
  private void readFromMetacat(HttpServletResponse response, String docid,
1317
                               String qformat, String abstrpath, String user,
1318 1716 berkley
                               String[] groups, boolean zip,
1319 1665 tao
                               ZipOutputStream zout, boolean withInlineData,
1320
                               Hashtable params)
1321 1360 tao
               throws ClassNotFoundException, IOException, SQLException,
1322 731 bojilova
                      McdbException, Exception
1323 453 berkley
  {
1324 1360 tao
1325 731 bojilova
    try {
1326 1360 tao
1327
1328 1217 tao
      DocumentImpl doc = new DocumentImpl(docid);
1329 1360 tao
1330 947 tao
      //check the permission for read
1331 1217 tao
      if (!doc.hasReadPermission(user, groups, docid))
1332 947 tao
      {
1333
        Exception e = new Exception("User " + user + " does not have permission"
1334
                       +" to read the document with the docid " + docid);
1335 1360 tao
1336 947 tao
        throw e;
1337
      }
1338 1360 tao
1339 731 bojilova
      if ( doc.getRootNodeID() == 0 ) {
1340
        // this is data file
1341
        String filepath = util.getOption("datafilepath");
1342
        if(!filepath.endsWith("/")) {
1343
          filepath += "/";
1344
        }
1345 1292 tao
        String filename = filepath + docid;
1346
        FileInputStream fin = null;
1347
        fin = new FileInputStream(filename);
1348 1360 tao
1349 1292 tao
        //MIME type
1350 731 bojilova
        String contentType = getServletContext().getMimeType(filename);
1351 1716 berkley
        if (contentType == null)
1352 1556 tao
        {
1353
          ContentTypeProvider provider = new ContentTypeProvider(docid);
1354
          contentType = provider.getContentType();
1355
          MetaCatUtil.debugMessage("Final contenttype is: "+ contentType, 30);
1356 453 berkley
        }
1357 1716 berkley
1358 731 bojilova
        response.setContentType(contentType);
1359 733 bojilova
        // if we decide to use "application/octet-stream" for all data returns
1360
        // response.setContentType("application/octet-stream");
1361 1360 tao
1362 731 bojilova
        try {
1363 1360 tao
1364
          ServletOutputStream out = response.getOutputStream();
1365 731 bojilova
          byte[] buf = new byte[4 * 1024]; // 4K buffer
1366
          int b = fin.read(buf);
1367
          while (b != -1) {
1368
            out.write(buf, 0, b);
1369
            b = fin.read(buf);
1370 453 berkley
          }
1371 731 bojilova
        } finally {
1372
          if (fin != null) fin.close();
1373 453 berkley
        }
1374 731 bojilova
1375
      } else {
1376
        // this is metadata doc
1377 1360 tao
        if ( qformat.equals("xml") ) {
1378
1379 832 jones
          // set content type first
1380
          response.setContentType("text/xml");   //MIME type
1381
          PrintWriter out = response.getWriter();
1382 1482 tao
          doc.toXml(out, user, groups, withInlineData);
1383 832 jones
        } else {
1384 731 bojilova
          response.setContentType("text/html");  //MIME type
1385
          PrintWriter out = response.getWriter();
1386 1360 tao
1387 731 bojilova
          // Look up the document type
1388
          String doctype = doc.getDoctype();
1389
          // Transform the document to the new doctype
1390 1217 tao
          DBTransform dbt = new DBTransform();
1391 1482 tao
          dbt.transformXMLDocument(doc.toString(user, groups, withInlineData),
1392 1716 berkley
                                   doctype,"-//W3C//HTML//EN",
1393 1665 tao
                                   qformat, out, params);
1394 731 bojilova
        }
1395 1360 tao
1396 453 berkley
      }
1397 1292 tao
    }
1398 1360 tao
    catch (Exception except)
1399 1292 tao
    {
1400 1217 tao
      throw except;
1401 1360 tao
1402 731 bojilova
    }
1403 1360 tao
1404 731 bojilova
  }
1405 1360 tao
1406 731 bojilova
  // read data from URLConnection
1407
  private void readFromURLConnection(HttpServletResponse response, String docid)
1408
               throws IOException, MalformedURLException
1409 566 jones
  {
1410 1360 tao
    ServletOutputStream out = response.getOutputStream();
1411 731 bojilova
    String contentType = getServletContext().getMimeType(docid); //MIME type
1412
    if (contentType == null) {
1413
      if (docid.endsWith(".xml")) {
1414
        contentType="text/xml";
1415
      } else if (docid.endsWith(".css")) {
1416
        contentType="text/css";
1417
      } else if (docid.endsWith(".dtd")) {
1418
        contentType="text/plain";
1419
      } else if (docid.endsWith(".xsd")) {
1420 733 bojilova
        contentType="text/xml";
1421 731 bojilova
      } else if (docid.endsWith("/")) {
1422 733 bojilova
        contentType="text/html";
1423 731 bojilova
      } else {
1424 733 bojilova
        File f = new File(docid);
1425
        if ( f.isDirectory() ) {
1426
          contentType="text/html";
1427
        } else {
1428
          contentType="application/octet-stream";
1429
        }
1430 731 bojilova
      }
1431
    }
1432
    response.setContentType(contentType);
1433 733 bojilova
    // if we decide to use "application/octet-stream" for all data returns
1434
    // response.setContentType("application/octet-stream");
1435 731 bojilova
1436
    // this is http url
1437
    URL url = new URL(docid);
1438
    BufferedInputStream bis = null;
1439 566 jones
    try {
1440 731 bojilova
      bis = new BufferedInputStream(url.openStream());
1441
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1442
      int b = bis.read(buf);
1443
      while (b != -1) {
1444
        out.write(buf, 0, b);
1445
        b = bis.read(buf);
1446 636 berkley
      }
1447 731 bojilova
    } finally {
1448
      if (bis != null) bis.close();
1449 566 jones
    }
1450 1360 tao
1451 566 jones
  }
1452 1360 tao
1453 731 bojilova
  // read file/doc and write to ZipOutputStream
1454 1360 tao
  private void addDocToZip(String docid, ZipOutputStream zout,
1455 947 tao
                              String user, String[] groups)
1456 1360 tao
               throws ClassNotFoundException, IOException, SQLException,
1457 731 bojilova
                      McdbException, Exception
1458 636 berkley
  {
1459 731 bojilova
    byte[] bytestring = null;
1460
    ZipEntry zentry = null;
1461
1462
    try {
1463
      URL url = new URL(docid);
1464
1465
      // this http url; read from URLConnection; add to zip
1466
      zentry = new ZipEntry(docid);
1467
      zout.putNextEntry(zentry);
1468
      BufferedInputStream bis = null;
1469
      try {
1470
        bis = new BufferedInputStream(url.openStream());
1471
        byte[] buf = new byte[4 * 1024]; // 4K buffer
1472
        int b = bis.read(buf);
1473
        while(b != -1) {
1474
          zout.write(buf, 0, b);
1475
          b = bis.read(buf);
1476
        }
1477
      } finally {
1478
        if (bis != null) bis.close();
1479 636 berkley
      }
1480 731 bojilova
      zout.closeEntry();
1481
1482
    } catch (MalformedURLException mue) {
1483 1360 tao
1484 731 bojilova
      // this is metacat doc (data file or metadata doc)
1485 1360 tao
1486 731 bojilova
      try {
1487 1360 tao
1488 1217 tao
        DocumentImpl doc = new DocumentImpl(docid);
1489 1360 tao
1490 947 tao
        //check the permission for read
1491 1217 tao
        if (!doc.hasReadPermission(user, groups, docid))
1492 947 tao
        {
1493
          Exception e = new Exception("User " + user + " does not have "
1494
                    +"permission to read the document with the docid " + docid);
1495 1360 tao
1496 947 tao
          throw e;
1497 1360 tao
        }
1498
1499 731 bojilova
        if ( doc.getRootNodeID() == 0 ) {
1500
          // this is data file; add file to zip
1501
          String filepath = util.getOption("datafilepath");
1502
          if(!filepath.endsWith("/")) {
1503
            filepath += "/";
1504
          }
1505 1292 tao
          String filename = filepath + docid;
1506 731 bojilova
          FileInputStream fin = null;
1507 1292 tao
          fin = new FileInputStream(filename);
1508 731 bojilova
          try {
1509 1360 tao
1510 1292 tao
            zentry = new ZipEntry(docid);
1511
            zout.putNextEntry(zentry);
1512 731 bojilova
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1513
            int b = fin.read(buf);
1514
            while (b != -1) {
1515
              zout.write(buf, 0, b);
1516
              b = fin.read(buf);
1517
            }
1518
          } finally {
1519
            if (fin != null) fin.close();
1520
          }
1521
          zout.closeEntry();
1522
1523
        } else {
1524
          // this is metadata doc; add doc to zip
1525
          bytestring = doc.toString().getBytes();
1526
          zentry = new ZipEntry(docid + ".xml");
1527
          zentry.setSize(bytestring.length);
1528
          zout.putNextEntry(zentry);
1529
          zout.write(bytestring, 0, bytestring.length);
1530
          zout.closeEntry();
1531 636 berkley
        }
1532 1217 tao
      } catch (Exception except) {
1533
        throw except;
1534 1360 tao
1535 636 berkley
      }
1536 1360 tao
1537 636 berkley
    }
1538 1360 tao
1539 636 berkley
  }
1540 2072 jones
1541 1292 tao
  /**
1542
   * If metacat couldn't find a data file or document locally, it will read this
1543
   * docid from its home server. This is for the replication feature
1544
   */
1545 1360 tao
  private void readFromRemoteMetaCat(HttpServletResponse response, String docid,
1546
                     String rev, String user, String password,
1547 1292 tao
                     ServletOutputStream out, boolean zip, ZipOutputStream zout)
1548
                        throws Exception
1549
 {
1550
   // Create a object of RemoteDocument, "" is for zipEntryPath
1551 1360 tao
   RemoteDocument remoteDoc =
1552 1292 tao
                        new RemoteDocument (docid, rev,user, password, "");
1553 1293 tao
   String docType = remoteDoc.getDocType();
1554
   // Only read data file
1555
   if (docType.equals("BIN"))
1556 1292 tao
   {
1557 1293 tao
    // If it is zip format
1558
    if (zip)
1559
    {
1560
      remoteDoc.readDocumentFromRemoteServerByZip(zout);
1561 1360 tao
    }//if
1562 1293 tao
    else
1563
    {
1564
      if (out == null)
1565
      {
1566
        out = response.getOutputStream();
1567
      }//if
1568
      response.setContentType("application/octet-stream");
1569
      remoteDoc.readDocumentFromRemoteServer(out);
1570
    }//else (not zip)
1571 1360 tao
   }//if doctype=bin
1572 1292 tao
   else
1573
   {
1574 1293 tao
     throw new Exception("Docid: "+docid+"."+rev+" couldn't find");
1575 1360 tao
   }//else
1576 1292 tao
 }//readFromRemoteMetaCat
1577 1360 tao
1578 731 bojilova
  // END OF READ SECTION
1579 1716 berkley
1580
1581
1582 731 bojilova
  // INSERT/UPDATE SECTION
1583 1360 tao
  /**
1584
   * Handle the database putdocument request and write an XML document
1585 55 jones
   * to the database connection
1586
   */
1587 1360 tao
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1588 1377 tao
               String user, String[] groups) {
1589 59 jones
1590 1217 tao
    DBConnection dbConn = null;
1591
    int serialNumber = -1;
1592 309 bojilova
1593 204 jones
    try {
1594
      // Get the document indicated
1595
      String[] doctext = (String[])params.get("doctext");
1596 557 bojilova
1597 680 bojilova
      String pub = null;
1598
      if (params.containsKey("public")) {
1599
        pub = ((String[])params.get("public"))[0];
1600 557 bojilova
      }
1601 680 bojilova
1602 598 bojilova
      StringReader dtd = null;
1603 680 bojilova
      if (params.containsKey("dtdtext")) {
1604 598 bojilova
        String[] dtdtext = (String[])params.get("dtdtext");
1605
        try {
1606 619 bojilova
          if ( !dtdtext[0].equals("") ) {
1607
            dtd = new StringReader(dtdtext[0]);
1608
          }
1609 598 bojilova
        } catch (NullPointerException npe) {}
1610
      }
1611 1360 tao
1612 1760 tao
      StringReader xml = new StringReader(doctext[0]);
1613 695 bojilova
      boolean validate = false;
1614 1384 tao
      DocumentImplWrapper documentWrapper = null;
1615 204 jones
      try {
1616 1360 tao
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1617 695 bojilova
        // in order to decide whether to use validation parser
1618 1760 tao
        validate = needDTDValidation(xml);
1619 1384 tao
        if (validate)
1620
        {
1621
          // set a dtd base validation parser
1622
          String rule = DocumentImpl.DTD;
1623
          documentWrapper = new DocumentImplWrapper(rule, validate);
1624
        }
1625 1760 tao
        else if (needSchemaValidation(xml))
1626 1384 tao
        {
1627 1409 tao
          // for eml2
1628 1760 tao
          if (needEml2Validation(xml))
1629 1409 tao
          {
1630
             // set eml2 base validation parser
1631
            String rule = DocumentImpl.EML2;
1632 1471 tao
            // using emlparser to check id validation
1633
            EMLParser parser = new EMLParser(doctext[0]);
1634 1409 tao
            documentWrapper = new DocumentImplWrapper(rule, true);
1635
          }
1636
          else
1637
          {
1638
            // set schema base validation parser
1639
            String rule = DocumentImpl.SCHEMA;
1640
            documentWrapper = new DocumentImplWrapper(rule, true);
1641
          }
1642 1384 tao
        }
1643
        else
1644
        {
1645
          documentWrapper = new DocumentImplWrapper("", false);
1646
        }
1647 1716 berkley
1648 204 jones
        String[] action = (String[])params.get("action");
1649
        String[] docid = (String[])params.get("docid");
1650
        String newdocid = null;
1651 203 jones
1652 204 jones
        String doAction = null;
1653
        if (action[0].equals("insert")) {
1654
          doAction = "INSERT";
1655
        } else if (action[0].equals("update")) {
1656
          doAction = "UPDATE";
1657
        }
1658 1360 tao
1659
        try
1660 1217 tao
        {
1661 680 bojilova
          // get a connection from the pool
1662 1217 tao
          dbConn=DBConnectionPool.
1663
                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1664
          serialNumber=dbConn.getCheckOutSerialNumber();
1665 1360 tao
1666 1760 tao
           // write the document to the database
1667 1360 tao
          try
1668 1217 tao
          {
1669 680 bojilova
            String accNumber = docid[0];
1670 1292 tao
            MetaCatUtil.debugMessage(""+ doAction + " " + accNumber +"...", 10);
1671 1360 tao
            if (accNumber.equals(""))
1672 1217 tao
            {
1673 680 bojilova
              accNumber = null;
1674 1217 tao
            }//if
1675 1384 tao
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1676
                                          accNumber, user, groups);
1677 1360 tao
1678
          }//try
1679
          catch (NullPointerException npe)
1680 1217 tao
          {
1681 1384 tao
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1682
                                          null, user, groups);
1683 1217 tao
          }//catch
1684 1716 berkley
1685 1360 tao
        }//try
1686
        finally
1687 1217 tao
        {
1688
          // Return db connection
1689
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1690 1360 tao
        }
1691 309 bojilova
1692 204 jones
        // set content type and other response header fields first
1693 1377 tao
        //response.setContentType("text/xml");
1694 204 jones
        out.println("<?xml version=\"1.0\"?>");
1695
        out.println("<success>");
1696 1360 tao
        out.println("<docid>" + newdocid + "</docid>");
1697 204 jones
        out.println("</success>");
1698
1699 1716 berkley
      }
1700
      catch (NullPointerException npe)
1701 1466 tao
      {
1702 1377 tao
        //response.setContentType("text/xml");
1703 204 jones
        out.println("<?xml version=\"1.0\"?>");
1704
        out.println("<error>");
1705 1360 tao
        out.println(npe.getMessage());
1706 204 jones
        out.println("</error>");
1707 55 jones
      }
1708 1716 berkley
    }
1709
    catch (Exception e)
1710 1466 tao
    {
1711 1377 tao
      //response.setContentType("text/xml");
1712 204 jones
      out.println("<?xml version=\"1.0\"?>");
1713
      out.println("<error>");
1714 1360 tao
      out.println(e.getMessage());
1715 204 jones
      out.println("</error>");
1716 203 jones
    }
1717 55 jones
  }
1718 203 jones
1719 1360 tao
  /**
1720
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1721 695 bojilova
   * in order to decide whether to use validation parser
1722
   */
1723 1760 tao
  private static boolean needDTDValidation(StringReader xmlreader) throws
1724
                                                             IOException
1725
  {
1726 1360 tao
1727 1760 tao
1728 695 bojilova
    StringBuffer cbuff = new StringBuffer();
1729
    java.util.Stack st = new java.util.Stack();
1730
    boolean validate = false;
1731
    int c;
1732
    int inx;
1733 1360 tao
1734 695 bojilova
    // read from the stream until find the keywords
1735
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1736
      cbuff.append((char)c);
1737
1738
      // "<!DOCTYPE" keyword is found; put it in the stack
1739
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1740
        cbuff = new StringBuffer();
1741
        st.push("<!DOCTYPE");
1742
      }
1743
      // "PUBLIC" keyword is found; put it in the stack
1744
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1745
        cbuff = new StringBuffer();
1746
        st.push("PUBLIC");
1747
      }
1748
      // "SYSTEM" keyword is found; put it in the stack
1749
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1750
        cbuff = new StringBuffer();
1751
        st.push("SYSTEM");
1752
      }
1753
      // ">" character is found; put it in the stack
1754 1360 tao
      // ">" is found twice: fisrt from <?xml ...?>
1755 695 bojilova
      // and second from <!DOCTYPE ... >
1756
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1757
        cbuff = new StringBuffer();
1758
        st.push(">");
1759
      }
1760
    }
1761
1762
    // close the stream
1763 1760 tao
    xmlreader.reset();
1764 695 bojilova
1765
    // check the stack whether it contains the keywords:
1766
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1767
    if ( st.size() == 4 ) {
1768
      if ( ((String)st.pop()).equals(">") &&
1769
           ( ((String)st.peek()).equals("PUBLIC") |
1770
             ((String)st.pop()).equals("SYSTEM") ) &&
1771
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1772
        validate = true;
1773
      }
1774
    }
1775
1776 1384 tao
    MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1777 695 bojilova
    return validate;
1778
  }
1779 731 bojilova
  // END OF INSERT/UPDATE SECTION
1780 1716 berkley
1781 1384 tao
  /* check if the xml string contains key words to specify schema loocation*/
1782 1760 tao
  private boolean needSchemaValidation(StringReader xml) throws IOException
1783 1384 tao
  {
1784
    boolean needSchemaValidate =false;
1785
    if (xml == null)
1786
    {
1787
      MetaCatUtil.debugMessage("Validation for schema is " +
1788
                               needSchemaValidate, 10);
1789
      return needSchemaValidate;
1790
    }
1791 1760 tao
    System.out.println("before get target line");
1792 1629 tao
    String targetLine = getSchemaLine(xml);
1793 1760 tao
    System.out.println("before get target line");
1794 1716 berkley
    // to see if the second line contain some keywords
1795 1629 tao
    if (targetLine != null && (targetLine.indexOf(SCHEMALOCATIONKEYWORD) != -1||
1796
             targetLine.indexOf(NONAMESPACELOCATION) != -1 ))
1797 1384 tao
    {
1798
      // if contains schema location key word, should be validate
1799
      needSchemaValidate = true;
1800
    }
1801 1716 berkley
1802
    MetaCatUtil.debugMessage("Validation for schema is " +
1803 1384 tao
                             needSchemaValidate, 10);
1804
    return needSchemaValidate;
1805 1716 berkley
1806 1384 tao
  }
1807 1716 berkley
1808 1409 tao
   /* check if the xml string contains key words to specify schema loocation*/
1809 1760 tao
  private boolean needEml2Validation(StringReader xml) throws IOException
1810 1409 tao
  {
1811
    boolean needEml2Validate =false;
1812 1760 tao
    String emlNameSpace =DocumentImpl.EMLNAMESPACE;
1813
    String schemaLocationContent = null;
1814 1409 tao
    if (xml == null)
1815
    {
1816
      MetaCatUtil.debugMessage("Validation for schema is " +
1817
                               needEml2Validate, 10);
1818
      return needEml2Validate;
1819
    }
1820 1629 tao
    String targetLine = getSchemaLine(xml);
1821 1716 berkley
1822 1760 tao
    if (targetLine != null)
1823 1409 tao
    {
1824 1760 tao
1825
      int startIndex = targetLine.indexOf(SCHEMALOCATIONKEYWORD);
1826
      int start = 1;
1827
      int end   = 1;
1828
      String schemaLocation = null;
1829
      int count = 0;
1830
      if (startIndex != -1)
1831
      {
1832
        for ( int i=startIndex; i<targetLine.length(); i++)
1833
        {
1834
          if (targetLine.charAt(i) =='"')
1835
          {
1836
            count ++;
1837
          }
1838
          if (targetLine.charAt(i) =='"' && count == 1)
1839
          {
1840
            start = i;
1841
          }
1842
          if (targetLine.charAt(i) =='"' && count == 2)
1843
          {
1844
            end = i;
1845
            break;
1846
          }
1847
        }
1848
      }
1849
      schemaLocation = targetLine.substring(start+1, end);
1850
      MetaCatUtil.debugMessage("schemaLocation in xml is: "+schemaLocation, 30);
1851
      if ( schemaLocation.indexOf(emlNameSpace) != -1)
1852
      {
1853
        needEml2Validate = true;
1854
      }
1855 1409 tao
    }
1856 1716 berkley
1857
    MetaCatUtil.debugMessage("Validation for eml is " +
1858 1409 tao
                             needEml2Validate, 10);
1859
    return needEml2Validate;
1860 1716 berkley
1861 1409 tao
  }
1862 1716 berkley
1863 1760 tao
  private String getSchemaLine(StringReader xml) throws IOException
1864 1629 tao
  {
1865
    // find the line
1866
    String secondLine = null;
1867
    int count =0;
1868
    int endIndex = 0;
1869
    int startIndex = 0;
1870
    final int TARGETNUM = 2;
1871 1760 tao
    StringBuffer buffer = new StringBuffer();
1872
    boolean comment =false;
1873
    char thirdPreviousCharacter = '?';
1874
    char secondPreviousCharacter ='?';
1875
    char previousCharacter = '?';
1876
    char currentCharacter = '?';
1877
1878
    while ( (currentCharacter = (char) xml.read()) != -1)
1879 1629 tao
    {
1880 1760 tao
      //in a comment
1881
      if (currentCharacter =='-' && previousCharacter == '-'  &&
1882
          secondPreviousCharacter =='!' && thirdPreviousCharacter == '<')
1883 1629 tao
      {
1884 1760 tao
        comment = true;
1885
      }
1886
      //out of comment
1887
      if (comment && currentCharacter == '>' && previousCharacter == '-' &&
1888
          secondPreviousCharacter =='-')
1889
      {
1890
         comment = false;
1891
      }
1892
1893
      //this is not comment
1894
      if (currentCharacter !='!' && previousCharacter == '<' && !comment)
1895
      {
1896 1629 tao
        count ++;
1897 1760 tao
      }
1898
      // get target line
1899
      if (count == TARGETNUM && currentCharacter !='>')
1900 1629 tao
      {
1901 1760 tao
        buffer.append(currentCharacter);
1902
      }
1903
      if (count == TARGETNUM && currentCharacter == '>')
1904
      {
1905
          break;
1906
      }
1907
      thirdPreviousCharacter = secondPreviousCharacter;
1908
      secondPreviousCharacter = previousCharacter;
1909
      previousCharacter = currentCharacter;
1910
1911
    }
1912
    secondLine = buffer.toString();
1913 1629 tao
    MetaCatUtil.debugMessage("the second line string is: "+secondLine, 25);
1914 1760 tao
    xml.reset();
1915 1629 tao
    return secondLine;
1916
  }
1917 1716 berkley
1918 731 bojilova
  // DELETE SECTION
1919 1360 tao
  /**
1920
   * Handle the database delete request and delete an XML document
1921 203 jones
   * from the database connection
1922
   */
1923 1360 tao
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1924 802 bojilova
               HttpServletResponse response, String user, String[] groups) {
1925 203 jones
1926
    String[] docid = (String[])params.get("docid");
1927 1360 tao
1928 203 jones
    // delete the document from the database
1929
    try {
1930 1360 tao
1931 203 jones
                                      // NOTE -- NEED TO TEST HERE
1932 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
1933 203 jones
                                      // BEFORE ACCESSING ARRAY
1934 1360 tao
      try {
1935 1217 tao
        DocumentImpl.delete(docid[0], user, groups);
1936 204 jones
        response.setContentType("text/xml");
1937
        out.println("<?xml version=\"1.0\"?>");
1938
        out.println("<success>");
1939 1360 tao
        out.println("Document deleted.");
1940 204 jones
        out.println("</success>");
1941 203 jones
      } catch (AccessionNumberException ane) {
1942 204 jones
        response.setContentType("text/xml");
1943
        out.println("<?xml version=\"1.0\"?>");
1944
        out.println("<error>");
1945
        out.println("Error deleting document!!!");
1946 1360 tao
        out.println(ane.getMessage());
1947 204 jones
        out.println("</error>");
1948 203 jones
      }
1949 204 jones
    } catch (Exception e) {
1950
      response.setContentType("text/xml");
1951
      out.println("<?xml version=\"1.0\"?>");
1952
      out.println("<error>");
1953 1360 tao
      out.println(e.getMessage());
1954 204 jones
      out.println("</error>");
1955 1360 tao
    }
1956 203 jones
  }
1957 731 bojilova
  // END OF DELETE SECTION
1958 1360 tao
1959 731 bojilova
  // VALIDATE SECTION
1960 1360 tao
  /**
1961 380 jones
   * Handle the validation request and return the results to the requestor
1962 68 higgins
   */
1963 1342 tao
  private void handleValidateAction(PrintWriter out, Hashtable params) {
1964 68 higgins
1965 103 jones
    // Get the document indicated
1966
    String valtext = null;
1967 1217 tao
    DBConnection dbConn = null;
1968
    int serialNumber = -1;
1969 1360 tao
1970 103 jones
    try {
1971
      valtext = ((String[])params.get("valtext"))[0];
1972
    } catch (Exception nullpe) {
1973 68 higgins
1974 1360 tao
1975 162 bojilova
      String docid = null;
1976 103 jones
      try {
1977
        // Find the document id number
1978 1360 tao
        docid = ((String[])params.get("docid"))[0];
1979 309 bojilova
1980 1360 tao
1981 309 bojilova
        // Get the document indicated from the db
1982 1217 tao
        DocumentImpl xmldoc = new DocumentImpl(docid);
1983 393 jones
        valtext = xmldoc.toString();
1984 185 jones
1985 103 jones
      } catch (NullPointerException npe) {
1986 1360 tao
1987 253 jones
        out.println("<error>Error getting document ID: " + docid + "</error>");
1988 1217 tao
        //if ( conn != null ) { util.returnConnection(conn); }
1989 380 jones
        return;
1990 309 bojilova
      } catch (Exception e) {
1991 1360 tao
1992
        out.println(e.getMessage());
1993
      }
1994 103 jones
    }
1995 68 higgins
1996 1360 tao
1997 103 jones
    try {
1998 309 bojilova
      // get a connection from the pool
1999 1217 tao
      dbConn=DBConnectionPool.
2000
                  getDBConnection("MetaCatServlet.handleValidateAction");
2001
      serialNumber=dbConn.getCheckOutSerialNumber();
2002
      DBValidate valobj = new DBValidate(saxparser,dbConn);
2003 185 jones
      boolean valid = valobj.validateString(valtext);
2004 68 higgins
2005
      // set content type and other response header fields first
2006 1360 tao
2007 253 jones
      out.println(valobj.returnErrors());
2008
2009 103 jones
    } catch (NullPointerException npe2) {
2010
      // set content type and other response header fields first
2011 1360 tao
2012
      out.println("<error>Error validating document.</error>");
2013 309 bojilova
    } catch (Exception e) {
2014 1360 tao
2015
      out.println(e.getMessage());
2016 309 bojilova
    } finally {
2017 1217 tao
      // Return db connection
2018
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2019 1360 tao
    }
2020 103 jones
  }
2021 731 bojilova
  // END OF VALIDATE SECTION
2022 1360 tao
2023 731 bojilova
  // OTHER ACTION HANDLERS
2024 1360 tao
2025 1292 tao
  /**
2026
   * Handle "getrevsionanddoctype" action
2027
   * Given a docid, return it's current revision and doctype from data base
2028
   * The output is String look like "rev;doctype"
2029
   */
2030 1360 tao
  private void handleGetRevisionAndDocTypeAction(PrintWriter out,
2031 1292 tao
                                                              Hashtable params)
2032
  {
2033
    // To store doc parameter
2034
    String [] docs = new String[10];
2035
    // Store a single doc id
2036
    String givenDocId = null;
2037
    // Get docid from parameters
2038 1360 tao
    if (params.containsKey("docid"))
2039 1292 tao
    {
2040
      docs = (String[])params.get("docid");
2041
    }
2042
    // Get first docid form string array
2043
    givenDocId = docs[0];
2044 1360 tao
2045
    try
2046 1292 tao
    {
2047
      // Make sure there is a docid
2048
      if (givenDocId == null || givenDocId.equals(""))
2049
      {
2050
        throw new Exception("User didn't specify docid!");
2051
      }//if
2052 1360 tao
2053 1292 tao
      // Create a DBUtil object
2054
      DBUtil dbutil = new DBUtil();
2055
      // Get a rev and doctype
2056 1360 tao
      String revAndDocType =
2057 1292 tao
                dbutil.getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
2058
      out.println(revAndDocType);
2059
2060 1360 tao
    }//try
2061
    catch (Exception e)
2062 1292 tao
    {
2063
      // Handle exception
2064
      out.println("<?xml version=\"1.0\"?>");
2065
      out.println("<error>");
2066
      out.println(e.getMessage());
2067
      out.println("</error>");
2068 1360 tao
    }//catch
2069
2070 1292 tao
  }//handleGetRevisionAndDocTypeAction
2071 1360 tao
2072
  /**
2073 688 bojilova
   * Handle "getaccesscontrol" action.
2074
   * Read Access Control List from db connection in XML format
2075
   */
2076 1360 tao
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
2077
                                       HttpServletResponse response,
2078 802 bojilova
                                       String username, String[] groupnames) {
2079 688 bojilova
2080 1217 tao
    DBConnection dbConn = null;
2081
    int serialNumber = -1;
2082 688 bojilova
    String docid = ((String[])params.get("docid"))[0];
2083 1360 tao
2084 688 bojilova
    try {
2085
2086
        // get connection from the pool
2087 1217 tao
        dbConn=DBConnectionPool.
2088
                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2089
        serialNumber=dbConn.getCheckOutSerialNumber();
2090
        AccessControlList aclobj = new AccessControlList(dbConn);
2091 802 bojilova
        String acltext = aclobj.getACL(docid, username, groupnames);
2092 688 bojilova
        out.println(acltext);
2093
2094
    } catch (Exception e) {
2095
      out.println("<?xml version=\"1.0\"?>");
2096
      out.println("<error>");
2097
      out.println(e.getMessage());
2098
      out.println("</error>");
2099
    } finally {
2100 1217 tao
      // Retrun db connection to pool
2101
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2102 1360 tao
    }
2103
2104 688 bojilova
  }
2105
2106 1360 tao
  /**
2107 731 bojilova
   * Handle the "getprincipals" action.
2108
   * Read all principals from authentication scheme in XML format
2109
   */
2110
  private void handleGetPrincipalsAction(PrintWriter out, String user,
2111
                                         String password) {
2112
2113 1360 tao
2114 731 bojilova
    try {
2115
2116 1360 tao
2117 731 bojilova
        AuthSession auth = new AuthSession();
2118
        String principals = auth.getPrincipals(user, password);
2119
        out.println(principals);
2120
2121
    } catch (Exception e) {
2122
      out.println("<?xml version=\"1.0\"?>");
2123
      out.println("<error>");
2124
      out.println(e.getMessage());
2125
      out.println("</error>");
2126 1360 tao
    }
2127
2128 731 bojilova
  }
2129
2130 1360 tao
  /**
2131 688 bojilova
   * Handle "getdoctypes" action.
2132 302 bojilova
   * Read all doctypes from db connection in XML format
2133
   */
2134 1360 tao
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
2135 302 bojilova
                                       HttpServletResponse response) {
2136
2137 1360 tao
2138 302 bojilova
    try {
2139
2140 1360 tao
2141 1217 tao
        DBUtil dbutil = new DBUtil();
2142 302 bojilova
        String doctypes = dbutil.readDoctypes();
2143
        out.println(doctypes);
2144
2145
    } catch (Exception e) {
2146
      out.println("<?xml version=\"1.0\"?>");
2147
      out.println("<error>");
2148
      out.println(e.getMessage());
2149
      out.println("</error>");
2150 1360 tao
    }
2151
2152 302 bojilova
  }
2153
2154 1360 tao
  /**
2155 699 bojilova
   * Handle the "getdtdschema" action.
2156
   * Read DTD or Schema file for a given doctype from Metacat catalog system
2157
   */
2158
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2159
                                        HttpServletResponse response) {
2160
2161 1360 tao
2162 699 bojilova
    String doctype = null;
2163
    String[] doctypeArr = (String[])params.get("doctype");
2164
2165
    // get only the first doctype specified in the list of doctypes
2166
    // it could be done for all doctypes in that list
2167
    if (doctypeArr != null) {
2168 1360 tao
        doctype = ((String[])params.get("doctype"))[0];
2169 699 bojilova
    }
2170
2171
    try {
2172
2173 1360 tao
2174 1217 tao
        DBUtil dbutil = new DBUtil();
2175 699 bojilova
        String dtdschema = dbutil.readDTDSchema(doctype);
2176
        out.println(dtdschema);
2177
2178
    } catch (Exception e) {
2179
      out.println("<?xml version=\"1.0\"?>");
2180
      out.println("<error>");
2181
      out.println(e.getMessage());
2182
      out.println("</error>");
2183 1360 tao
    }
2184
2185 699 bojilova
  }
2186
2187 1360 tao
  /**
2188 793 bojilova
   * Handle the "getlastdocid" action.
2189
   * Get the latest docid with rev number from db connection in XML format
2190
   */
2191 1360 tao
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2192 793 bojilova
                                        HttpServletResponse response) {
2193
2194 1217 tao
2195 847 jones
    String scope = ((String[])params.get("scope"))[0];
2196
    if (scope == null) {
2197
        scope = ((String[])params.get("username"))[0];
2198
    }
2199 793 bojilova
2200
    try {
2201
2202 1360 tao
2203 1217 tao
        DBUtil dbutil = new DBUtil();
2204 847 jones
        String lastDocid = dbutil.getMaxDocid(scope);
2205 793 bojilova
        out.println("<?xml version=\"1.0\"?>");
2206
        out.println("<lastDocid>");
2207 847 jones
        out.println("  <scope>" + scope + "</scope>");
2208 793 bojilova
        out.println("  <docid>" + lastDocid + "</docid>");
2209
        out.println("</lastDocid>");
2210
2211
    } catch (Exception e) {
2212
      out.println("<?xml version=\"1.0\"?>");
2213
      out.println("<error>");
2214
      out.println(e.getMessage());
2215
      out.println("</error>");
2216 1217 tao
    }
2217 1360 tao
2218 793 bojilova
  }
2219
2220 1360 tao
  /**
2221
   * Handle documents passed to metacat that are encoded using the
2222 798 jones
   * "multipart/form-data" mime type.  This is typically used for uploading
2223
   * data files which may be binary and large.
2224
   */
2225
  private void handleMultipartForm(HttpServletRequest request,
2226 1360 tao
                                   HttpServletResponse response)
2227 798 jones
  {
2228
    PrintWriter out = null;
2229
    String action = null;
2230
2231
    // Parse the multipart form, and save the parameters in a Hashtable and
2232
    // save the FileParts in a hashtable
2233
2234
    Hashtable params = new Hashtable();
2235
    Hashtable fileList = new Hashtable();
2236 1617 tao
    int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2237
                                                                   .intValue();
2238
    MetaCatUtil.debugMessage("The limit size of data file is: "+sizeLimit, 50);
2239 798 jones
2240
    try {
2241
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
2242 1716 berkley
      MultipartParser mp = new MultipartParser(request, sizeLimit*1024*1024);
2243 798 jones
      Part part;
2244
      while ((part = mp.readNextPart()) != null) {
2245
        String name = part.getName();
2246
2247
        if (part.isParam()) {
2248
          // it's a parameter part
2249
          ParamPart paramPart = (ParamPart) part;
2250
          String value = paramPart.getStringValue();
2251
          params.put(name, value);
2252
          if (name.equals("action")) {
2253
            action = value;
2254
          }
2255
        } else if (part.isFile()) {
2256
          // it's a file part
2257
          FilePart filePart = (FilePart) part;
2258
          fileList.put(name, filePart);
2259
2260
          // Stop once the first file part is found, otherwise going onto the
2261
          // next part prevents access to the file contents.  So...for upload
2262
          // to work, the datafile must be the last part
2263
          break;
2264
        }
2265
      }
2266
    } catch (IOException ioe) {
2267
      try {
2268
        out = response.getWriter();
2269
      } catch (IOException ioe2) {
2270
        System.err.println("Fatal Error: couldn't get response output stream.");
2271
      }
2272
      out.println("<?xml version=\"1.0\"?>");
2273
      out.println("<error>");
2274
      out.println("Error: problem reading multipart data.");
2275
      out.println("</error>");
2276
    }
2277
2278
    // Get the session information
2279
    String username = null;
2280
    String password = null;
2281 802 bojilova
    String[] groupnames = null;
2282 798 jones
    String sess_id = null;
2283
2284 1360 tao
    // be aware of session expiration on every request
2285 798 jones
    HttpSession sess = request.getSession(true);
2286
    if (sess.isNew()) {
2287
      // session expired or has not been stored b/w user requests
2288
      username = "public";
2289
      sess.setAttribute("username", username);
2290
    } else {
2291
      username = (String)sess.getAttribute("username");
2292
      password = (String)sess.getAttribute("password");
2293 802 bojilova
      groupnames = (String[])sess.getAttribute("groupnames");
2294 798 jones
      try {
2295
        sess_id = (String)sess.getId();
2296
      } catch(IllegalStateException ise) {
2297
        System.out.println("error in  handleMultipartForm: this shouldn't " +
2298 1360 tao
                           "happen: the session should be valid: " +
2299 798 jones
                           ise.getMessage());
2300
      }
2301 1360 tao
    }
2302
2303 1292 tao
    // Get the out stream
2304
    try {
2305 798 jones
          out = response.getWriter();
2306
        } catch (IOException ioe2) {
2307 943 tao
          util.debugMessage("Fatal Error: couldn't get response "+
2308 1490 tao
                             "output stream.", 30);
2309 798 jones
        }
2310 1360 tao
2311 1292 tao
    if ( action.equals("upload")) {
2312
      if (username != null &&  !username.equals("public")) {
2313 1360 tao
        handleUploadAction(request, out, params, fileList,
2314 1292 tao
                           username, groupnames);
2315
      } else {
2316 1360 tao
2317 798 jones
        out.println("<?xml version=\"1.0\"?>");
2318
        out.println("<error>");
2319
        out.println("Permission denied for " + action);
2320
        out.println("</error>");
2321
      }
2322
    } else {
2323 1292 tao
      /*try {
2324 798 jones
        out = response.getWriter();
2325
      } catch (IOException ioe2) {
2326
        System.err.println("Fatal Error: couldn't get response output stream.");
2327 1292 tao
      }*/
2328 798 jones
      out.println("<?xml version=\"1.0\"?>");
2329
      out.println("<error>");
2330
      out.println("Error: action not registered.  Please report this error.");
2331
      out.println("</error>");
2332
    }
2333 1217 tao
    out.close();
2334 798 jones
  }
2335
2336 1360 tao
  /**
2337
   * Handle the upload action by saving the attached file to disk and
2338 798 jones
   * registering it in the Metacat db
2339
   */
2340
  private void handleUploadAction(HttpServletRequest request,
2341 1360 tao
                                  PrintWriter out,
2342
                                  Hashtable params, Hashtable fileList,
2343 802 bojilova
                                  String username, String[] groupnames)
2344 798 jones
  {
2345 1292 tao
    //PrintWriter out = null;
2346 1217 tao
    //Connection conn = null;
2347 798 jones
    String action = null;
2348
    String docid = null;
2349 1360 tao
2350 1292 tao
    /*response.setContentType("text/xml");
2351 1360 tao
    try
2352 1041 tao
    {
2353 798 jones
      out = response.getWriter();
2354 1360 tao
    }
2355
    catch (IOException ioe2)
2356 1041 tao
    {
2357 798 jones
      System.err.println("Fatal Error: couldn't get response output stream.");
2358 1292 tao
    }*/
2359 798 jones
2360 1360 tao
    if (params.containsKey("docid"))
2361 1041 tao
    {
2362 798 jones
      docid = (String)params.get("docid");
2363
    }
2364
2365
    // Make sure we have a docid and datafile
2366
    if (docid != null && fileList.containsKey("datafile")) {
2367
2368
      // Get a reference to the file part of the form
2369
      FilePart filePart = (FilePart)fileList.get("datafile");
2370
      String fileName = filePart.getFileName();
2371 1056 tao
      MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2372 798 jones
2373
      // Check if the right file existed in the uploaded data
2374
      if (fileName != null) {
2375 1360 tao
2376
        try
2377 1028 tao
        {
2378 1292 tao
           //MetaCatUtil.debugMessage("Upload datafile " + docid +"...", 10);
2379 1028 tao
           //If document get lock data file grant
2380 1070 tao
           if (DocumentImpl.getDataFileLockGrant(docid))
2381
           {
2382 1064 tao
              // register the file in the database (which generates an exception
2383 1028 tao
              //if the docid is not acceptable or other untoward things happen
2384
              DocumentImpl.registerDocument(fileName, "BIN", docid, username);
2385 1360 tao
2386 1028 tao
              // Save the data file to disk using "docid" as the name
2387
              dataDirectory.mkdirs();
2388
              File newFile = new File(dataDirectory, docid);
2389
              long size = filePart.writeTo(newFile);
2390 1360 tao
2391 1292 tao
              // Force replication this data file
2392
              // To data file, "insert" and update is same
2393 1360 tao
              // The fourth parameter is null. Because it is notification server
2394
              // and this method is in MetaCatServerlet. It is original command,
2395 1292 tao
              // not get force replication info from another metacat
2396
              ForceReplicationHandler frh = new ForceReplicationHandler
2397
                                                (docid, "insert", false, null);
2398 1360 tao
2399 1028 tao
              // set content type and other response header fields first
2400
              out.println("<?xml version=\"1.0\"?>");
2401
              out.println("<success>");
2402 1360 tao
              out.println("<docid>" + docid + "</docid>");
2403
              out.println("<size>" + size + "</size>");
2404 1028 tao
              out.println("</success>");
2405 1070 tao
          }//if
2406 1360 tao
2407 1028 tao
        } //try
2408 1360 tao
        catch (Exception e)
2409 1041 tao
        {
2410 798 jones
          out.println("<?xml version=\"1.0\"?>");
2411
          out.println("<error>");
2412 1360 tao
          out.println(e.getMessage());
2413 798 jones
          out.println("</error>");
2414
        }
2415 1360 tao
2416 1041 tao
      }
2417 1360 tao
      else
2418 1041 tao
      {
2419 798 jones
        // the field did not contain a file
2420
        out.println("<?xml version=\"1.0\"?>");
2421
        out.println("<error>");
2422 1360 tao
        out.println("The uploaded data did not contain a valid file.");
2423 798 jones
        out.println("</error>");
2424
      }
2425 1360 tao
    }
2426
    else
2427 1041 tao
    {
2428 798 jones
      // Error bcse docid missing or file missing
2429
      out.println("<?xml version=\"1.0\"?>");
2430
      out.println("<error>");
2431
      out.println("The uploaded data did not contain a valid docid " +
2432 1360 tao
                  "or valid file.");
2433 798 jones
      out.println("</error>");
2434
    }
2435
  }
2436 1716 berkley
2437 1369 tao
  /*
2438
   * A method to handle set access action
2439
   */
2440
  private void handleSetAccessAction(PrintWriter out,
2441
                                   Hashtable params,
2442
                                   String username)
2443
  {
2444
    String [] docList        = null;
2445
    String [] principalList  = null;
2446
    String [] permissionList = null;
2447
    String [] permTypeList   = null;
2448
    String [] permOrderList  = null;
2449
    String permission = null;
2450
    String permType   = null;
2451
    String permOrder  = null;
2452
    Vector errorList  = new Vector();
2453
    String error      = null;
2454
    Vector successList = new Vector();
2455
    String success    = null;
2456 1716 berkley
2457
2458 1369 tao
    // Get parameters
2459 1716 berkley
    if (params.containsKey("docid"))
2460 1369 tao
    {
2461
      docList = (String[])params.get("docid");
2462
    }
2463
    if (params.containsKey("principal"))
2464
    {
2465 1716 berkley
      principalList = (String[])params.get("principal");
2466 1369 tao
    }
2467
    if (params.containsKey("permission"))
2468
    {
2469
      permissionList = (String[])params.get("permission");
2470 1716 berkley
2471 1369 tao
    }
2472
    if (params.containsKey("permType"))
2473
    {
2474
      permTypeList = (String[])params.get("permType");
2475 1716 berkley
2476 1369 tao
    }
2477
    if (params.containsKey("permOrder"))
2478
    {
2479
      permOrderList = (String[])params.get("permOrder");
2480 1716 berkley
2481 1369 tao
    }
2482 1716 berkley
2483 1369 tao
    // Make sure the parameter is not null
2484
    if (docList == null || principalList == null || permTypeList == null ||
2485
        permissionList == null)
2486
    {
2487
      error = "Please check your parameter list, it should look like: "+
2488
              "?action=setaccess&docid=pipeline.1.1&principal=public" +
2489
              "&permission=read&permType=allow&permOrder=allowFirst";
2490
      errorList.addElement(error);
2491
      outputResponse(successList, errorList, out);
2492
      return;
2493
    }
2494 1716 berkley
2495 1369 tao
    // Only select first element for permission, type and order
2496
    permission = permissionList[0];
2497
    permType = permTypeList[0];
2498
    if (permOrderList != null)
2499
    {
2500
       permOrder = permOrderList[0];
2501
    }
2502 1716 berkley
2503 1369 tao
    // Get package doctype set
2504
    Vector packageSet =MetaCatUtil.getOptionList(
2505
                                    MetaCatUtil.getOption("packagedoctypeset"));
2506
    //debug
2507
    if (packageSet != null)
2508
    {
2509
      for (int i = 0; i<packageSet.size(); i++)
2510
      {
2511 1716 berkley
        MetaCatUtil.debugMessage("doctype in package set: " +
2512 1369 tao
                              (String)packageSet.elementAt(i), 34);
2513
      }
2514
    }//if
2515 1716 berkley
2516 1369 tao
    // handle every accessionNumber
2517
    for (int i=0; i <docList.length; i++)
2518
    {
2519
      String accessionNumber = docList[i];
2520
      String owner = null;
2521
      String publicId = null;
2522
      // Get document owner and public id
2523
      try
2524
      {
2525
        owner = getFieldValueForDoc(accessionNumber, "user_owner");
2526
        publicId = getFieldValueForDoc(accessionNumber, "doctype");
2527
      }//try
2528
      catch (Exception e)
2529
      {
2530
        MetaCatUtil.debugMessage("Error in handleSetAccessAction: " +
2531
                                  e.getMessage(), 30);
2532
        error = "Error in set access control for document - " + accessionNumber+
2533
                 e.getMessage();
2534
        errorList.addElement(error);
2535
        continue;
2536
      }
2537 1716 berkley
      //check if user is the owner. Only owner can do owner
2538 1369 tao
      if (username == null || owner == null || !username.equals(owner))
2539
      {
2540
        error = "User - " + username + " does not have permission to set " +
2541
                "access control for docid - " + accessionNumber;
2542
        errorList.addElement(error);
2543
        continue;
2544
      }
2545 1716 berkley
2546 1369 tao
      // If docid publicid is BIN data file or other beta4, 6 package document
2547
      // we could not do set access control. Because we don't want inconsistent
2548
      // to its access docuemnt
2549
      if (publicId!=null && packageSet!=null && packageSet.contains(publicId))
2550
      {
2551
        error = "Could not set access control to document "+ accessionNumber +
2552
                "because it is in a pakcage and it has a access file for it";
2553
        errorList.addElement(error);
2554
        continue;
2555
      }
2556 1716 berkley
2557 1369 tao
      // for every principle
2558
      for (int j = 0; j<principalList.length; j++)
2559
      {
2560
        String principal = principalList[j];
2561
        try
2562
        {
2563
          //insert permission
2564 1716 berkley
          AccessControlForSingleFile accessControl = new
2565 1369 tao
                           AccessControlForSingleFile(accessionNumber,
2566
                                    principal, permission, permType, permOrder);
2567
          accessControl.insertPermissions();
2568
          success = "Set access control to document "+ accessionNumber +
2569
                    " successfully";
2570
          successList.addElement(success);
2571
        }
2572
        catch (Exception ee)
2573
        {
2574
          MetaCatUtil.debugMessage("Erorr in handleSetAccessAction2: " +
2575
                                   ee.getMessage(), 30);
2576 1716 berkley
          error = "Faild to set access control for document " +
2577 1369 tao
                  accessionNumber + " because " + ee.getMessage();
2578
          errorList.addElement(error);
2579
          continue;
2580
        }
2581
      }//for every principle
2582 1716 berkley
    }//for every document
2583 1369 tao
    outputResponse(successList, errorList, out);
2584
  }//handleSetAccessAction
2585 1716 berkley
2586
2587 1369 tao
  /*
2588
   * A method try to determin a docid's public id, if couldn't find null
2589
   * will be returned.
2590
   */
2591 1716 berkley
  private String getFieldValueForDoc(String accessionNumber, String fieldName)
2592 1369 tao
                                      throws Exception
2593
  {
2594
    if (accessionNumber==null || accessionNumber.equals("") ||fieldName == null
2595
        || fieldName.equals(""))
2596
    {
2597
      throw new Exception("Docid or field name was not specified");
2598
    }
2599 1716 berkley
2600 1369 tao
    PreparedStatement pstmt = null;
2601
    ResultSet rs = null;
2602
    String fieldValue = null;
2603
    String docId = null;
2604
    DBConnection conn = null;
2605
    int serialNumber = -1;
2606 1716 berkley
2607 1369 tao
    // get rid of revision if access number has
2608
    docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2609
    try
2610
    {
2611
      //check out DBConnection
2612
      conn=DBConnectionPool.getDBConnection("MetaCatServlet.getPublicIdForDoc");
2613
      serialNumber=conn.getCheckOutSerialNumber();
2614
      pstmt = conn.prepareStatement(
2615
            "SELECT " + fieldName + " FROM xml_documents " +
2616
            "WHERE docid = ? ");
2617 1716 berkley
2618 1369 tao
      pstmt.setString(1, docId);
2619
      pstmt.execute();
2620
      rs = pstmt.getResultSet();
2621
      boolean hasRow = rs.next();
2622
      int perm = 0;
2623 1716 berkley
      if ( hasRow )
2624 1369 tao
      {
2625
        fieldValue = rs.getString(1);
2626
      }
2627
      else
2628
      {
2629
        throw new Exception("Could not find document: "+accessionNumber);
2630
      }
2631
    }//try
2632
    catch (Exception e)
2633
    {
2634
      MetaCatUtil.debugMessage("Exception in MetacatServlet.getPublicIdForDoc: "
2635
                               + e.getMessage(), 30);
2636
      throw e;
2637
    }
2638
    finally
2639
    {
2640
      try
2641
      {
2642
        rs.close();
2643
        pstmt.close();
2644 1716 berkley
2645 1369 tao
      }
2646
      finally
2647
      {
2648
        DBConnectionPool.returnDBConnection(conn, serialNumber);
2649
      }
2650
    }
2651
    return fieldValue;
2652
  }//getFieldValueForDoc
2653 1716 berkley
2654 1369 tao
  /*
2655
   * A method to output setAccess action result
2656
   */
2657 1716 berkley
  private void outputResponse(Vector successList,
2658 1369 tao
                              Vector errorList,
2659
                              PrintWriter out)
2660
  {
2661
    boolean error = false;
2662
    boolean success = false;
2663
    // Output prolog
2664
    out.println(PROLOG);
2665
    // output success message
2666
    if ( successList != null)
2667
    {
2668
      for (int i = 0; i<successList.size(); i++)
2669
      {
2670
        out.println(SUCCESS);
2671
        out.println((String)successList.elementAt(i));
2672
        out.println(SUCCESSCLOSE);
2673
        success = true;
2674
      }//for
2675
    }//if
2676
    // output error message
2677
    if (errorList != null)
2678
    {
2679
      for (int i = 0; i<errorList.size(); i++)
2680
      {
2681
        out.println(ERROR);
2682
        out.println((String)errorList.elementAt(i));
2683
        out.println(ERRORCLOSE);
2684
        error = true;
2685
      }//for
2686
    }//if
2687 1716 berkley
2688 1369 tao
    // if no error and no success info, send a error that nothing happened
2689
    if( !error && !success)
2690
    {
2691
      out.println(ERROR);
2692
      out.println("Nothing happend for setaccess action");
2693
      out.println(ERRORCLOSE);
2694
    }
2695 1716 berkley
2696 1369 tao
  }//outputResponse
2697 46 jones
}