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 731 bojilova
 * abstractpath -- XPath in metadata document to read from<br>
97 688 bojilova
 * action=getaccesscontrol -- retrieve acl info for Metacat document<br>
98
 * action=getdoctypes -- retrieve all doctypes (publicID)<br>
99 699 bojilova
 * action=getdtdschema -- retrieve a DTD or Schema file<br>
100 688 bojilova
 * action=getdataguide -- retrieve a Data Guide<br>
101 725 bojilova
 * action=getprincipals -- retrieve a list of principals in XML<br>
102 205 jones
 * datadoc -- data document name (id)<br>
103
 * <p>
104 1360 tao
 * The particular combination of parameters that are valid for each
105 205 jones
 * particular action value is quite specific.  This documentation
106
 * will be reorganized to reflect this information.
107 46 jones
 */
108
public class MetaCatServlet extends HttpServlet {
109
110 370 berkley
  private ServletConfig config = null;
111
  private ServletContext context = null;
112
  private String resultStyleURL = null;
113
  private String xmlcatalogfile = null;
114
  private String saxparser = null;
115 1360 tao
  private String datafilepath = null;
116 798 jones
  private File dataDirectory = null;
117 1360 tao
  private String servletpath = null;
118
  private String htmlpath = null;
119 380 jones
  private PropertyResourceBundle options = null;
120
  private MetaCatUtil util = null;
121 1217 tao
  private DBConnectionPool connPool = null;
122 1723 berkley
  private Hashtable sessionHash = new Hashtable();
123 1369 tao
  private static final String PROLOG = "<?xml version=\"1.0\"?>";
124
  private static final String SUCCESS = "<success>";
125
  private static final String SUCCESSCLOSE = "</success>";
126
  private static final String ERROR = "<error>";
127
  private static final String ERRORCLOSE = "</error>";
128 1466 tao
  public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
129
  public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
130 1610 tao
  public static final String EML2KEYWORD =":eml";
131 1951 jones
  private static final String CONFIG_DIR  = "WEB-INF";
132
  private static final String CONFIG_NAME = "metacat.properties";
133 380 jones
134 50 jones
  /**
135
   * Initialize the servlet by creating appropriate database connections
136
   */
137 46 jones
  public void init( ServletConfig config ) throws ServletException {
138
    try {
139
      super.init( config );
140
      this.config = config;
141 1360 tao
      this.context = config.getServletContext();
142 184 jones
      System.out.println("MetaCatServlet Initialize");
143 82 jones
144 1951 jones
      // Initialize the properties file for our options
145
      String dirPath = context.getRealPath(CONFIG_DIR);
146
      File propertyFile = new File(dirPath,CONFIG_NAME);
147
      Options options = null;
148
      try {
149
          options = Options.initialize(propertyFile);
150
          MetaCatUtil.debugMessage("Options configured: " +
151
            options.getOption("configured"), 20);
152
      } catch (IOException ioe) {
153
        MetaCatUtil.debugMessage("Error in loading options: "
154
           +ioe.getMessage(), 20);
155
      }
156
157 184 jones
      util = new MetaCatUtil();
158 1360 tao
159 1217 tao
      //initial DBConnection pool
160
      connPool = DBConnectionPool.getInstance();
161 184 jones
162 83 jones
      // Get the configuration file information
163 184 jones
      resultStyleURL = util.getOption("resultStyleURL");
164
      xmlcatalogfile = util.getOption("xmlcatalogfile");
165
      saxparser = util.getOption("saxparser");
166 798 jones
      datafilepath = util.getOption("datafilepath");
167
      dataDirectory = new File(datafilepath);
168 360 bojilova
      servletpath = util.getOption("servletpath");
169
      htmlpath = util.getOption("htmlpath");
170 598 bojilova
171 1217 tao
172 46 jones
    } catch ( ServletException ex ) {
173
      throw ex;
174 1217 tao
    } catch (SQLException e) {
175
      MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
176
                                          +e.getMessage(), 20);
177 46 jones
    }
178
  }
179
180 320 bojilova
  /**
181
   * Close all db connections from the pool
182
   */
183
  public void destroy() {
184 1360 tao
      // Close all db connection
185
      System.out.println("Destroying MetacatServlet");
186 1217 tao
      connPool.release();
187 320 bojilova
  }
188
189 50 jones
  /** Handle "GET" method requests from HTTP clients */
190 46 jones
  public void doGet (HttpServletRequest request, HttpServletResponse response)
191
    throws ServletException, IOException {
192
193 48 jones
    // Process the data and send back the response
194 59 jones
    handleGetOrPost(request, response);
195 48 jones
  }
196
197 50 jones
  /** Handle "POST" method requests from HTTP clients */
198 48 jones
  public void doPost( HttpServletRequest request, HttpServletResponse response)
199
    throws ServletException, IOException {
200
201
    // Process the data and send back the response
202 59 jones
    handleGetOrPost(request, response);
203 48 jones
  }
204
205 49 jones
  /**
206 50 jones
   * Control servlet response depending on the action parameter specified
207 49 jones
   */
208 1360 tao
  private void handleGetOrPost(HttpServletRequest request,
209
                               HttpServletResponse response)
210
                               throws ServletException, IOException
211 798 jones
  {
212 48 jones
213 309 bojilova
    if ( util == null ) {
214 1360 tao
        util = new MetaCatUtil();
215 309 bojilova
    }
216 1221 tao
    /*MetaCatUtil.debugMessage("Connection pool size: "
217 1217 tao
                                     +connPool.getSizeOfDBConnectionPool(),10);
218
    MetaCatUtil.debugMessage("Free DBConnection number: "
219 1221 tao
                                  +connPool.getFreeDBConnectionNumber(), 10);*/
220 1360 tao
    //If all DBConnection in the pool are free and DBConnection pool
221
    //size is greater than initial value, shrink the connection pool
222 1221 tao
    //size to initial value
223
    DBConnectionPool.shrinkDBConnectionPoolSize();
224 1360 tao
225 1217 tao
    //Debug message to print out the method which have a busy DBConnection
226
    connPool.printMethodNameHavingBusyDBConnection();
227 1360 tao
228 800 jones
    String ctype = request.getContentType();
229
    if (ctype != null && ctype.startsWith("multipart/form-data")) {
230 798 jones
      handleMultipartForm(request, response);
231
    } else {
232 1360 tao
233
234 798 jones
      String name = null;
235
      String[] value = null;
236
      String[] docid = new String[3];
237
      Hashtable params = new Hashtable();
238
      Enumeration paramlist = request.getParameterNames();
239 1360 tao
240
241 798 jones
      while (paramlist.hasMoreElements()) {
242 1360 tao
243 798 jones
        name = (String)paramlist.nextElement();
244
        value = request.getParameterValues(name);
245 1360 tao
246 798 jones
        // Decode the docid and mouse click information
247
        if (name.endsWith(".y")) {
248
          docid[0] = name.substring(0,name.length()-2);
249
          params.put("docid", docid);
250
          name = "ypos";
251 648 berkley
        }
252 798 jones
        if (name.endsWith(".x")) {
253
          name = "xpos";
254 1360 tao
        }
255
256
        params.put(name,value);
257
      }
258
259
260 1217 tao
      //handle param is emptpy
261
      if (params.isEmpty() || params == null)
262
      {
263
        return;
264
      }
265 1716 berkley
266 798 jones
      //if the user clicked on the input images, decode which image
267
      //was clicked then set the action.
268 1360 tao
      String action = ((String[])params.get("action"))[0];
269 1217 tao
      util.debugMessage("Line 230: Action is: " + action, 1);
270 1360 tao
271 798 jones
      // This block handles session management for the servlet
272
      // by looking up the current session information for all actions
273
      // other than "login" and "logout"
274
      String username = null;
275
      String password = null;
276 802 bojilova
      String[] groupnames = null;
277 798 jones
      String sess_id = null;
278 1360 tao
279 798 jones
      // handle login action
280
      if (action.equals("login")) {
281 1217 tao
        PrintWriter out = response.getWriter();
282
        handleLoginAction(out, params, request, response);
283
        out.close();
284 1360 tao
285
      // handle logout action
286 798 jones
      } else if (action.equals("logout")) {
287 1217 tao
        PrintWriter out = response.getWriter();
288
        handleLogoutAction(out, params, request, response);
289
        out.close();
290 1360 tao
291 1221 tao
      // handle shrink DBConnection request
292
      } else if (action.equals("shrink")) {
293
        PrintWriter out = response.getWriter();
294
        boolean success = false;
295 1360 tao
        //If all DBConnection in the pool are free and DBConnection pool
296
        //size is greater than initial value, shrink the connection pool
297 1221 tao
        //size to initial value
298
        success = DBConnectionPool.shrinkConnectionPoolSize();
299
        if (success)
300
        {
301
          //if successfully shrink the pool size to initial value
302
          out.println("DBConnection Pool shrink successfully");
303
        }//if
304
        else
305
        {
306
          out.println("DBConnection pool couldn't shrink successfully");
307
        }
308
       //close out put
309
        out.close();
310 1360 tao
311
      // aware of session expiration on every request
312 1723 berkley
      }
313
      else
314
      {
315 798 jones
        HttpSession sess = request.getSession(true);
316 1723 berkley
        if (sess.isNew() && !params.containsKey("sessionid")) {
317 798 jones
          // session expired or has not been stored b/w user requests
318 2045 tao
          MetaCatUtil.debugMessage("in session is new or no sessionid", 40);
319 798 jones
          username = "public";
320
          sess.setAttribute("username", username);
321 1723 berkley
        }
322
        else
323
        {
324 2045 tao
          MetaCatUtil.debugMessage("in session is not new or " +
325
                                    " has sessionid parameter", 40);
326 1723 berkley
          try
327
          {
328 1716 berkley
            if(params.containsKey("sessionid"))
329
            {
330 1723 berkley
              sess_id = ((String[])params.get("sessionid"))[0];
331 2045 tao
              MetaCatUtil.debugMessage("in has sessionid " + sess_id, 40);
332 1723 berkley
              if(sessionHash.containsKey(sess_id))
333
              {
334 2045 tao
                MetaCatUtil.debugMessage("find the id " + sess_id +
335
                                         " in hash table", 40);
336 1723 berkley
                sess = (HttpSession)sessionHash.get(sess_id);
337
              }
338 1716 berkley
            }
339
            else
340
            {
341 2045 tao
              // we already store the session in login, so we don't need here
342
              /*MetaCatUtil.debugMessage("in no sessionid parameter ", 40);
343 1716 berkley
              sess_id = (String)sess.getId();
344 2045 tao
              MetaCatUtil.debugMessage("storing the session id "+ sess_id +
345
                  " which has username " + sess.getAttribute("username") +
346
                 " into session hash in handleGetOrPost method", 35);
347
              sessionHash.put(sess_id, sess);*/
348 1716 berkley
            }
349 1723 berkley
          }
350
          catch(IllegalStateException ise)
351
          {
352 798 jones
            System.out.println("error in handleGetOrPost: this shouldn't " +
353 1360 tao
                               "happen: the session should be valid: " +
354 798 jones
                               ise.getMessage());
355
          }
356 1723 berkley
357
          username = (String)sess.getAttribute("username");
358 2045 tao
          MetaCatUtil.debugMessage("The user name from session is: "+
359
                                   username, 20);
360 1723 berkley
          password = (String)sess.getAttribute("password");
361
          groupnames = (String[])sess.getAttribute("groupnames");
362 1360 tao
        }
363 1906 tao
364 2045 tao
        //make user user username should be public
365
        if (username == null || (username.trim().equals("")))
366
        {
367
          username = "public";
368
        }
369
        MetaCatUtil.debugMessage("The user is : "+ username, 5);
370 1906 tao
      }
371 947 tao
       // Now that we know the session is valid, we can delegate the request
372 798 jones
      // to a particular action handler
373
      if(action.equals("query")) {
374 1217 tao
        PrintWriter out = response.getWriter();
375 1716 berkley
        handleQuery(out,params,response,username,groupnames,sess_id);
376 1217 tao
        out.close();
377 798 jones
      } else if(action.equals("squery")) {
378 1217 tao
        PrintWriter out = response.getWriter();
379 798 jones
        if(params.containsKey("query")) {
380 1716 berkley
         handleSQuery(out, params,response,username,groupnames,sess_id);
381 1217 tao
         out.close();
382 798 jones
        } else {
383
          out.println("Illegal action squery without \"query\" parameter");
384 1217 tao
          out.close();
385 798 jones
        }
386 943 tao
      } else if (action.equals("export")) {
387 1360 tao
388 1292 tao
        handleExportAction(params, response, username, groupnames, password);
389 798 jones
      } else if (action.equals("read")) {
390 1292 tao
        handleReadAction(params, response, username,password, groupnames);
391 1483 tao
      } else if (action.equals("readinlinedata")) {
392 1716 berkley
        handleReadInlineDataAction(params, response, username,
393 1483 tao
                                   password, groupnames);
394 798 jones
      } else if (action.equals("insert") || action.equals("update")) {
395 458 berkley
        PrintWriter out = response.getWriter();
396 1444 tao
        if ( (username != null) &&  !username.equals("public") ) {
397 1377 tao
          handleInsertOrUpdateAction(out,params,username,groupnames);
398 1444 tao
        } else {
399 1556 tao
          out.println("Permission denied for user "+username +" " + action);
400
       }
401 1217 tao
        out.close();
402 798 jones
      } else if (action.equals("delete")) {
403
        PrintWriter out = response.getWriter();
404
        if ( (username != null) &&  !username.equals("public") ) {
405 802 bojilova
          handleDeleteAction(out, params, response, username, groupnames);
406 1360 tao
        } else {
407 798 jones
          out.println("Permission denied for " + action);
408 1217 tao
        }
409
        out.close();
410 798 jones
      } else if (action.equals("validate")) {
411
        PrintWriter out = response.getWriter();
412 1342 tao
        handleValidateAction(out, params);
413 1217 tao
        out.close();
414 1369 tao
      } else if (action.equals("setaccess")) {
415
         PrintWriter out = response.getWriter();
416
         handleSetAccessAction(out, params, username);
417
        out.close();
418 798 jones
      } else if (action.equals("getaccesscontrol")) {
419
        PrintWriter out = response.getWriter();
420 802 bojilova
        handleGetAccessControlAction(out,params,response,username,groupnames);
421 1217 tao
        out.close();
422 798 jones
      } else if (action.equals("getprincipals")) {
423
        PrintWriter out = response.getWriter();
424 1217 tao
        handleGetPrincipalsAction(out, username, password);
425
        out.close();
426 798 jones
      } else if (action.equals("getdoctypes")) {
427
        PrintWriter out = response.getWriter();
428 1217 tao
        handleGetDoctypesAction(out, params, response);
429
        out.close();
430 798 jones
      } else if (action.equals("getdtdschema")) {
431
        PrintWriter out = response.getWriter();
432 1217 tao
        handleGetDTDSchemaAction(out, params, response);
433
        out.close();
434 798 jones
      } else if (action.equals("getdataguide")) {
435
        PrintWriter out = response.getWriter();
436 1217 tao
        handleGetDataGuideAction(out, params, response);
437
        out.close();
438 798 jones
      } else if (action.equals("getlastdocid")) {
439
        PrintWriter out = response.getWriter();
440 1217 tao
        handleGetMaxDocidAction(out, params, response);
441
        out.close();
442 1292 tao
      } else if (action.equals("getrevisionanddoctype")) {
443
        PrintWriter out = response.getWriter();
444
        handleGetRevisionAndDocTypeAction(out, params);
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 (params.containsKey("abstractpath")) {
1142
        abstrpath = ((String[])params.get("abstractpath"))[0];
1143 738 bojilova
        if ( !abstrpath.equals("") && (abstrpath != null) ) {
1144
          viewAbstract(response, abstrpath, docs[0]);
1145
          return;
1146
        }
1147 437 berkley
      }
1148 731 bojilova
      if ( (docs.length > 1) || qformat.equals("zip") ) {
1149
        zip = true;
1150
        out = response.getOutputStream();
1151
        response.setContentType("application/zip"); //MIME type
1152
        zout = new ZipOutputStream(out);
1153
      }
1154
      // go through the list of docs to read
1155
      for (int i=0; i < docs.length; i++ ) {
1156
        try {
1157
1158
          URL murl = new URL(docs[i]);
1159
          Hashtable murlQueryStr = util.parseQuery(murl.getQuery());
1160 1360 tao
          // case docid="http://.../?docid=aaa"
1161 731 bojilova
          // or docid="metacat://.../?docid=bbb"
1162
          if (murlQueryStr.containsKey("docid")) {
1163
            // get only docid, eliminate the rest
1164
            docid = (String)murlQueryStr.get("docid");
1165
            if ( zip ) {
1166 947 tao
              addDocToZip(docid, zout, user, groups);
1167 731 bojilova
            } else {
1168
              readFromMetacat(response, docid, qformat, abstrpath,
1169 1665 tao
                              user, groups, zip, zout, withInlineData, params);
1170 731 bojilova
            }
1171
1172
          // case docid="http://.../filename"
1173
          } else {
1174
            docid = docs[i];
1175
            if ( zip ) {
1176 947 tao
              addDocToZip(docid, zout, user, groups);
1177 731 bojilova
            } else {
1178
              readFromURLConnection(response, docid);
1179
            }
1180
          }
1181
1182
        // case docid="ccc"
1183
        } catch (MalformedURLException mue) {
1184
          docid = docs[i];
1185
          if ( zip ) {
1186 947 tao
            addDocToZip(docid, zout, user, groups);
1187 731 bojilova
          } else {
1188
            readFromMetacat(response, docid, qformat, abstrpath,
1189 1665 tao
                            user, groups, zip, zout, withInlineData, params);
1190 731 bojilova
          }
1191
        }
1192 1360 tao
1193 731 bojilova
      } /* end for */
1194 1360 tao
1195 731 bojilova
      if ( zip ) {
1196
        zout.finish(); //terminate the zip file
1197
        zout.close();  //close the zip stream
1198
      }
1199 1360 tao
1200
1201 1292 tao
    }
1202
    // To handle doc not found exception
1203
    catch (McdbDocNotFoundException notFoundE)
1204
    {
1205
      // the docid which didn't be found
1206
      String notFoundDocId = notFoundE.getUnfoundDocId();
1207
      String notFoundRevision = notFoundE.getUnfoundRevision();
1208
      MetaCatUtil.debugMessage("Missed id: "+ notFoundDocId, 30);
1209
      MetaCatUtil.debugMessage("Missed rev: "+ notFoundRevision, 30);
1210
      try
1211
      {
1212
        // read docid from remote server
1213
        readFromRemoteMetaCat(response, notFoundDocId, notFoundRevision,
1214
                                              user, passWord, out, zip, zout);
1215
        // Close zout outputstream
1216
        if ( zout != null)
1217
        {
1218
          zout.close();
1219
        }
1220
        // close output stream
1221
        if (out != null)
1222
        {
1223
          out.close();
1224
        }
1225 1360 tao
1226 1292 tao
      }//try
1227
      catch ( Exception exc)
1228
      {
1229
        MetaCatUtil.debugMessage("Erorr in MetacatServlet.hanldReadAction: "+
1230
                                      exc.getMessage(), 30);
1231
        try
1232
        {
1233 1360 tao
          if (out != null)
1234 1292 tao
          {
1235
            response.setContentType("text/xml");
1236
            // Send back error message by printWriter
1237
            pw = new PrintWriter(out);
1238
            pw.println("<?xml version=\"1.0\"?>");
1239
            pw.println("<error>");
1240
            pw.println(notFoundE.getMessage());
1241
            pw.println("</error>");
1242
            pw.close();
1243
            out.close();
1244 1360 tao
1245 1292 tao
          }
1246
          else
1247
          {
1248
           response.setContentType("text/xml"); //MIME type
1249
           // Send back error message if out = null
1250
           if (pw == null)
1251
           {
1252
             // If pw is null, open the respnose
1253
            pw = response.getWriter();
1254
           }
1255
           pw.println("<?xml version=\"1.0\"?>");
1256
           pw.println("<error>");
1257
           pw.println(notFoundE.getMessage());
1258
           pw.println("</error>");
1259
           pw.close();
1260
        }
1261
        // close zout
1262 1360 tao
        if ( zout != null )
1263
        {
1264
          zout.close();
1265 1292 tao
        }
1266
        }//try
1267
        catch (IOException ie)
1268
        {
1269
          MetaCatUtil.debugMessage("Problem with the servlet output " +
1270
                           "in MetacatServlet.handleReadAction: " +
1271
                           ie.getMessage(), 30);
1272
        }//cathch
1273
      }//catch
1274
    }// catch McdbDocNotFoundException
1275 1360 tao
    catch (Exception e)
1276 1292 tao
    {
1277 731 bojilova
      try {
1278 1360 tao
1279 845 jones
        if (out != null) {
1280 1292 tao
            response.setContentType("text/xml"); //MIME type
1281
            pw = new PrintWriter(out);
1282 845 jones
            pw.println("<?xml version=\"1.0\"?>");
1283
            pw.println("<error>");
1284
            pw.println(e.getMessage());
1285
            pw.println("</error>");
1286
            pw.close();
1287 1292 tao
            out.close();
1288 845 jones
        }
1289 1292 tao
        else
1290
        {
1291
           response.setContentType("text/xml"); //MIME type
1292
           // Send back error message if out = null
1293
           if ( pw == null)
1294
           {
1295
            pw = response.getWriter();
1296
           }
1297
           pw.println("<?xml version=\"1.0\"?>");
1298
           pw.println("<error>");
1299
           pw.println(e.getMessage());
1300
           pw.println("</error>");
1301
           pw.close();
1302 1360 tao
1303 1292 tao
        }
1304
        // Close zip output stream
1305 731 bojilova
        if ( zout != null ) { zout.close(); }
1306 1360 tao
1307 731 bojilova
      } catch (IOException ioe) {
1308 1292 tao
        MetaCatUtil.debugMessage("Problem with the servlet output " +
1309 731 bojilova
                           "in MetacatServlet.handleReadAction: " +
1310 1292 tao
                           ioe.getMessage(), 30);
1311 731 bojilova
        ioe.printStackTrace(System.out);
1312 1360 tao
1313 731 bojilova
      }
1314
1315 1482 tao
      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadAction: " +
1316
                               e.getMessage(), 30);
1317
      //e.printStackTrace(System.out);
1318 437 berkley
    }
1319 1360 tao
1320 437 berkley
  }
1321 1360 tao
1322 731 bojilova
  // read metadata or data from Metacat
1323
  private void readFromMetacat(HttpServletResponse response, String docid,
1324
                               String qformat, String abstrpath, String user,
1325 1716 berkley
                               String[] groups, boolean zip,
1326 1665 tao
                               ZipOutputStream zout, boolean withInlineData,
1327
                               Hashtable params)
1328 1360 tao
               throws ClassNotFoundException, IOException, SQLException,
1329 731 bojilova
                      McdbException, Exception
1330 453 berkley
  {
1331 1360 tao
1332 731 bojilova
    try {
1333 1360 tao
1334
1335 1217 tao
      DocumentImpl doc = new DocumentImpl(docid);
1336 1360 tao
1337 947 tao
      //check the permission for read
1338 1217 tao
      if (!doc.hasReadPermission(user, groups, docid))
1339 947 tao
      {
1340
        Exception e = new Exception("User " + user + " does not have permission"
1341
                       +" to read the document with the docid " + docid);
1342 1360 tao
1343 947 tao
        throw e;
1344
      }
1345 1360 tao
1346 731 bojilova
      if ( doc.getRootNodeID() == 0 ) {
1347
        // this is data file
1348
        String filepath = util.getOption("datafilepath");
1349
        if(!filepath.endsWith("/")) {
1350
          filepath += "/";
1351
        }
1352 1292 tao
        String filename = filepath + docid;
1353
        FileInputStream fin = null;
1354
        fin = new FileInputStream(filename);
1355 1360 tao
1356 1292 tao
        //MIME type
1357 731 bojilova
        String contentType = getServletContext().getMimeType(filename);
1358 1716 berkley
        if (contentType == null)
1359 1556 tao
        {
1360
          ContentTypeProvider provider = new ContentTypeProvider(docid);
1361
          contentType = provider.getContentType();
1362
          MetaCatUtil.debugMessage("Final contenttype is: "+ contentType, 30);
1363 453 berkley
        }
1364 1716 berkley
1365 731 bojilova
        response.setContentType(contentType);
1366 733 bojilova
        // if we decide to use "application/octet-stream" for all data returns
1367
        // response.setContentType("application/octet-stream");
1368 1360 tao
1369 731 bojilova
        try {
1370 1360 tao
1371
          ServletOutputStream out = response.getOutputStream();
1372 731 bojilova
          byte[] buf = new byte[4 * 1024]; // 4K buffer
1373
          int b = fin.read(buf);
1374
          while (b != -1) {
1375
            out.write(buf, 0, b);
1376
            b = fin.read(buf);
1377 453 berkley
          }
1378 731 bojilova
        } finally {
1379
          if (fin != null) fin.close();
1380 453 berkley
        }
1381 731 bojilova
1382
      } else {
1383
        // this is metadata doc
1384 1360 tao
        if ( qformat.equals("xml") ) {
1385
1386 832 jones
          // set content type first
1387
          response.setContentType("text/xml");   //MIME type
1388
          PrintWriter out = response.getWriter();
1389 1482 tao
          doc.toXml(out, user, groups, withInlineData);
1390 832 jones
        } else {
1391 731 bojilova
          response.setContentType("text/html");  //MIME type
1392
          PrintWriter out = response.getWriter();
1393 1360 tao
1394 731 bojilova
          // Look up the document type
1395
          String doctype = doc.getDoctype();
1396
          // Transform the document to the new doctype
1397 1217 tao
          DBTransform dbt = new DBTransform();
1398 1482 tao
          dbt.transformXMLDocument(doc.toString(user, groups, withInlineData),
1399 1716 berkley
                                   doctype,"-//W3C//HTML//EN",
1400 1665 tao
                                   qformat, out, params);
1401 731 bojilova
        }
1402 1360 tao
1403 453 berkley
      }
1404 1292 tao
    }
1405 1360 tao
    catch (Exception except)
1406 1292 tao
    {
1407 1217 tao
      throw except;
1408 1360 tao
1409 731 bojilova
    }
1410 1360 tao
1411 731 bojilova
  }
1412 1360 tao
1413 731 bojilova
  // read data from URLConnection
1414
  private void readFromURLConnection(HttpServletResponse response, String docid)
1415
               throws IOException, MalformedURLException
1416 566 jones
  {
1417 1360 tao
    ServletOutputStream out = response.getOutputStream();
1418 731 bojilova
    String contentType = getServletContext().getMimeType(docid); //MIME type
1419
    if (contentType == null) {
1420
      if (docid.endsWith(".xml")) {
1421
        contentType="text/xml";
1422
      } else if (docid.endsWith(".css")) {
1423
        contentType="text/css";
1424
      } else if (docid.endsWith(".dtd")) {
1425
        contentType="text/plain";
1426
      } else if (docid.endsWith(".xsd")) {
1427 733 bojilova
        contentType="text/xml";
1428 731 bojilova
      } else if (docid.endsWith("/")) {
1429 733 bojilova
        contentType="text/html";
1430 731 bojilova
      } else {
1431 733 bojilova
        File f = new File(docid);
1432
        if ( f.isDirectory() ) {
1433
          contentType="text/html";
1434
        } else {
1435
          contentType="application/octet-stream";
1436
        }
1437 731 bojilova
      }
1438
    }
1439
    response.setContentType(contentType);
1440 733 bojilova
    // if we decide to use "application/octet-stream" for all data returns
1441
    // response.setContentType("application/octet-stream");
1442 731 bojilova
1443
    // this is http url
1444
    URL url = new URL(docid);
1445
    BufferedInputStream bis = null;
1446 566 jones
    try {
1447 731 bojilova
      bis = new BufferedInputStream(url.openStream());
1448
      byte[] buf = new byte[4 * 1024]; // 4K buffer
1449
      int b = bis.read(buf);
1450
      while (b != -1) {
1451
        out.write(buf, 0, b);
1452
        b = bis.read(buf);
1453 636 berkley
      }
1454 731 bojilova
    } finally {
1455
      if (bis != null) bis.close();
1456 566 jones
    }
1457 1360 tao
1458 566 jones
  }
1459 1360 tao
1460 731 bojilova
  // read file/doc and write to ZipOutputStream
1461 1360 tao
  private void addDocToZip(String docid, ZipOutputStream zout,
1462 947 tao
                              String user, String[] groups)
1463 1360 tao
               throws ClassNotFoundException, IOException, SQLException,
1464 731 bojilova
                      McdbException, Exception
1465 636 berkley
  {
1466 731 bojilova
    byte[] bytestring = null;
1467
    ZipEntry zentry = null;
1468
1469
    try {
1470
      URL url = new URL(docid);
1471
1472
      // this http url; read from URLConnection; add to zip
1473
      zentry = new ZipEntry(docid);
1474
      zout.putNextEntry(zentry);
1475
      BufferedInputStream bis = null;
1476
      try {
1477
        bis = new BufferedInputStream(url.openStream());
1478
        byte[] buf = new byte[4 * 1024]; // 4K buffer
1479
        int b = bis.read(buf);
1480
        while(b != -1) {
1481
          zout.write(buf, 0, b);
1482
          b = bis.read(buf);
1483
        }
1484
      } finally {
1485
        if (bis != null) bis.close();
1486 636 berkley
      }
1487 731 bojilova
      zout.closeEntry();
1488
1489
    } catch (MalformedURLException mue) {
1490 1360 tao
1491 731 bojilova
      // this is metacat doc (data file or metadata doc)
1492 1360 tao
1493 731 bojilova
      try {
1494 1360 tao
1495 1217 tao
        DocumentImpl doc = new DocumentImpl(docid);
1496 1360 tao
1497 947 tao
        //check the permission for read
1498 1217 tao
        if (!doc.hasReadPermission(user, groups, docid))
1499 947 tao
        {
1500
          Exception e = new Exception("User " + user + " does not have "
1501
                    +"permission to read the document with the docid " + docid);
1502 1360 tao
1503 947 tao
          throw e;
1504 1360 tao
        }
1505
1506 731 bojilova
        if ( doc.getRootNodeID() == 0 ) {
1507
          // this is data file; add file to zip
1508
          String filepath = util.getOption("datafilepath");
1509
          if(!filepath.endsWith("/")) {
1510
            filepath += "/";
1511
          }
1512 1292 tao
          String filename = filepath + docid;
1513 731 bojilova
          FileInputStream fin = null;
1514 1292 tao
          fin = new FileInputStream(filename);
1515 731 bojilova
          try {
1516 1360 tao
1517 1292 tao
            zentry = new ZipEntry(docid);
1518
            zout.putNextEntry(zentry);
1519 731 bojilova
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1520
            int b = fin.read(buf);
1521
            while (b != -1) {
1522
              zout.write(buf, 0, b);
1523
              b = fin.read(buf);
1524
            }
1525
          } finally {
1526
            if (fin != null) fin.close();
1527
          }
1528
          zout.closeEntry();
1529
1530
        } else {
1531
          // this is metadata doc; add doc to zip
1532
          bytestring = doc.toString().getBytes();
1533
          zentry = new ZipEntry(docid + ".xml");
1534
          zentry.setSize(bytestring.length);
1535
          zout.putNextEntry(zentry);
1536
          zout.write(bytestring, 0, bytestring.length);
1537
          zout.closeEntry();
1538 636 berkley
        }
1539 1217 tao
      } catch (Exception except) {
1540
        throw except;
1541 1360 tao
1542 636 berkley
      }
1543 1360 tao
1544 636 berkley
    }
1545 1360 tao
1546 636 berkley
  }
1547 1360 tao
1548 731 bojilova
  // view abstract within document
1549
  private void viewAbstract(HttpServletResponse response,
1550
                            String abstractpath, String docid)
1551
               throws ClassNotFoundException, IOException, SQLException,
1552
                      McdbException, Exception
1553
  {
1554 1360 tao
1555 1217 tao
    PrintWriter out =null;
1556 102 jones
    try {
1557 1360 tao
1558 731 bojilova
      response.setContentType("text/html");  //MIME type
1559 1217 tao
      out = response.getWriter();
1560
      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid);
1561 731 bojilova
      out.println("<html><head><title>Abstract</title></head>");
1562
      out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
1563
      for (int i=0; i<abstracts.length; i++) {
1564
        out.println("<p>" + (String)abstracts[i] + "</p>");
1565
      }
1566
      out.println("</body></html>");
1567 85 jones
1568 1217 tao
    } catch (Exception e) {
1569
       out.println("<?xml version=\"1.0\"?>");
1570
       out.println("<error>");
1571
       out.println(e.getMessage());
1572
       out.println("</error>");
1573 1360 tao
1574
1575 731 bojilova
    }
1576 49 jones
  }
1577 1292 tao
  /**
1578
   * If metacat couldn't find a data file or document locally, it will read this
1579
   * docid from its home server. This is for the replication feature
1580
   */
1581 1360 tao
  private void readFromRemoteMetaCat(HttpServletResponse response, String docid,
1582
                     String rev, String user, String password,
1583 1292 tao
                     ServletOutputStream out, boolean zip, ZipOutputStream zout)
1584
                        throws Exception
1585
 {
1586
   // Create a object of RemoteDocument, "" is for zipEntryPath
1587 1360 tao
   RemoteDocument remoteDoc =
1588 1292 tao
                        new RemoteDocument (docid, rev,user, password, "");
1589 1293 tao
   String docType = remoteDoc.getDocType();
1590
   // Only read data file
1591
   if (docType.equals("BIN"))
1592 1292 tao
   {
1593 1293 tao
    // If it is zip format
1594
    if (zip)
1595
    {
1596
      remoteDoc.readDocumentFromRemoteServerByZip(zout);
1597 1360 tao
    }//if
1598 1293 tao
    else
1599
    {
1600
      if (out == null)
1601
      {
1602
        out = response.getOutputStream();
1603
      }//if
1604
      response.setContentType("application/octet-stream");
1605
      remoteDoc.readDocumentFromRemoteServer(out);
1606
    }//else (not zip)
1607 1360 tao
   }//if doctype=bin
1608 1292 tao
   else
1609
   {
1610 1293 tao
     throw new Exception("Docid: "+docid+"."+rev+" couldn't find");
1611 1360 tao
   }//else
1612 1292 tao
 }//readFromRemoteMetaCat
1613 1360 tao
1614 731 bojilova
  // END OF READ SECTION
1615 1716 berkley
1616
1617
1618 731 bojilova
  // INSERT/UPDATE SECTION
1619 1360 tao
  /**
1620
   * Handle the database putdocument request and write an XML document
1621 55 jones
   * to the database connection
1622
   */
1623 1360 tao
  private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params,
1624 1377 tao
               String user, String[] groups) {
1625 59 jones
1626 1217 tao
    DBConnection dbConn = null;
1627
    int serialNumber = -1;
1628 309 bojilova
1629 204 jones
    try {
1630
      // Get the document indicated
1631
      String[] doctext = (String[])params.get("doctext");
1632 557 bojilova
1633 680 bojilova
      String pub = null;
1634
      if (params.containsKey("public")) {
1635
        pub = ((String[])params.get("public"))[0];
1636 557 bojilova
      }
1637 680 bojilova
1638 598 bojilova
      StringReader dtd = null;
1639 680 bojilova
      if (params.containsKey("dtdtext")) {
1640 598 bojilova
        String[] dtdtext = (String[])params.get("dtdtext");
1641
        try {
1642 619 bojilova
          if ( !dtdtext[0].equals("") ) {
1643
            dtd = new StringReader(dtdtext[0]);
1644
          }
1645 598 bojilova
        } catch (NullPointerException npe) {}
1646
      }
1647 1360 tao
1648 1760 tao
      StringReader xml = new StringReader(doctext[0]);
1649 695 bojilova
      boolean validate = false;
1650 1384 tao
      DocumentImplWrapper documentWrapper = null;
1651 204 jones
      try {
1652 1360 tao
        // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1653 695 bojilova
        // in order to decide whether to use validation parser
1654 1760 tao
        validate = needDTDValidation(xml);
1655 1384 tao
        if (validate)
1656
        {
1657
          // set a dtd base validation parser
1658
          String rule = DocumentImpl.DTD;
1659
          documentWrapper = new DocumentImplWrapper(rule, validate);
1660
        }
1661 1760 tao
        else if (needSchemaValidation(xml))
1662 1384 tao
        {
1663 1409 tao
          // for eml2
1664 1760 tao
          if (needEml2Validation(xml))
1665 1409 tao
          {
1666
             // set eml2 base validation parser
1667
            String rule = DocumentImpl.EML2;
1668 1471 tao
            // using emlparser to check id validation
1669
            EMLParser parser = new EMLParser(doctext[0]);
1670 1409 tao
            documentWrapper = new DocumentImplWrapper(rule, true);
1671
          }
1672
          else
1673
          {
1674
            // set schema base validation parser
1675
            String rule = DocumentImpl.SCHEMA;
1676
            documentWrapper = new DocumentImplWrapper(rule, true);
1677
          }
1678 1384 tao
        }
1679
        else
1680
        {
1681
          documentWrapper = new DocumentImplWrapper("", false);
1682
        }
1683 1716 berkley
1684 204 jones
        String[] action = (String[])params.get("action");
1685
        String[] docid = (String[])params.get("docid");
1686
        String newdocid = null;
1687 203 jones
1688 204 jones
        String doAction = null;
1689
        if (action[0].equals("insert")) {
1690
          doAction = "INSERT";
1691
        } else if (action[0].equals("update")) {
1692
          doAction = "UPDATE";
1693
        }
1694 1360 tao
1695
        try
1696 1217 tao
        {
1697 680 bojilova
          // get a connection from the pool
1698 1217 tao
          dbConn=DBConnectionPool.
1699
                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1700
          serialNumber=dbConn.getCheckOutSerialNumber();
1701 1360 tao
1702 1760 tao
           // write the document to the database
1703 1360 tao
          try
1704 1217 tao
          {
1705 680 bojilova
            String accNumber = docid[0];
1706 1292 tao
            MetaCatUtil.debugMessage(""+ doAction + " " + accNumber +"...", 10);
1707 1360 tao
            if (accNumber.equals(""))
1708 1217 tao
            {
1709 680 bojilova
              accNumber = null;
1710 1217 tao
            }//if
1711 1384 tao
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1712
                                          accNumber, user, groups);
1713 1360 tao
1714
          }//try
1715
          catch (NullPointerException npe)
1716 1217 tao
          {
1717 1384 tao
            newdocid = documentWrapper.write(dbConn, xml, pub, dtd, doAction,
1718
                                          null, user, groups);
1719 1217 tao
          }//catch
1720 1716 berkley
1721 1360 tao
        }//try
1722
        finally
1723 1217 tao
        {
1724
          // Return db connection
1725
          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1726 1360 tao
        }
1727 309 bojilova
1728 204 jones
        // set content type and other response header fields first
1729 1377 tao
        //response.setContentType("text/xml");
1730 204 jones
        out.println("<?xml version=\"1.0\"?>");
1731
        out.println("<success>");
1732 1360 tao
        out.println("<docid>" + newdocid + "</docid>");
1733 204 jones
        out.println("</success>");
1734
1735 1716 berkley
      }
1736
      catch (NullPointerException npe)
1737 1466 tao
      {
1738 1377 tao
        //response.setContentType("text/xml");
1739 204 jones
        out.println("<?xml version=\"1.0\"?>");
1740
        out.println("<error>");
1741 1360 tao
        out.println(npe.getMessage());
1742 204 jones
        out.println("</error>");
1743 55 jones
      }
1744 1716 berkley
    }
1745
    catch (Exception e)
1746 1466 tao
    {
1747 1377 tao
      //response.setContentType("text/xml");
1748 204 jones
      out.println("<?xml version=\"1.0\"?>");
1749
      out.println("<error>");
1750 1360 tao
      out.println(e.getMessage());
1751 204 jones
      out.println("</error>");
1752 203 jones
    }
1753 55 jones
  }
1754 203 jones
1755 1360 tao
  /**
1756
   * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... >
1757 695 bojilova
   * in order to decide whether to use validation parser
1758
   */
1759 1760 tao
  private static boolean needDTDValidation(StringReader xmlreader) throws
1760
                                                             IOException
1761
  {
1762 1360 tao
1763 1760 tao
1764 695 bojilova
    StringBuffer cbuff = new StringBuffer();
1765
    java.util.Stack st = new java.util.Stack();
1766
    boolean validate = false;
1767
    int c;
1768
    int inx;
1769 1360 tao
1770 695 bojilova
    // read from the stream until find the keywords
1771
    while ( (st.empty() || st.size()<4) && ((c = xmlreader.read()) != -1) ) {
1772
      cbuff.append((char)c);
1773
1774
      // "<!DOCTYPE" keyword is found; put it in the stack
1775
      if ( (inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1 ) {
1776
        cbuff = new StringBuffer();
1777
        st.push("<!DOCTYPE");
1778
      }
1779
      // "PUBLIC" keyword is found; put it in the stack
1780
      if ( (inx = cbuff.toString().indexOf("PUBLIC")) != -1 ) {
1781
        cbuff = new StringBuffer();
1782
        st.push("PUBLIC");
1783
      }
1784
      // "SYSTEM" keyword is found; put it in the stack
1785
      if ( (inx = cbuff.toString().indexOf("SYSTEM")) != -1 ) {
1786
        cbuff = new StringBuffer();
1787
        st.push("SYSTEM");
1788
      }
1789
      // ">" character is found; put it in the stack
1790 1360 tao
      // ">" is found twice: fisrt from <?xml ...?>
1791 695 bojilova
      // and second from <!DOCTYPE ... >
1792
      if ( (inx = cbuff.toString().indexOf(">")) != -1 ) {
1793
        cbuff = new StringBuffer();
1794
        st.push(">");
1795
      }
1796
    }
1797
1798
    // close the stream
1799 1760 tao
    xmlreader.reset();
1800 695 bojilova
1801
    // check the stack whether it contains the keywords:
1802
    // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1803
    if ( st.size() == 4 ) {
1804
      if ( ((String)st.pop()).equals(">") &&
1805
           ( ((String)st.peek()).equals("PUBLIC") |
1806
             ((String)st.pop()).equals("SYSTEM") ) &&
1807
           ((String)st.pop()).equals("<!DOCTYPE") )  {
1808
        validate = true;
1809
      }
1810
    }
1811
1812 1384 tao
    MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1813 695 bojilova
    return validate;
1814
  }
1815 731 bojilova
  // END OF INSERT/UPDATE SECTION
1816 1716 berkley
1817 1384 tao
  /* check if the xml string contains key words to specify schema loocation*/
1818 1760 tao
  private boolean needSchemaValidation(StringReader xml) throws IOException
1819 1384 tao
  {
1820
    boolean needSchemaValidate =false;
1821
    if (xml == null)
1822
    {
1823
      MetaCatUtil.debugMessage("Validation for schema is " +
1824
                               needSchemaValidate, 10);
1825
      return needSchemaValidate;
1826
    }
1827 1760 tao
    System.out.println("before get target line");
1828 1629 tao
    String targetLine = getSchemaLine(xml);
1829 1760 tao
    System.out.println("before get target line");
1830 1716 berkley
    // to see if the second line contain some keywords
1831 1629 tao
    if (targetLine != null && (targetLine.indexOf(SCHEMALOCATIONKEYWORD) != -1||
1832
             targetLine.indexOf(NONAMESPACELOCATION) != -1 ))
1833 1384 tao
    {
1834
      // if contains schema location key word, should be validate
1835
      needSchemaValidate = true;
1836
    }
1837 1716 berkley
1838
    MetaCatUtil.debugMessage("Validation for schema is " +
1839 1384 tao
                             needSchemaValidate, 10);
1840
    return needSchemaValidate;
1841 1716 berkley
1842 1384 tao
  }
1843 1716 berkley
1844 1409 tao
   /* check if the xml string contains key words to specify schema loocation*/
1845 1760 tao
  private boolean needEml2Validation(StringReader xml) throws IOException
1846 1409 tao
  {
1847
    boolean needEml2Validate =false;
1848 1760 tao
    String emlNameSpace =DocumentImpl.EMLNAMESPACE;
1849
    String schemaLocationContent = null;
1850 1409 tao
    if (xml == null)
1851
    {
1852
      MetaCatUtil.debugMessage("Validation for schema is " +
1853
                               needEml2Validate, 10);
1854
      return needEml2Validate;
1855
    }
1856 1629 tao
    String targetLine = getSchemaLine(xml);
1857 1716 berkley
1858 1760 tao
    if (targetLine != null)
1859 1409 tao
    {
1860 1760 tao
1861
      int startIndex = targetLine.indexOf(SCHEMALOCATIONKEYWORD);
1862
      int start = 1;
1863
      int end   = 1;
1864
      String schemaLocation = null;
1865
      int count = 0;
1866
      if (startIndex != -1)
1867
      {
1868
        for ( int i=startIndex; i<targetLine.length(); i++)
1869
        {
1870
          if (targetLine.charAt(i) =='"')
1871
          {
1872
            count ++;
1873
          }
1874
          if (targetLine.charAt(i) =='"' && count == 1)
1875
          {
1876
            start = i;
1877
          }
1878
          if (targetLine.charAt(i) =='"' && count == 2)
1879
          {
1880
            end = i;
1881
            break;
1882
          }
1883
        }
1884
      }
1885
      schemaLocation = targetLine.substring(start+1, end);
1886
      MetaCatUtil.debugMessage("schemaLocation in xml is: "+schemaLocation, 30);
1887
      if ( schemaLocation.indexOf(emlNameSpace) != -1)
1888
      {
1889
        needEml2Validate = true;
1890
      }
1891 1409 tao
    }
1892 1716 berkley
1893
    MetaCatUtil.debugMessage("Validation for eml is " +
1894 1409 tao
                             needEml2Validate, 10);
1895
    return needEml2Validate;
1896 1716 berkley
1897 1409 tao
  }
1898 1716 berkley
1899 1760 tao
  private String getSchemaLine(StringReader xml) throws IOException
1900 1629 tao
  {
1901
    // find the line
1902
    String secondLine = null;
1903
    int count =0;
1904
    int endIndex = 0;
1905
    int startIndex = 0;
1906
    final int TARGETNUM = 2;
1907 1760 tao
    StringBuffer buffer = new StringBuffer();
1908
    boolean comment =false;
1909
    char thirdPreviousCharacter = '?';
1910
    char secondPreviousCharacter ='?';
1911
    char previousCharacter = '?';
1912
    char currentCharacter = '?';
1913
1914
    while ( (currentCharacter = (char) xml.read()) != -1)
1915 1629 tao
    {
1916 1760 tao
      //in a comment
1917
      if (currentCharacter =='-' && previousCharacter == '-'  &&
1918
          secondPreviousCharacter =='!' && thirdPreviousCharacter == '<')
1919 1629 tao
      {
1920 1760 tao
        comment = true;
1921
      }
1922
      //out of comment
1923
      if (comment && currentCharacter == '>' && previousCharacter == '-' &&
1924
          secondPreviousCharacter =='-')
1925
      {
1926
         comment = false;
1927
      }
1928
1929
      //this is not comment
1930
      if (currentCharacter !='!' && previousCharacter == '<' && !comment)
1931
      {
1932 1629 tao
        count ++;
1933 1760 tao
      }
1934
      // get target line
1935
      if (count == TARGETNUM && currentCharacter !='>')
1936 1629 tao
      {
1937 1760 tao
        buffer.append(currentCharacter);
1938
      }
1939
      if (count == TARGETNUM && currentCharacter == '>')
1940
      {
1941
          break;
1942
      }
1943
      thirdPreviousCharacter = secondPreviousCharacter;
1944
      secondPreviousCharacter = previousCharacter;
1945
      previousCharacter = currentCharacter;
1946
1947
    }
1948
    secondLine = buffer.toString();
1949 1629 tao
    MetaCatUtil.debugMessage("the second line string is: "+secondLine, 25);
1950 1760 tao
    xml.reset();
1951 1629 tao
    return secondLine;
1952
  }
1953 1716 berkley
1954 731 bojilova
  // DELETE SECTION
1955 1360 tao
  /**
1956
   * Handle the database delete request and delete an XML document
1957 203 jones
   * from the database connection
1958
   */
1959 1360 tao
  private void handleDeleteAction(PrintWriter out, Hashtable params,
1960 802 bojilova
               HttpServletResponse response, String user, String[] groups) {
1961 203 jones
1962
    String[] docid = (String[])params.get("docid");
1963 1360 tao
1964 203 jones
    // delete the document from the database
1965
    try {
1966 1360 tao
1967 203 jones
                                      // NOTE -- NEED TO TEST HERE
1968 408 jones
                                      // FOR EXISTENCE OF DOCID PARAM
1969 203 jones
                                      // BEFORE ACCESSING ARRAY
1970 1360 tao
      try {
1971 1217 tao
        DocumentImpl.delete(docid[0], user, groups);
1972 204 jones
        response.setContentType("text/xml");
1973
        out.println("<?xml version=\"1.0\"?>");
1974
        out.println("<success>");
1975 1360 tao
        out.println("Document deleted.");
1976 204 jones
        out.println("</success>");
1977 203 jones
      } catch (AccessionNumberException ane) {
1978 204 jones
        response.setContentType("text/xml");
1979
        out.println("<?xml version=\"1.0\"?>");
1980
        out.println("<error>");
1981
        out.println("Error deleting document!!!");
1982 1360 tao
        out.println(ane.getMessage());
1983 204 jones
        out.println("</error>");
1984 203 jones
      }
1985 204 jones
    } catch (Exception e) {
1986
      response.setContentType("text/xml");
1987
      out.println("<?xml version=\"1.0\"?>");
1988
      out.println("<error>");
1989 1360 tao
      out.println(e.getMessage());
1990 204 jones
      out.println("</error>");
1991 1360 tao
    }
1992 203 jones
  }
1993 731 bojilova
  // END OF DELETE SECTION
1994 1360 tao
1995 731 bojilova
  // VALIDATE SECTION
1996 1360 tao
  /**
1997 380 jones
   * Handle the validation request and return the results to the requestor
1998 68 higgins
   */
1999 1342 tao
  private void handleValidateAction(PrintWriter out, Hashtable params) {
2000 68 higgins
2001 103 jones
    // Get the document indicated
2002
    String valtext = null;
2003 1217 tao
    DBConnection dbConn = null;
2004
    int serialNumber = -1;
2005 1360 tao
2006 103 jones
    try {
2007
      valtext = ((String[])params.get("valtext"))[0];
2008
    } catch (Exception nullpe) {
2009 68 higgins
2010 1360 tao
2011 162 bojilova
      String docid = null;
2012 103 jones
      try {
2013
        // Find the document id number
2014 1360 tao
        docid = ((String[])params.get("docid"))[0];
2015 309 bojilova
2016 1360 tao
2017 309 bojilova
        // Get the document indicated from the db
2018 1217 tao
        DocumentImpl xmldoc = new DocumentImpl(docid);
2019 393 jones
        valtext = xmldoc.toString();
2020 185 jones
2021 103 jones
      } catch (NullPointerException npe) {
2022 1360 tao
2023 253 jones
        out.println("<error>Error getting document ID: " + docid + "</error>");
2024 1217 tao
        //if ( conn != null ) { util.returnConnection(conn); }
2025 380 jones
        return;
2026 309 bojilova
      } catch (Exception e) {
2027 1360 tao
2028
        out.println(e.getMessage());
2029
      }
2030 103 jones
    }
2031 68 higgins
2032 1360 tao
2033 103 jones
    try {
2034 309 bojilova
      // get a connection from the pool
2035 1217 tao
      dbConn=DBConnectionPool.
2036
                  getDBConnection("MetaCatServlet.handleValidateAction");
2037
      serialNumber=dbConn.getCheckOutSerialNumber();
2038
      DBValidate valobj = new DBValidate(saxparser,dbConn);
2039 185 jones
      boolean valid = valobj.validateString(valtext);
2040 68 higgins
2041
      // set content type and other response header fields first
2042 1360 tao
2043 253 jones
      out.println(valobj.returnErrors());
2044
2045 103 jones
    } catch (NullPointerException npe2) {
2046
      // set content type and other response header fields first
2047 1360 tao
2048
      out.println("<error>Error validating document.</error>");
2049 309 bojilova
    } catch (Exception e) {
2050 1360 tao
2051
      out.println(e.getMessage());
2052 309 bojilova
    } finally {
2053 1217 tao
      // Return db connection
2054
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2055 1360 tao
    }
2056 103 jones
  }
2057 731 bojilova
  // END OF VALIDATE SECTION
2058 1360 tao
2059 731 bojilova
  // OTHER ACTION HANDLERS
2060 1360 tao
2061 1292 tao
  /**
2062
   * Handle "getrevsionanddoctype" action
2063
   * Given a docid, return it's current revision and doctype from data base
2064
   * The output is String look like "rev;doctype"
2065
   */
2066 1360 tao
  private void handleGetRevisionAndDocTypeAction(PrintWriter out,
2067 1292 tao
                                                              Hashtable params)
2068
  {
2069
    // To store doc parameter
2070
    String [] docs = new String[10];
2071
    // Store a single doc id
2072
    String givenDocId = null;
2073
    // Get docid from parameters
2074 1360 tao
    if (params.containsKey("docid"))
2075 1292 tao
    {
2076
      docs = (String[])params.get("docid");
2077
    }
2078
    // Get first docid form string array
2079
    givenDocId = docs[0];
2080 1360 tao
2081
    try
2082 1292 tao
    {
2083
      // Make sure there is a docid
2084
      if (givenDocId == null || givenDocId.equals(""))
2085
      {
2086
        throw new Exception("User didn't specify docid!");
2087
      }//if
2088 1360 tao
2089 1292 tao
      // Create a DBUtil object
2090
      DBUtil dbutil = new DBUtil();
2091
      // Get a rev and doctype
2092 1360 tao
      String revAndDocType =
2093 1292 tao
                dbutil.getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
2094
      out.println(revAndDocType);
2095
2096 1360 tao
    }//try
2097
    catch (Exception e)
2098 1292 tao
    {
2099
      // Handle exception
2100
      out.println("<?xml version=\"1.0\"?>");
2101
      out.println("<error>");
2102
      out.println(e.getMessage());
2103
      out.println("</error>");
2104 1360 tao
    }//catch
2105
2106 1292 tao
  }//handleGetRevisionAndDocTypeAction
2107 1360 tao
2108
  /**
2109 688 bojilova
   * Handle "getaccesscontrol" action.
2110
   * Read Access Control List from db connection in XML format
2111
   */
2112 1360 tao
  private void handleGetAccessControlAction(PrintWriter out, Hashtable params,
2113
                                       HttpServletResponse response,
2114 802 bojilova
                                       String username, String[] groupnames) {
2115 688 bojilova
2116 1217 tao
    DBConnection dbConn = null;
2117
    int serialNumber = -1;
2118 688 bojilova
    String docid = ((String[])params.get("docid"))[0];
2119 1360 tao
2120 688 bojilova
    try {
2121
2122
        // get connection from the pool
2123 1217 tao
        dbConn=DBConnectionPool.
2124
                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2125
        serialNumber=dbConn.getCheckOutSerialNumber();
2126
        AccessControlList aclobj = new AccessControlList(dbConn);
2127 802 bojilova
        String acltext = aclobj.getACL(docid, username, groupnames);
2128 688 bojilova
        out.println(acltext);
2129
2130
    } catch (Exception e) {
2131
      out.println("<?xml version=\"1.0\"?>");
2132
      out.println("<error>");
2133
      out.println(e.getMessage());
2134
      out.println("</error>");
2135
    } finally {
2136 1217 tao
      // Retrun db connection to pool
2137
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2138 1360 tao
    }
2139
2140 688 bojilova
  }
2141
2142 1360 tao
  /**
2143 731 bojilova
   * Handle the "getprincipals" action.
2144
   * Read all principals from authentication scheme in XML format
2145
   */
2146
  private void handleGetPrincipalsAction(PrintWriter out, String user,
2147
                                         String password) {
2148
2149 1360 tao
2150 731 bojilova
    try {
2151
2152 1360 tao
2153 731 bojilova
        AuthSession auth = new AuthSession();
2154
        String principals = auth.getPrincipals(user, password);
2155
        out.println(principals);
2156
2157
    } catch (Exception e) {
2158
      out.println("<?xml version=\"1.0\"?>");
2159
      out.println("<error>");
2160
      out.println(e.getMessage());
2161
      out.println("</error>");
2162 1360 tao
    }
2163
2164 731 bojilova
  }
2165
2166 1360 tao
  /**
2167 688 bojilova
   * Handle "getdoctypes" action.
2168 302 bojilova
   * Read all doctypes from db connection in XML format
2169
   */
2170 1360 tao
  private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
2171 302 bojilova
                                       HttpServletResponse response) {
2172
2173 1360 tao
2174 302 bojilova
    try {
2175
2176 1360 tao
2177 1217 tao
        DBUtil dbutil = new DBUtil();
2178 302 bojilova
        String doctypes = dbutil.readDoctypes();
2179
        out.println(doctypes);
2180
2181
    } catch (Exception e) {
2182
      out.println("<?xml version=\"1.0\"?>");
2183
      out.println("<error>");
2184
      out.println(e.getMessage());
2185
      out.println("</error>");
2186 1360 tao
    }
2187
2188 302 bojilova
  }
2189
2190 1360 tao
  /**
2191 699 bojilova
   * Handle the "getdtdschema" action.
2192
   * Read DTD or Schema file for a given doctype from Metacat catalog system
2193
   */
2194
  private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2195
                                        HttpServletResponse response) {
2196
2197 1360 tao
2198 699 bojilova
    String doctype = null;
2199
    String[] doctypeArr = (String[])params.get("doctype");
2200
2201
    // get only the first doctype specified in the list of doctypes
2202
    // it could be done for all doctypes in that list
2203
    if (doctypeArr != null) {
2204 1360 tao
        doctype = ((String[])params.get("doctype"))[0];
2205 699 bojilova
    }
2206
2207
    try {
2208
2209 1360 tao
2210 1217 tao
        DBUtil dbutil = new DBUtil();
2211 699 bojilova
        String dtdschema = dbutil.readDTDSchema(doctype);
2212
        out.println(dtdschema);
2213
2214
    } catch (Exception e) {
2215
      out.println("<?xml version=\"1.0\"?>");
2216
      out.println("<error>");
2217
      out.println(e.getMessage());
2218
      out.println("</error>");
2219 1360 tao
    }
2220
2221 699 bojilova
  }
2222
2223 1360 tao
  /**
2224 688 bojilova
   * Handle the "getdataguide" action.
2225 302 bojilova
   * Read Data Guide for a given doctype from db connection in XML format
2226
   */
2227 1360 tao
  private void handleGetDataGuideAction(PrintWriter out, Hashtable params,
2228 302 bojilova
                                        HttpServletResponse response) {
2229
2230 1360 tao
2231 316 bojilova
    String doctype = null;
2232
    String[] doctypeArr = (String[])params.get("doctype");
2233 309 bojilova
2234 316 bojilova
    // get only the first doctype specified in the list of doctypes
2235
    // it could be done for all doctypes in that list
2236
    if (doctypeArr != null) {
2237 1360 tao
        doctype = ((String[])params.get("doctype"))[0];
2238 316 bojilova
    }
2239
2240 302 bojilova
    try {
2241
2242 1360 tao
2243 1217 tao
        DBUtil dbutil = new DBUtil();
2244 316 bojilova
        String dataguide = dbutil.readDataGuide(doctype);
2245 302 bojilova
        out.println(dataguide);
2246
2247
    } catch (Exception e) {
2248
      out.println("<?xml version=\"1.0\"?>");
2249
      out.println("<error>");
2250
      out.println(e.getMessage());
2251
      out.println("</error>");
2252 1217 tao
    }
2253 1360 tao
2254 302 bojilova
  }
2255
2256 1360 tao
  /**
2257 793 bojilova
   * Handle the "getlastdocid" action.
2258
   * Get the latest docid with rev number from db connection in XML format
2259
   */
2260 1360 tao
  private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2261 793 bojilova
                                        HttpServletResponse response) {
2262
2263 1217 tao
2264 847 jones
    String scope = ((String[])params.get("scope"))[0];
2265
    if (scope == null) {
2266
        scope = ((String[])params.get("username"))[0];
2267
    }
2268 793 bojilova
2269
    try {
2270
2271 1360 tao
2272 1217 tao
        DBUtil dbutil = new DBUtil();
2273 847 jones
        String lastDocid = dbutil.getMaxDocid(scope);
2274 793 bojilova
        out.println("<?xml version=\"1.0\"?>");
2275
        out.println("<lastDocid>");
2276 847 jones
        out.println("  <scope>" + scope + "</scope>");
2277 793 bojilova
        out.println("  <docid>" + lastDocid + "</docid>");
2278
        out.println("</lastDocid>");
2279
2280
    } catch (Exception e) {
2281
      out.println("<?xml version=\"1.0\"?>");
2282
      out.println("<error>");
2283
      out.println(e.getMessage());
2284
      out.println("</error>");
2285 1217 tao
    }
2286 1360 tao
2287 793 bojilova
  }
2288
2289 1360 tao
  /**
2290
   * Handle documents passed to metacat that are encoded using the
2291 798 jones
   * "multipart/form-data" mime type.  This is typically used for uploading
2292
   * data files which may be binary and large.
2293
   */
2294
  private void handleMultipartForm(HttpServletRequest request,
2295 1360 tao
                                   HttpServletResponse response)
2296 798 jones
  {
2297
    PrintWriter out = null;
2298
    String action = null;
2299
2300
    // Parse the multipart form, and save the parameters in a Hashtable and
2301
    // save the FileParts in a hashtable
2302
2303
    Hashtable params = new Hashtable();
2304
    Hashtable fileList = new Hashtable();
2305 1617 tao
    int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2306
                                                                   .intValue();
2307
    MetaCatUtil.debugMessage("The limit size of data file is: "+sizeLimit, 50);
2308 798 jones
2309
    try {
2310
      // MBJ: need to put filesize limit in Metacat config (metacat.properties)
2311 1716 berkley
      MultipartParser mp = new MultipartParser(request, sizeLimit*1024*1024);
2312 798 jones
      Part part;
2313
      while ((part = mp.readNextPart()) != null) {
2314
        String name = part.getName();
2315
2316
        if (part.isParam()) {
2317
          // it's a parameter part
2318
          ParamPart paramPart = (ParamPart) part;
2319
          String value = paramPart.getStringValue();
2320
          params.put(name, value);
2321
          if (name.equals("action")) {
2322
            action = value;
2323
          }
2324
        } else if (part.isFile()) {
2325
          // it's a file part
2326
          FilePart filePart = (FilePart) part;
2327
          fileList.put(name, filePart);
2328
2329
          // Stop once the first file part is found, otherwise going onto the
2330
          // next part prevents access to the file contents.  So...for upload
2331
          // to work, the datafile must be the last part
2332
          break;
2333
        }
2334
      }
2335
    } catch (IOException ioe) {
2336
      try {
2337
        out = response.getWriter();
2338
      } catch (IOException ioe2) {
2339
        System.err.println("Fatal Error: couldn't get response output stream.");
2340
      }
2341
      out.println("<?xml version=\"1.0\"?>");
2342
      out.println("<error>");
2343
      out.println("Error: problem reading multipart data.");
2344
      out.println("</error>");
2345
    }
2346
2347
    // Get the session information
2348
    String username = null;
2349
    String password = null;
2350 802 bojilova
    String[] groupnames = null;
2351 798 jones
    String sess_id = null;
2352
2353 1360 tao
    // be aware of session expiration on every request
2354 798 jones
    HttpSession sess = request.getSession(true);
2355
    if (sess.isNew()) {
2356
      // session expired or has not been stored b/w user requests
2357
      username = "public";
2358
      sess.setAttribute("username", username);
2359
    } else {
2360
      username = (String)sess.getAttribute("username");
2361
      password = (String)sess.getAttribute("password");
2362 802 bojilova
      groupnames = (String[])sess.getAttribute("groupnames");
2363 798 jones
      try {
2364
        sess_id = (String)sess.getId();
2365
      } catch(IllegalStateException ise) {
2366
        System.out.println("error in  handleMultipartForm: this shouldn't " +
2367 1360 tao
                           "happen: the session should be valid: " +
2368 798 jones
                           ise.getMessage());
2369
      }
2370 1360 tao
    }
2371
2372 1292 tao
    // Get the out stream
2373
    try {
2374 798 jones
          out = response.getWriter();
2375
        } catch (IOException ioe2) {
2376 943 tao
          util.debugMessage("Fatal Error: couldn't get response "+
2377 1490 tao
                             "output stream.", 30);
2378 798 jones
        }
2379 1360 tao
2380 1292 tao
    if ( action.equals("upload")) {
2381
      if (username != null &&  !username.equals("public")) {
2382 1360 tao
        handleUploadAction(request, out, params, fileList,
2383 1292 tao
                           username, groupnames);
2384
      } else {
2385 1360 tao
2386 798 jones
        out.println("<?xml version=\"1.0\"?>");
2387
        out.println("<error>");
2388
        out.println("Permission denied for " + action);
2389
        out.println("</error>");
2390
      }
2391
    } else {
2392 1292 tao
      /*try {
2393 798 jones
        out = response.getWriter();
2394
      } catch (IOException ioe2) {
2395
        System.err.println("Fatal Error: couldn't get response output stream.");
2396 1292 tao
      }*/
2397 798 jones
      out.println("<?xml version=\"1.0\"?>");
2398
      out.println("<error>");
2399
      out.println("Error: action not registered.  Please report this error.");
2400
      out.println("</error>");
2401
    }
2402 1217 tao
    out.close();
2403 798 jones
  }
2404
2405 1360 tao
  /**
2406
   * Handle the upload action by saving the attached file to disk and
2407 798 jones
   * registering it in the Metacat db
2408
   */
2409
  private void handleUploadAction(HttpServletRequest request,
2410 1360 tao
                                  PrintWriter out,
2411
                                  Hashtable params, Hashtable fileList,
2412 802 bojilova
                                  String username, String[] groupnames)
2413 798 jones
  {
2414 1292 tao
    //PrintWriter out = null;
2415 1217 tao
    //Connection conn = null;
2416 798 jones
    String action = null;
2417
    String docid = null;
2418 1360 tao
2419 1292 tao
    /*response.setContentType("text/xml");
2420 1360 tao
    try
2421 1041 tao
    {
2422 798 jones
      out = response.getWriter();
2423 1360 tao
    }
2424
    catch (IOException ioe2)
2425 1041 tao
    {
2426 798 jones
      System.err.println("Fatal Error: couldn't get response output stream.");
2427 1292 tao
    }*/
2428 798 jones
2429 1360 tao
    if (params.containsKey("docid"))
2430 1041 tao
    {
2431 798 jones
      docid = (String)params.get("docid");
2432
    }
2433
2434
    // Make sure we have a docid and datafile
2435
    if (docid != null && fileList.containsKey("datafile")) {
2436
2437
      // Get a reference to the file part of the form
2438
      FilePart filePart = (FilePart)fileList.get("datafile");
2439
      String fileName = filePart.getFileName();
2440 1056 tao
      MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2441 798 jones
2442
      // Check if the right file existed in the uploaded data
2443
      if (fileName != null) {
2444 1360 tao
2445
        try
2446 1028 tao
        {
2447 1292 tao
           //MetaCatUtil.debugMessage("Upload datafile " + docid +"...", 10);
2448 1028 tao
           //If document get lock data file grant
2449 1070 tao
           if (DocumentImpl.getDataFileLockGrant(docid))
2450
           {
2451 1064 tao
              // register the file in the database (which generates an exception
2452 1028 tao
              //if the docid is not acceptable or other untoward things happen
2453
              DocumentImpl.registerDocument(fileName, "BIN", docid, username);
2454 1360 tao
2455 1028 tao
              // Save the data file to disk using "docid" as the name
2456
              dataDirectory.mkdirs();
2457
              File newFile = new File(dataDirectory, docid);
2458
              long size = filePart.writeTo(newFile);
2459 1360 tao
2460 1292 tao
              // Force replication this data file
2461
              // To data file, "insert" and update is same
2462 1360 tao
              // The fourth parameter is null. Because it is notification server
2463
              // and this method is in MetaCatServerlet. It is original command,
2464 1292 tao
              // not get force replication info from another metacat
2465
              ForceReplicationHandler frh = new ForceReplicationHandler
2466
                                                (docid, "insert", false, null);
2467 1360 tao
2468 1028 tao
              // set content type and other response header fields first
2469
              out.println("<?xml version=\"1.0\"?>");
2470
              out.println("<success>");
2471 1360 tao
              out.println("<docid>" + docid + "</docid>");
2472
              out.println("<size>" + size + "</size>");
2473 1028 tao
              out.println("</success>");
2474 1070 tao
          }//if
2475 1360 tao
2476 1028 tao
        } //try
2477 1360 tao
        catch (Exception e)
2478 1041 tao
        {
2479 798 jones
          out.println("<?xml version=\"1.0\"?>");
2480
          out.println("<error>");
2481 1360 tao
          out.println(e.getMessage());
2482 798 jones
          out.println("</error>");
2483
        }
2484 1360 tao
2485 1041 tao
      }
2486 1360 tao
      else
2487 1041 tao
      {
2488 798 jones
        // the field did not contain a file
2489
        out.println("<?xml version=\"1.0\"?>");
2490
        out.println("<error>");
2491 1360 tao
        out.println("The uploaded data did not contain a valid file.");
2492 798 jones
        out.println("</error>");
2493
      }
2494 1360 tao
    }
2495
    else
2496 1041 tao
    {
2497 798 jones
      // Error bcse docid missing or file missing
2498
      out.println("<?xml version=\"1.0\"?>");
2499
      out.println("<error>");
2500
      out.println("The uploaded data did not contain a valid docid " +
2501 1360 tao
                  "or valid file.");
2502 798 jones
      out.println("</error>");
2503
    }
2504
  }
2505 1716 berkley
2506 1369 tao
  /*
2507
   * A method to handle set access action
2508
   */
2509
  private void handleSetAccessAction(PrintWriter out,
2510
                                   Hashtable params,
2511
                                   String username)
2512
  {
2513
    String [] docList        = null;
2514
    String [] principalList  = null;
2515
    String [] permissionList = null;
2516
    String [] permTypeList   = null;
2517
    String [] permOrderList  = null;
2518
    String permission = null;
2519
    String permType   = null;
2520
    String permOrder  = null;
2521
    Vector errorList  = new Vector();
2522
    String error      = null;
2523
    Vector successList = new Vector();
2524
    String success    = null;
2525 1716 berkley
2526
2527 1369 tao
    // Get parameters
2528 1716 berkley
    if (params.containsKey("docid"))
2529 1369 tao
    {
2530
      docList = (String[])params.get("docid");
2531
    }
2532
    if (params.containsKey("principal"))
2533
    {
2534 1716 berkley
      principalList = (String[])params.get("principal");
2535 1369 tao
    }
2536
    if (params.containsKey("permission"))
2537
    {
2538
      permissionList = (String[])params.get("permission");
2539 1716 berkley
2540 1369 tao
    }
2541
    if (params.containsKey("permType"))
2542
    {
2543
      permTypeList = (String[])params.get("permType");
2544 1716 berkley
2545 1369 tao
    }
2546
    if (params.containsKey("permOrder"))
2547
    {
2548
      permOrderList = (String[])params.get("permOrder");
2549 1716 berkley
2550 1369 tao
    }
2551 1716 berkley
2552 1369 tao
    // Make sure the parameter is not null
2553
    if (docList == null || principalList == null || permTypeList == null ||
2554
        permissionList == null)
2555
    {
2556
      error = "Please check your parameter list, it should look like: "+
2557
              "?action=setaccess&docid=pipeline.1.1&principal=public" +
2558
              "&permission=read&permType=allow&permOrder=allowFirst";
2559
      errorList.addElement(error);
2560
      outputResponse(successList, errorList, out);
2561
      return;
2562
    }
2563 1716 berkley
2564 1369 tao
    // Only select first element for permission, type and order
2565
    permission = permissionList[0];
2566
    permType = permTypeList[0];
2567
    if (permOrderList != null)
2568
    {
2569
       permOrder = permOrderList[0];
2570
    }
2571 1716 berkley
2572 1369 tao
    // Get package doctype set
2573
    Vector packageSet =MetaCatUtil.getOptionList(
2574
                                    MetaCatUtil.getOption("packagedoctypeset"));
2575
    //debug
2576
    if (packageSet != null)
2577
    {
2578
      for (int i = 0; i<packageSet.size(); i++)
2579
      {
2580 1716 berkley
        MetaCatUtil.debugMessage("doctype in package set: " +
2581 1369 tao
                              (String)packageSet.elementAt(i), 34);
2582
      }
2583
    }//if
2584 1716 berkley
2585 1369 tao
    // handle every accessionNumber
2586
    for (int i=0; i <docList.length; i++)
2587
    {
2588
      String accessionNumber = docList[i];
2589
      String owner = null;
2590
      String publicId = null;
2591
      // Get document owner and public id
2592
      try
2593
      {
2594
        owner = getFieldValueForDoc(accessionNumber, "user_owner");
2595
        publicId = getFieldValueForDoc(accessionNumber, "doctype");
2596
      }//try
2597
      catch (Exception e)
2598
      {
2599
        MetaCatUtil.debugMessage("Error in handleSetAccessAction: " +
2600
                                  e.getMessage(), 30);
2601
        error = "Error in set access control for document - " + accessionNumber+
2602
                 e.getMessage();
2603
        errorList.addElement(error);
2604
        continue;
2605
      }
2606 1716 berkley
      //check if user is the owner. Only owner can do owner
2607 1369 tao
      if (username == null || owner == null || !username.equals(owner))
2608
      {
2609
        error = "User - " + username + " does not have permission to set " +
2610
                "access control for docid - " + accessionNumber;
2611
        errorList.addElement(error);
2612
        continue;
2613
      }
2614 1716 berkley
2615 1369 tao
      // If docid publicid is BIN data file or other beta4, 6 package document
2616
      // we could not do set access control. Because we don't want inconsistent
2617
      // to its access docuemnt
2618
      if (publicId!=null && packageSet!=null && packageSet.contains(publicId))
2619
      {
2620
        error = "Could not set access control to document "+ accessionNumber +
2621
                "because it is in a pakcage and it has a access file for it";
2622
        errorList.addElement(error);
2623
        continue;
2624
      }
2625 1716 berkley
2626 1369 tao
      // for every principle
2627
      for (int j = 0; j<principalList.length; j++)
2628
      {
2629
        String principal = principalList[j];
2630
        try
2631
        {
2632
          //insert permission
2633 1716 berkley
          AccessControlForSingleFile accessControl = new
2634 1369 tao
                           AccessControlForSingleFile(accessionNumber,
2635
                                    principal, permission, permType, permOrder);
2636
          accessControl.insertPermissions();
2637
          success = "Set access control to document "+ accessionNumber +
2638
                    " successfully";
2639
          successList.addElement(success);
2640
        }
2641
        catch (Exception ee)
2642
        {
2643
          MetaCatUtil.debugMessage("Erorr in handleSetAccessAction2: " +
2644
                                   ee.getMessage(), 30);
2645 1716 berkley
          error = "Faild to set access control for document " +
2646 1369 tao
                  accessionNumber + " because " + ee.getMessage();
2647
          errorList.addElement(error);
2648
          continue;
2649
        }
2650
      }//for every principle
2651 1716 berkley
    }//for every document
2652 1369 tao
    outputResponse(successList, errorList, out);
2653
  }//handleSetAccessAction
2654 1716 berkley
2655
2656 1369 tao
  /*
2657
   * A method try to determin a docid's public id, if couldn't find null
2658
   * will be returned.
2659
   */
2660 1716 berkley
  private String getFieldValueForDoc(String accessionNumber, String fieldName)
2661 1369 tao
                                      throws Exception
2662
  {
2663
    if (accessionNumber==null || accessionNumber.equals("") ||fieldName == null
2664
        || fieldName.equals(""))
2665
    {
2666
      throw new Exception("Docid or field name was not specified");
2667
    }
2668 1716 berkley
2669 1369 tao
    PreparedStatement pstmt = null;
2670
    ResultSet rs = null;
2671
    String fieldValue = null;
2672
    String docId = null;
2673
    DBConnection conn = null;
2674
    int serialNumber = -1;
2675 1716 berkley
2676 1369 tao
    // get rid of revision if access number has
2677
    docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2678
    try
2679
    {
2680
      //check out DBConnection
2681
      conn=DBConnectionPool.getDBConnection("MetaCatServlet.getPublicIdForDoc");
2682
      serialNumber=conn.getCheckOutSerialNumber();
2683
      pstmt = conn.prepareStatement(
2684
            "SELECT " + fieldName + " FROM xml_documents " +
2685
            "WHERE docid = ? ");
2686 1716 berkley
2687 1369 tao
      pstmt.setString(1, docId);
2688
      pstmt.execute();
2689
      rs = pstmt.getResultSet();
2690
      boolean hasRow = rs.next();
2691
      int perm = 0;
2692 1716 berkley
      if ( hasRow )
2693 1369 tao
      {
2694
        fieldValue = rs.getString(1);
2695
      }
2696
      else
2697
      {
2698
        throw new Exception("Could not find document: "+accessionNumber);
2699
      }
2700
    }//try
2701
    catch (Exception e)
2702
    {
2703
      MetaCatUtil.debugMessage("Exception in MetacatServlet.getPublicIdForDoc: "
2704
                               + e.getMessage(), 30);
2705
      throw e;
2706
    }
2707
    finally
2708
    {
2709
      try
2710
      {
2711
        rs.close();
2712
        pstmt.close();
2713 1716 berkley
2714 1369 tao
      }
2715
      finally
2716
      {
2717
        DBConnectionPool.returnDBConnection(conn, serialNumber);
2718
      }
2719
    }
2720
    return fieldValue;
2721
  }//getFieldValueForDoc
2722 1716 berkley
2723 1369 tao
  /*
2724
   * A method to output setAccess action result
2725
   */
2726 1716 berkley
  private void outputResponse(Vector successList,
2727 1369 tao
                              Vector errorList,
2728
                              PrintWriter out)
2729
  {
2730
    boolean error = false;
2731
    boolean success = false;
2732
    // Output prolog
2733
    out.println(PROLOG);
2734
    // output success message
2735
    if ( successList != null)
2736
    {
2737
      for (int i = 0; i<successList.size(); i++)
2738
      {
2739
        out.println(SUCCESS);
2740
        out.println((String)successList.elementAt(i));
2741
        out.println(SUCCESSCLOSE);
2742
        success = true;
2743
      }//for
2744
    }//if
2745
    // output error message
2746
    if (errorList != null)
2747
    {
2748
      for (int i = 0; i<errorList.size(); i++)
2749
      {
2750
        out.println(ERROR);
2751
        out.println((String)errorList.elementAt(i));
2752
        out.println(ERRORCLOSE);
2753
        error = true;
2754
      }//for
2755
    }//if
2756 1716 berkley
2757 1369 tao
    // if no error and no success info, send a error that nothing happened
2758
    if( !error && !success)
2759
    {
2760
      out.println(ERROR);
2761
      out.println("Nothing happend for setaccess action");
2762
      out.println(ERRORCLOSE);
2763
    }
2764 1716 berkley
2765 1369 tao
  }//outputResponse
2766 46 jones
}