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