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 2169 sgarg
 *
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 2169 sgarg
                handleExportAction(params, response, username,
416 2102 jones
                        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 2169 sgarg
     *
653 2098 jones
     * @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 2169 sgarg
     *
675 2098 jones
     * @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 2169 sgarg
     *
705 2098 jones
     * @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 2169 sgarg
    private void handleExportAction(Hashtable params,
711
            HttpServletResponse response,
712 2102 jones
            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 2169 sgarg
     *
795 2098 jones
     * @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 2169 sgarg
            HttpServletRequest request, HttpServletResponse response,
802 2102 jones
            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 2169 sgarg
            if (inlineDataId == null || inlineDataId.equals("")) {
818 2098 jones
                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 2245 sgarg
                    AccessControlInterface.READSTRING))
827
            {
828 2098 jones
                throw new Exception("User " + user
829
                        + " doesn't have permission " + " to read document "
830
                        + docId);
831
            }
832 2245 sgarg
            else
833
            {
834
              //check data access level
835
              try
836
              {
837
                Hashtable unReadableInlineDataList =
838
                PermissionController.getUnReadableInlineDataIdList(docId,user,groups);
839
                if (unReadableInlineDataList.containsValue(inlineDataId))
840
                {
841
                  throw new Exception("User " + user
842
                       + " doesn't have permission " + " to read inlinedata "
843
                       + inlineDataId);
844 2098 jones
845 2245 sgarg
                }//if
846
              }//try
847
              catch (Exception e)
848
              {
849
                throw e;
850
              }//catch
851
            }//else
852
853 2098 jones
            // Get output stream
854
            out = response.getOutputStream();
855
            // read the inline data from the file
856
            String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
857
            File lineData = new File(inlinePath, inlineDataId);
858
            FileInputStream input = new FileInputStream(lineData);
859
            byte[] buffer = new byte[4 * 1024];
860
            int bytes = input.read(buffer);
861
            while (bytes != -1) {
862
                out.write(buffer, 0, bytes);
863
                bytes = input.read(buffer);
864
            }
865 1292 tao
            out.close();
866 1360 tao
867 2169 sgarg
            EventLog.getInstance().log(request.getRemoteAddr(), user,
868 2102 jones
                    inlineDataId, "readinlinedata");
869 2098 jones
        } catch (Exception e) {
870
            try {
871
                PrintWriter pw = null;
872
                // Send error message back
873
                if (out != null) {
874
                    pw = new PrintWriter(out);
875
                } else {
876
                    pw = response.getWriter();
877
                }
878
                pw.println("<?xml version=\"1.0\"?>");
879
                pw.println("<error>");
880
                pw.println(e.getMessage());
881
                pw.println("</error>");
882
                // Close printwriter
883
                pw.close();
884
                // Close output stream if out is not null
885
                if (out != null) {
886
                    out.close();
887
                }
888
            } catch (IOException ioe) {
889
                MetaCatUtil.debugMessage("Problem with the servlet output "
890
                        + "in MetacatServlet.handleExportAction: "
891
                        + ioe.getMessage(), 30);
892
            }
893
            MetaCatUtil.debugMessage(
894
                    "Error in MetacatServlet.handleReadInlineDataAction: "
895
                            + e.getMessage(), 30);
896 1292 tao
        }
897 2098 jones
    }
898
899
    /*
900
     * Get the nodeid from xml_nodes for the inlinedataid
901
     */
902
    private long getInlineDataNodeId(String inLineDataId, String docId)
903
            throws SQLException
904 1292 tao
    {
905 2098 jones
        long nodeId = 0;
906
        String INLINE = "inline";
907
        boolean hasRow;
908
        PreparedStatement pStmt = null;
909
        DBConnection conn = null;
910
        int serialNumber = -1;
911
        String sql = "SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? "
912
                + "AND nodetype='TEXT' AND parentnodeid IN "
913
                + "(SELECT nodeid FROM xml_nodes WHERE docid=? AND "
914
                + "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
915 1360 tao
916 2098 jones
        try {
917
            //check out DBConnection
918
            conn = DBConnectionPool
919
                    .getDBConnection("AccessControlList.isAllowFirst");
920
            serialNumber = conn.getCheckOutSerialNumber();
921 1360 tao
922 2098 jones
            pStmt = conn.prepareStatement(sql);
923
            //bind value
924
            pStmt.setString(1, docId);//docid
925
            pStmt.setString(2, inLineDataId);//inlinedataid
926
            pStmt.setString(3, docId);
927
            // excute query
928
            pStmt.execute();
929
            ResultSet rs = pStmt.getResultSet();
930
            hasRow = rs.next();
931
            // get result
932
            if (hasRow) {
933
                nodeId = rs.getLong(1);
934
            }//if
935
936
        } catch (SQLException e) {
937
            throw e;
938
        } finally {
939
            try {
940
                pStmt.close();
941
            } finally {
942
                DBConnectionPool.returnDBConnection(conn, serialNumber);
943
            }
944 1292 tao
        }
945 2098 jones
        MetaCatUtil.debugMessage("The nodeid for inlinedataid " + inLineDataId
946
                + " is: " + nodeId, 35);
947
        return nodeId;
948
    }
949 1360 tao
950 2098 jones
    /**
951
     * Handle the "read" request of metadata/data files from Metacat or any
952
     * files from Internet; transformed metadata XML document into HTML
953
     * presentation if requested; zip files when more than one were requested.
954 2169 sgarg
     *
955 2098 jones
     * @param params the Hashtable of HTTP request parameters
956 2102 jones
     * @param request the HTTP request object linked to the client
957 2098 jones
     * @param response the HTTP response object linked to the client
958
     * @param user the username sent the request
959
     * @param groups the user's groupnames
960
     */
961 2102 jones
    private void handleReadAction(Hashtable params, HttpServletRequest request,
962 2098 jones
            HttpServletResponse response, String user, String passWord,
963
            String[] groups)
964
    {
965
        ServletOutputStream out = null;
966
        ZipOutputStream zout = null;
967
        PrintWriter pw = null;
968
        boolean zip = false;
969
        boolean withInlineData = true;
970 1360 tao
971 2098 jones
        try {
972
            String[] docs = new String[0];
973
            String docid = "";
974
            String qformat = "";
975
            String abstrpath = null;
976 731 bojilova
977 2098 jones
            // read the params
978
            if (params.containsKey("docid")) {
979
                docs = (String[]) params.get("docid");
980
            }
981
            if (params.containsKey("qformat")) {
982
                qformat = ((String[]) params.get("qformat"))[0];
983
            }
984
            // the param for only metadata (eml)
985 2245 sgarg
            // we don't support read a eml document without inline data now.
986
            /*if (params.containsKey("inlinedata")) {
987 1360 tao
988 2098 jones
                String inlineData = ((String[]) params.get("inlinedata"))[0];
989
                if (inlineData.equalsIgnoreCase("false")) {
990
                    withInlineData = false;
991
                }
992 2245 sgarg
            }*/
993 2098 jones
            if ((docs.length > 1) || qformat.equals("zip")) {
994
                zip = true;
995
                out = response.getOutputStream();
996
                response.setContentType("application/zip"); //MIME type
997
                zout = new ZipOutputStream(out);
998
            }
999
            // go through the list of docs to read
1000
            for (int i = 0; i < docs.length; i++) {
1001
                try {
1002 1360 tao
1003 2098 jones
                    URL murl = new URL(docs[i]);
1004 2099 jones
                    Hashtable murlQueryStr = MetaCatUtil.parseQuery(
1005
                            murl.getQuery());
1006 2098 jones
                    // case docid="http://.../?docid=aaa"
1007
                    // or docid="metacat://.../?docid=bbb"
1008
                    if (murlQueryStr.containsKey("docid")) {
1009
                        // get only docid, eliminate the rest
1010
                        docid = (String) murlQueryStr.get("docid");
1011
                        if (zip) {
1012 2102 jones
                            addDocToZip(request, docid, zout, user, groups);
1013 2098 jones
                        } else {
1014 2102 jones
                            readFromMetacat(request, response, docid, qformat,
1015 2098 jones
                                    abstrpath, user, groups, zip, zout,
1016
                                    withInlineData, params);
1017
                        }
1018 1360 tao
1019 2098 jones
                        // case docid="http://.../filename"
1020
                    } else {
1021
                        docid = docs[i];
1022
                        if (zip) {
1023 2102 jones
                            addDocToZip(request, docid, zout, user, groups);
1024 2098 jones
                        } else {
1025
                            readFromURLConnection(response, docid);
1026
                        }
1027
                    }
1028 2169 sgarg
1029 2098 jones
                } catch (MalformedURLException mue) {
1030
                    docid = docs[i];
1031
                    if (zip) {
1032 2102 jones
                        addDocToZip(request, docid, zout, user, groups);
1033 2098 jones
                    } else {
1034 2169 sgarg
                        readFromMetacat(request, response, docid, qformat,
1035
                                abstrpath, user, groups, zip, zout,
1036 2102 jones
                                withInlineData, params);
1037 2098 jones
                    }
1038
                }
1039 2099 jones
            }
1040 1360 tao
1041 2098 jones
            if (zip) {
1042
                zout.finish(); //terminate the zip file
1043
                zout.close(); //close the zip stream
1044
            }
1045 1360 tao
1046 2098 jones
        } catch (McdbDocNotFoundException notFoundE) {
1047
            // To handle doc not found exception
1048
            // the docid which didn't be found
1049
            String notFoundDocId = notFoundE.getUnfoundDocId();
1050
            String notFoundRevision = notFoundE.getUnfoundRevision();
1051
            MetaCatUtil.debugMessage("Missed id: " + notFoundDocId, 30);
1052
            MetaCatUtil.debugMessage("Missed rev: " + notFoundRevision, 30);
1053
            try {
1054
                // read docid from remote server
1055
                readFromRemoteMetaCat(response, notFoundDocId,
1056
                        notFoundRevision, user, passWord, out, zip, zout);
1057
                // Close zout outputstream
1058
                if (zout != null) {
1059
                    zout.close();
1060
                }
1061
                // close output stream
1062
                if (out != null) {
1063
                    out.close();
1064
                }
1065 1360 tao
1066 2098 jones
            } catch (Exception exc) {
1067
                MetaCatUtil.debugMessage(
1068
                        "Erorr in MetacatServlet.hanldReadAction: "
1069
                                + exc.getMessage(), 30);
1070
                try {
1071
                    if (out != null) {
1072
                        response.setContentType("text/xml");
1073
                        // Send back error message by printWriter
1074
                        pw = new PrintWriter(out);
1075
                        pw.println("<?xml version=\"1.0\"?>");
1076
                        pw.println("<error>");
1077
                        pw.println(notFoundE.getMessage());
1078
                        pw.println("</error>");
1079
                        pw.close();
1080
                        out.close();
1081 1360 tao
1082 2098 jones
                    } else {
1083
                        response.setContentType("text/xml"); //MIME type
1084
                        // Send back error message if out = null
1085
                        if (pw == null) {
1086
                            // If pw is null, open the respnose
1087
                            pw = response.getWriter();
1088
                        }
1089
                        pw.println("<?xml version=\"1.0\"?>");
1090
                        pw.println("<error>");
1091
                        pw.println(notFoundE.getMessage());
1092
                        pw.println("</error>");
1093
                        pw.close();
1094
                    }
1095
                    // close zout
1096
                    if (zout != null) {
1097
                        zout.close();
1098
                    }
1099
                } catch (IOException ie) {
1100
                    MetaCatUtil.debugMessage("Problem with the servlet output "
1101
                            + "in MetacatServlet.handleReadAction: "
1102
                            + ie.getMessage(), 30);
1103
                }
1104
            }
1105
        } catch (Exception e) {
1106
            try {
1107 1716 berkley
1108 2098 jones
                if (out != null) {
1109
                    response.setContentType("text/xml"); //MIME type
1110
                    pw = new PrintWriter(out);
1111
                    pw.println("<?xml version=\"1.0\"?>");
1112
                    pw.println("<error>");
1113
                    pw.println(e.getMessage());
1114
                    pw.println("</error>");
1115
                    pw.close();
1116
                    out.close();
1117
                } else {
1118
                    response.setContentType("text/xml"); //MIME type
1119
                    // Send back error message if out = null
1120
                    if (pw == null) {
1121
                        pw = response.getWriter();
1122
                    }
1123
                    pw.println("<?xml version=\"1.0\"?>");
1124
                    pw.println("<error>");
1125
                    pw.println(e.getMessage());
1126
                    pw.println("</error>");
1127
                    pw.close();
1128 1360 tao
1129 2098 jones
                }
1130
                // Close zip output stream
1131
                if (zout != null) {
1132
                    zout.close();
1133
                }
1134 1360 tao
1135 2098 jones
            } catch (IOException ioe) {
1136
                MetaCatUtil.debugMessage("Problem with the servlet output "
1137
                        + "in MetacatServlet.handleReadAction: "
1138
                        + ioe.getMessage(), 30);
1139
                ioe.printStackTrace(System.out);
1140 731 bojilova
1141 2098 jones
            }
1142 1360 tao
1143 2098 jones
            MetaCatUtil.debugMessage(
1144
                    "Error in MetacatServlet.handleReadAction: "
1145
                            + e.getMessage(), 30);
1146
            //e.printStackTrace(System.out);
1147 731 bojilova
        }
1148 2098 jones
    }
1149 1360 tao
1150 2169 sgarg
    /** read metadata or data from Metacat
1151 2098 jones
     */
1152 2169 sgarg
    private void readFromMetacat(HttpServletRequest request,
1153 2102 jones
            HttpServletResponse response, String docid, String qformat,
1154
            String abstrpath, String user, String[] groups, boolean zip,
1155
            ZipOutputStream zout, boolean withInlineData, Hashtable params)
1156
            throws ClassNotFoundException, IOException, SQLException,
1157
            McdbException, Exception
1158 1292 tao
    {
1159 1360 tao
1160 2098 jones
        try {
1161 1360 tao
1162 2098 jones
            DocumentImpl doc = new DocumentImpl(docid);
1163 1360 tao
1164 2098 jones
            //check the permission for read
1165 2113 jones
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1166 2098 jones
                Exception e = new Exception("User " + user
1167
                        + " does not have permission"
1168
                        + " to read the document with the docid " + docid);
1169 731 bojilova
1170 2098 jones
                throw e;
1171
            }
1172 1360 tao
1173 2098 jones
            if (doc.getRootNodeID() == 0) {
1174
                // this is data file
1175
                String filepath = MetaCatUtil.getOption("datafilepath");
1176
                if (!filepath.endsWith("/")) {
1177
                    filepath += "/";
1178
                }
1179
                String filename = filepath + docid;
1180
                FileInputStream fin = null;
1181
                fin = new FileInputStream(filename);
1182 1360 tao
1183 2098 jones
                //MIME type
1184
                String contentType = getServletContext().getMimeType(filename);
1185
                if (contentType == null) {
1186
                    ContentTypeProvider provider = new ContentTypeProvider(
1187
                            docid);
1188
                    contentType = provider.getContentType();
1189
                    MetaCatUtil.debugMessage("Final contenttype is: "
1190
                            + contentType, 30);
1191
                }
1192 731 bojilova
1193 2098 jones
                response.setContentType(contentType);
1194
                // if we decide to use "application/octet-stream" for all data
1195
                // returns
1196
                // response.setContentType("application/octet-stream");
1197 731 bojilova
1198 2098 jones
                try {
1199 731 bojilova
1200 2098 jones
                    ServletOutputStream out = response.getOutputStream();
1201
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
1202
                    int b = fin.read(buf);
1203
                    while (b != -1) {
1204
                        out.write(buf, 0, b);
1205
                        b = fin.read(buf);
1206
                    }
1207
                } finally {
1208
                    if (fin != null) fin.close();
1209
                }
1210 2169 sgarg
1211 2098 jones
            } else {
1212
                // this is metadata doc
1213
                if (qformat.equals("xml")) {
1214 1360 tao
1215 2098 jones
                    // set content type first
1216
                    response.setContentType("text/xml"); //MIME type
1217
                    PrintWriter out = response.getWriter();
1218
                    doc.toXml(out, user, groups, withInlineData);
1219
                } else {
1220
                    response.setContentType("text/html"); //MIME type
1221
                    PrintWriter out = response.getWriter();
1222 1360 tao
1223 2098 jones
                    // Look up the document type
1224
                    String doctype = doc.getDoctype();
1225
                    // Transform the document to the new doctype
1226
                    DBTransform dbt = new DBTransform();
1227
                    dbt.transformXMLDocument(doc.toString(user, groups,
1228
                            withInlineData), doctype, "-//W3C//HTML//EN",
1229
                            qformat, out, params);
1230
                }
1231 1360 tao
1232 2098 jones
            }
1233 2169 sgarg
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1234 2101 jones
                    docid, "read");
1235 2098 jones
        } catch (Exception except) {
1236
            throw except;
1237
        }
1238
    }
1239 1360 tao
1240 2169 sgarg
    /**
1241
     * read data from URLConnection
1242 2098 jones
     */
1243
    private void readFromURLConnection(HttpServletResponse response,
1244
            String docid) throws IOException, MalformedURLException
1245
    {
1246
        ServletOutputStream out = response.getOutputStream();
1247
        String contentType = getServletContext().getMimeType(docid); //MIME
1248
                                                                     // type
1249
        if (contentType == null) {
1250
            if (docid.endsWith(".xml")) {
1251
                contentType = "text/xml";
1252
            } else if (docid.endsWith(".css")) {
1253
                contentType = "text/css";
1254
            } else if (docid.endsWith(".dtd")) {
1255
                contentType = "text/plain";
1256
            } else if (docid.endsWith(".xsd")) {
1257
                contentType = "text/xml";
1258
            } else if (docid.endsWith("/")) {
1259
                contentType = "text/html";
1260
            } else {
1261
                File f = new File(docid);
1262
                if (f.isDirectory()) {
1263
                    contentType = "text/html";
1264
                } else {
1265
                    contentType = "application/octet-stream";
1266
                }
1267
            }
1268 1360 tao
        }
1269 2098 jones
        response.setContentType(contentType);
1270
        // if we decide to use "application/octet-stream" for all data returns
1271
        // response.setContentType("application/octet-stream");
1272 1360 tao
1273 2098 jones
        // this is http url
1274
        URL url = new URL(docid);
1275
        BufferedInputStream bis = null;
1276
        try {
1277
            bis = new BufferedInputStream(url.openStream());
1278 731 bojilova
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1279 2098 jones
            int b = bis.read(buf);
1280 731 bojilova
            while (b != -1) {
1281 2098 jones
                out.write(buf, 0, b);
1282
                b = bis.read(buf);
1283 731 bojilova
            }
1284 2098 jones
        } finally {
1285
            if (bis != null) bis.close();
1286 636 berkley
        }
1287 1360 tao
1288 636 berkley
    }
1289 1360 tao
1290 2169 sgarg
    /**
1291 2098 jones
     * read file/doc and write to ZipOutputStream
1292 2169 sgarg
     *
1293 2098 jones
     * @param docid
1294
     * @param zout
1295
     * @param user
1296
     * @param groups
1297
     * @throws ClassNotFoundException
1298
     * @throws IOException
1299
     * @throws SQLException
1300
     * @throws McdbException
1301
     * @throws Exception
1302
     */
1303 2169 sgarg
    private void addDocToZip(HttpServletRequest request, String docid,
1304 2102 jones
            ZipOutputStream zout, String user, String[] groups) throws
1305
            ClassNotFoundException, IOException, SQLException, McdbException,
1306
            Exception
1307 1293 tao
    {
1308 2098 jones
        byte[] bytestring = null;
1309
        ZipEntry zentry = null;
1310 1360 tao
1311 598 bojilova
        try {
1312 2098 jones
            URL url = new URL(docid);
1313 1360 tao
1314 2098 jones
            // this http url; read from URLConnection; add to zip
1315
            zentry = new ZipEntry(docid);
1316
            zout.putNextEntry(zentry);
1317
            BufferedInputStream bis = null;
1318
            try {
1319
                bis = new BufferedInputStream(url.openStream());
1320
                byte[] buf = new byte[4 * 1024]; // 4K buffer
1321
                int b = bis.read(buf);
1322
                while (b != -1) {
1323
                    zout.write(buf, 0, b);
1324
                    b = bis.read(buf);
1325
                }
1326
            } finally {
1327
                if (bis != null) bis.close();
1328
            }
1329
            zout.closeEntry();
1330 1716 berkley
1331 2098 jones
        } catch (MalformedURLException mue) {
1332 203 jones
1333 2098 jones
            // this is metacat doc (data file or metadata doc)
1334
            try {
1335
                DocumentImpl doc = new DocumentImpl(docid);
1336 1360 tao
1337 2098 jones
                //check the permission for read
1338 2113 jones
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1339 2098 jones
                    Exception e = new Exception("User " + user
1340
                            + " does not have "
1341
                            + "permission to read the document with the docid "
1342
                            + docid);
1343
                    throw e;
1344
                }
1345 1360 tao
1346 2098 jones
                if (doc.getRootNodeID() == 0) {
1347
                    // this is data file; add file to zip
1348
                    String filepath = MetaCatUtil.getOption("datafilepath");
1349
                    if (!filepath.endsWith("/")) {
1350
                        filepath += "/";
1351
                    }
1352
                    String filename = filepath + docid;
1353
                    FileInputStream fin = null;
1354
                    fin = new FileInputStream(filename);
1355
                    try {
1356 1360 tao
1357 2098 jones
                        zentry = new ZipEntry(docid);
1358
                        zout.putNextEntry(zentry);
1359
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
1360
                        int b = fin.read(buf);
1361
                        while (b != -1) {
1362
                            zout.write(buf, 0, b);
1363
                            b = fin.read(buf);
1364
                        }
1365
                    } finally {
1366
                        if (fin != null) fin.close();
1367
                    }
1368
                    zout.closeEntry();
1369 1716 berkley
1370 2098 jones
                } else {
1371
                    // this is metadata doc; add doc to zip
1372
                    bytestring = doc.toString().getBytes();
1373
                    zentry = new ZipEntry(docid + ".xml");
1374
                    zentry.setSize(bytestring.length);
1375
                    zout.putNextEntry(zentry);
1376
                    zout.write(bytestring, 0, bytestring.length);
1377
                    zout.closeEntry();
1378
                }
1379 2169 sgarg
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1380 2101 jones
                        docid, "read");
1381 2098 jones
            } catch (Exception except) {
1382
                throw except;
1383
            }
1384 1360 tao
        }
1385 2098 jones
    }
1386 309 bojilova
1387 2098 jones
    /**
1388
     * If metacat couldn't find a data file or document locally, it will read
1389
     * this docid from its home server. This is for the replication feature
1390
     */
1391
    private void readFromRemoteMetaCat(HttpServletResponse response,
1392
            String docid, String rev, String user, String password,
1393
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
1394
            throws Exception
1395 1466 tao
    {
1396 2098 jones
        // Create a object of RemoteDocument, "" is for zipEntryPath
1397
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
1398
                password, "");
1399
        String docType = remoteDoc.getDocType();
1400
        // Only read data file
1401
        if (docType.equals("BIN")) {
1402
            // If it is zip format
1403
            if (zip) {
1404
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
1405
            } else {
1406
                if (out == null) {
1407
                    out = response.getOutputStream();
1408
                }
1409
                response.setContentType("application/octet-stream");
1410
                remoteDoc.readDocumentFromRemoteServer(out);
1411
            }
1412
        } else {
1413
            throw new Exception("Docid: " + docid + "." + rev
1414
                    + " couldn't find");
1415
        }
1416 203 jones
    }
1417
1418 2098 jones
    /**
1419
     * Handle the database putdocument request and write an XML document to the
1420
     * database connection
1421
     */
1422 2102 jones
    private void handleInsertOrUpdateAction(HttpServletRequest request,
1423
            HttpServletResponse response, PrintWriter out, Hashtable params,
1424 2098 jones
            String user, String[] groups)
1425
    {
1426
        DBConnection dbConn = null;
1427
        int serialNumber = -1;
1428 1360 tao
1429 2098 jones
        try {
1430
            // Get the document indicated
1431
            String[] doctext = (String[]) params.get("doctext");
1432 2089 tao
1433 2098 jones
            String pub = null;
1434
            if (params.containsKey("public")) {
1435
                pub = ((String[]) params.get("public"))[0];
1436
            }
1437 1360 tao
1438 2098 jones
            StringReader dtd = null;
1439
            if (params.containsKey("dtdtext")) {
1440
                String[] dtdtext = (String[]) params.get("dtdtext");
1441
                try {
1442
                    if (!dtdtext[0].equals("")) {
1443
                        dtd = new StringReader(dtdtext[0]);
1444
                    }
1445
                } catch (NullPointerException npe) {
1446
                }
1447
            }
1448 695 bojilova
1449 2098 jones
            StringReader xml = new StringReader(doctext[0]);
1450
            boolean validate = false;
1451
            DocumentImplWrapper documentWrapper = null;
1452
            try {
1453
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1454
                // >
1455
                // in order to decide whether to use validation parser
1456
                validate = needDTDValidation(xml);
1457
                if (validate) {
1458
                    // set a dtd base validation parser
1459
                    String rule = DocumentImpl.DTD;
1460
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1461
                } else if (needSchemaValidation(xml)) {
1462
                    // for eml2
1463 2169 sgarg
                    String namespace = findNamespace(xml);
1464 2224 sgarg
                    if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1465
                                || namespace.compareTo(
1466
                                DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1467 2098 jones
                        // set eml2 base validation parser
1468 2163 tao
                        String rule = DocumentImpl.EML200;
1469 2098 jones
                        // using emlparser to check id validation
1470
                        EMLParser parser = new EMLParser(doctext[0]);
1471
                        documentWrapper = new DocumentImplWrapper(rule, true);
1472 2169 sgarg
                    } else if (namespace.compareTo(
1473
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1474
                        // set eml2 base validation parser
1475
                        String rule = DocumentImpl.EML210;
1476
                        // using emlparser to check id validation
1477
                        EMLParser parser = new EMLParser(doctext[0]);
1478
                        documentWrapper = new DocumentImplWrapper(rule, true);
1479 2098 jones
                    } else {
1480
                        // set schema base validation parser
1481
                        String rule = DocumentImpl.SCHEMA;
1482
                        documentWrapper = new DocumentImplWrapper(rule, true);
1483
                    }
1484
                } else {
1485
                    documentWrapper = new DocumentImplWrapper("", false);
1486
                }
1487 695 bojilova
1488 2098 jones
                String[] action = (String[]) params.get("action");
1489
                String[] docid = (String[]) params.get("docid");
1490
                String newdocid = null;
1491 695 bojilova
1492 2098 jones
                String doAction = null;
1493
                if (action[0].equals("insert")) {
1494
                    doAction = "INSERT";
1495
                } else if (action[0].equals("update")) {
1496
                    doAction = "UPDATE";
1497
                }
1498 695 bojilova
1499 2098 jones
                try {
1500
                    // get a connection from the pool
1501
                    dbConn = DBConnectionPool
1502
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1503
                    serialNumber = dbConn.getCheckOutSerialNumber();
1504 1716 berkley
1505 2098 jones
                    // write the document to the database
1506
                    try {
1507
                        String accNumber = docid[0];
1508
                        MetaCatUtil.debugMessage("" + doAction + " "
1509
                                + accNumber + "...", 10);
1510
                        if (accNumber.equals("")) {
1511
                            accNumber = null;
1512 2102 jones
                        }
1513 2098 jones
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1514
                                doAction, accNumber, user, groups);
1515 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
1516 2102 jones
                                user, accNumber, action[0]);
1517
                    } catch (NullPointerException npe) {
1518 2098 jones
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1519
                                doAction, null, user, groups);
1520 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
1521 2102 jones
                                user, "", action[0]);
1522
                    }
1523
                }
1524 2098 jones
                finally {
1525
                    // Return db connection
1526
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1527
                }
1528 1716 berkley
1529 2098 jones
                // set content type and other response header fields first
1530
                //response.setContentType("text/xml");
1531
                out.println("<?xml version=\"1.0\"?>");
1532
                out.println("<success>");
1533
                out.println("<docid>" + newdocid + "</docid>");
1534
                out.println("</success>");
1535 1716 berkley
1536 2098 jones
            } catch (NullPointerException npe) {
1537
                //response.setContentType("text/xml");
1538
                out.println("<?xml version=\"1.0\"?>");
1539
                out.println("<error>");
1540
                out.println(npe.getMessage());
1541
                out.println("</error>");
1542
            }
1543
        } catch (Exception e) {
1544
            //response.setContentType("text/xml");
1545
            out.println("<?xml version=\"1.0\"?>");
1546
            out.println("<error>");
1547
            out.println(e.getMessage());
1548
            out.println("</error>");
1549 1760 tao
        }
1550 1409 tao
    }
1551 1716 berkley
1552 2098 jones
    /**
1553
     * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > in
1554
     * order to decide whether to use validation parser
1555
     */
1556
    private static boolean needDTDValidation(StringReader xmlreader)
1557
            throws IOException
1558 1629 tao
    {
1559 2089 tao
1560 2098 jones
        StringBuffer cbuff = new StringBuffer();
1561
        java.util.Stack st = new java.util.Stack();
1562
        boolean validate = false;
1563
        int c;
1564
        int inx;
1565 2089 tao
1566 2098 jones
        // read from the stream until find the keywords
1567
        while ((st.empty() || st.size() < 4) && ((c = xmlreader.read()) != -1)) {
1568
            cbuff.append((char) c);
1569 1716 berkley
1570 2098 jones
            // "<!DOCTYPE" keyword is found; put it in the stack
1571
            if ((inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1) {
1572
                cbuff = new StringBuffer();
1573
                st.push("<!DOCTYPE");
1574
            }
1575
            // "PUBLIC" keyword is found; put it in the stack
1576
            if ((inx = cbuff.toString().indexOf("PUBLIC")) != -1) {
1577
                cbuff = new StringBuffer();
1578
                st.push("PUBLIC");
1579
            }
1580
            // "SYSTEM" keyword is found; put it in the stack
1581
            if ((inx = cbuff.toString().indexOf("SYSTEM")) != -1) {
1582
                cbuff = new StringBuffer();
1583
                st.push("SYSTEM");
1584
            }
1585
            // ">" character is found; put it in the stack
1586
            // ">" is found twice: fisrt from <?xml ...?>
1587
            // and second from <!DOCTYPE ... >
1588
            if ((inx = cbuff.toString().indexOf(">")) != -1) {
1589
                cbuff = new StringBuffer();
1590
                st.push(">");
1591
            }
1592
        }
1593 203 jones
1594 2098 jones
        // close the stream
1595
        xmlreader.reset();
1596 1360 tao
1597 2098 jones
        // check the stack whether it contains the keywords:
1598
        // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1599
        if (st.size() == 4) {
1600
            if (((String) st.pop()).equals(">")
1601
                    && (((String) st.peek()).equals("PUBLIC") | ((String) st
1602
                            .pop()).equals("SYSTEM"))
1603
                    && ((String) st.pop()).equals("<!DOCTYPE")) {
1604
                validate = true;
1605
            }
1606
        }
1607 1360 tao
1608 2098 jones
        MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1609
        return validate;
1610 1360 tao
    }
1611
1612 2098 jones
    // END OF INSERT/UPDATE SECTION
1613 68 higgins
1614 2098 jones
    /* check if the xml string contains key words to specify schema loocation */
1615
    private boolean needSchemaValidation(StringReader xml) throws IOException
1616
    {
1617
        boolean needSchemaValidate = false;
1618
        if (xml == null) {
1619
            MetaCatUtil.debugMessage("Validation for schema is "
1620
                    + needSchemaValidate, 10);
1621
            return needSchemaValidate;
1622
        }
1623
        System.out.println("before get target line");
1624
        String targetLine = getSchemaLine(xml);
1625
        System.out.println("before get target line");
1626
        // to see if the second line contain some keywords
1627
        if (targetLine != null
1628
                && (targetLine.indexOf(SCHEMALOCATIONKEYWORD) != -1 || targetLine
1629
                        .indexOf(NONAMESPACELOCATION) != -1)) {
1630
            // if contains schema location key word, should be validate
1631
            needSchemaValidate = true;
1632
        }
1633 1360 tao
1634 2098 jones
        MetaCatUtil.debugMessage("Validation for schema is "
1635
                + needSchemaValidate, 10);
1636
        return needSchemaValidate;
1637 68 higgins
1638 2098 jones
    }
1639 1360 tao
1640 2098 jones
    /* check if the xml string contains key words to specify schema loocation */
1641 2169 sgarg
    private String findNamespace(StringReader xml) throws IOException
1642 2098 jones
    {
1643 2169 sgarg
        String namespace = null;
1644
1645
        String eml2_0_0NameSpace = DocumentImpl.EML2_0_0NAMESPACE;
1646 2224 sgarg
        String eml2_0_1NameSpace = DocumentImpl.EML2_0_1NAMESPACE;
1647 2169 sgarg
        String eml2_1_0NameSpace = DocumentImpl.EML2_1_0NAMESPACE;
1648
1649 2098 jones
        if (xml == null) {
1650
            MetaCatUtil.debugMessage("Validation for schema is "
1651 2169 sgarg
                    + namespace, 10);
1652
            return namespace;
1653 2098 jones
        }
1654
        String targetLine = getSchemaLine(xml);
1655 309 bojilova
1656 2098 jones
        if (targetLine != null) {
1657 1360 tao
1658 2098 jones
            int startIndex = targetLine.indexOf(SCHEMALOCATIONKEYWORD);
1659
            int start = 1;
1660
            int end = 1;
1661
            String schemaLocation = null;
1662
            int count = 0;
1663
            if (startIndex != -1) {
1664
                for (int i = startIndex; i < targetLine.length(); i++) {
1665
                    if (targetLine.charAt(i) == '"') {
1666
                        count++;
1667
                    }
1668
                    if (targetLine.charAt(i) == '"' && count == 1) {
1669
                        start = i;
1670
                    }
1671
                    if (targetLine.charAt(i) == '"' && count == 2) {
1672
                        end = i;
1673
                        break;
1674
                    }
1675
                }
1676
            }
1677
            schemaLocation = targetLine.substring(start + 1, end);
1678
            MetaCatUtil.debugMessage("schemaLocation in xml is: "
1679
                    + schemaLocation, 30);
1680 2169 sgarg
            if (schemaLocation.indexOf(eml2_0_0NameSpace) != -1) {
1681
                namespace = eml2_0_0NameSpace;
1682 2224 sgarg
            } else if (schemaLocation.indexOf(eml2_0_1NameSpace) != -1) {
1683
                namespace = eml2_0_1NameSpace;
1684 2169 sgarg
            } else if (schemaLocation.indexOf(eml2_1_0NameSpace) != -1) {
1685
                namespace = eml2_1_0NameSpace;
1686 2098 jones
            }
1687
        }
1688 185 jones
1689 2169 sgarg
        MetaCatUtil.debugMessage("Validation for eml is " + namespace,
1690 2098 jones
                10);
1691 2224 sgarg
1692 2169 sgarg
        return namespace;
1693 1360 tao
1694 103 jones
    }
1695 68 higgins
1696 2098 jones
    private String getSchemaLine(StringReader xml) throws IOException
1697
    {
1698
        // find the line
1699
        String secondLine = null;
1700
        int count = 0;
1701
        int endIndex = 0;
1702
        int startIndex = 0;
1703
        final int TARGETNUM = 2;
1704
        StringBuffer buffer = new StringBuffer();
1705
        boolean comment = false;
1706
        char thirdPreviousCharacter = '?';
1707
        char secondPreviousCharacter = '?';
1708
        char previousCharacter = '?';
1709
        char currentCharacter = '?';
1710 1360 tao
1711 2098 jones
        while ((currentCharacter = (char) xml.read()) != -1) {
1712
            //in a comment
1713
            if (currentCharacter == '-' && previousCharacter == '-'
1714
                    && secondPreviousCharacter == '!'
1715
                    && thirdPreviousCharacter == '<') {
1716
                comment = true;
1717
            }
1718
            //out of comment
1719
            if (comment && currentCharacter == '>' && previousCharacter == '-'
1720
                    && secondPreviousCharacter == '-') {
1721
                comment = false;
1722
            }
1723 68 higgins
1724 2098 jones
            //this is not comment
1725
            if (currentCharacter != '!' && previousCharacter == '<' && !comment) {
1726
                count++;
1727
            }
1728
            // get target line
1729
            if (count == TARGETNUM && currentCharacter != '>') {
1730
                buffer.append(currentCharacter);
1731
            }
1732
            if (count == TARGETNUM && currentCharacter == '>') {
1733
                break;
1734
            }
1735
            thirdPreviousCharacter = secondPreviousCharacter;
1736
            secondPreviousCharacter = previousCharacter;
1737
            previousCharacter = currentCharacter;
1738 1360 tao
1739 2098 jones
        }
1740
        secondLine = buffer.toString();
1741
        MetaCatUtil
1742
                .debugMessage("the second line string is: " + secondLine, 25);
1743
        xml.reset();
1744
        return secondLine;
1745
    }
1746 253 jones
1747 2098 jones
    /**
1748
     * Handle the database delete request and delete an XML document from the
1749
     * database connection
1750
     */
1751
    private void handleDeleteAction(PrintWriter out, Hashtable params,
1752 2169 sgarg
            HttpServletRequest request, HttpServletResponse response,
1753 2102 jones
            String user, String[] groups)
1754 2098 jones
    {
1755 1360 tao
1756 2098 jones
        String[] docid = (String[]) params.get("docid");
1757 1360 tao
1758 2098 jones
        // delete the document from the database
1759
        try {
1760 1360 tao
1761 2098 jones
            // NOTE -- NEED TO TEST HERE
1762
            // FOR EXISTENCE OF DOCID PARAM
1763
            // BEFORE ACCESSING ARRAY
1764
            try {
1765
                DocumentImpl.delete(docid[0], user, groups);
1766 2169 sgarg
                EventLog.getInstance().log(request.getRemoteAddr(),
1767 2102 jones
                    user, docid[0], "delete");
1768 2098 jones
                response.setContentType("text/xml");
1769
                out.println("<?xml version=\"1.0\"?>");
1770
                out.println("<success>");
1771
                out.println("Document deleted.");
1772
                out.println("</success>");
1773
            } catch (AccessionNumberException ane) {
1774
                response.setContentType("text/xml");
1775
                out.println("<?xml version=\"1.0\"?>");
1776
                out.println("<error>");
1777
                out.println("Error deleting document!!!");
1778
                out.println(ane.getMessage());
1779
                out.println("</error>");
1780
            }
1781
        } catch (Exception e) {
1782
            response.setContentType("text/xml");
1783
            out.println("<?xml version=\"1.0\"?>");
1784
            out.println("<error>");
1785
            out.println(e.getMessage());
1786
            out.println("</error>");
1787
        }
1788 1292 tao
    }
1789 1360 tao
1790 2098 jones
    /**
1791
     * Handle the validation request and return the results to the requestor
1792
     */
1793
    private void handleValidateAction(PrintWriter out, Hashtable params)
1794 1292 tao
    {
1795 1360 tao
1796 2098 jones
        // Get the document indicated
1797
        String valtext = null;
1798
        DBConnection dbConn = null;
1799
        int serialNumber = -1;
1800 1292 tao
1801 2098 jones
        try {
1802
            valtext = ((String[]) params.get("valtext"))[0];
1803
        } catch (Exception nullpe) {
1804 1360 tao
1805 2098 jones
            String docid = null;
1806
            try {
1807
                // Find the document id number
1808
                docid = ((String[]) params.get("docid"))[0];
1809 1360 tao
1810 2098 jones
                // Get the document indicated from the db
1811
                DocumentImpl xmldoc = new DocumentImpl(docid);
1812
                valtext = xmldoc.toString();
1813 688 bojilova
1814 2098 jones
            } catch (NullPointerException npe) {
1815 1360 tao
1816 2098 jones
                out.println("<error>Error getting document ID: " + docid
1817
                        + "</error>");
1818
                //if ( conn != null ) { util.returnConnection(conn); }
1819
                return;
1820
            } catch (Exception e) {
1821 688 bojilova
1822 2098 jones
                out.println(e.getMessage());
1823
            }
1824
        }
1825 688 bojilova
1826 2098 jones
        try {
1827
            // get a connection from the pool
1828
            dbConn = DBConnectionPool
1829
                    .getDBConnection("MetaCatServlet.handleValidateAction");
1830
            serialNumber = dbConn.getCheckOutSerialNumber();
1831
            DBValidate valobj = new DBValidate(saxparser, dbConn);
1832
            boolean valid = valobj.validateString(valtext);
1833 1360 tao
1834 2098 jones
            // set content type and other response header fields first
1835 688 bojilova
1836 2098 jones
            out.println(valobj.returnErrors());
1837 731 bojilova
1838 2098 jones
        } catch (NullPointerException npe2) {
1839
            // set content type and other response header fields first
1840 1360 tao
1841 2098 jones
            out.println("<error>Error validating document.</error>");
1842
        } catch (Exception e) {
1843 731 bojilova
1844 2098 jones
            out.println(e.getMessage());
1845
        } finally {
1846
            // Return db connection
1847
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1848
        }
1849
    }
1850 1360 tao
1851 2098 jones
    /**
1852
     * Handle "getrevsionanddoctype" action Given a docid, return it's current
1853
     * revision and doctype from data base The output is String look like
1854
     * "rev;doctype"
1855
     */
1856
    private void handleGetRevisionAndDocTypeAction(PrintWriter out,
1857
            Hashtable params)
1858
    {
1859
        // To store doc parameter
1860
        String[] docs = new String[10];
1861
        // Store a single doc id
1862
        String givenDocId = null;
1863
        // Get docid from parameters
1864
        if (params.containsKey("docid")) {
1865
            docs = (String[]) params.get("docid");
1866
        }
1867
        // Get first docid form string array
1868
        givenDocId = docs[0];
1869 731 bojilova
1870 2098 jones
        try {
1871
            // Make sure there is a docid
1872
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
1873
                    "User didn't specify docid!"); }//if
1874 1360 tao
1875 2098 jones
            // Create a DBUtil object
1876
            DBUtil dbutil = new DBUtil();
1877
            // Get a rev and doctype
1878
            String revAndDocType = dbutil
1879
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1880
            out.println(revAndDocType);
1881 731 bojilova
1882 2098 jones
        } catch (Exception e) {
1883
            // Handle exception
1884
            out.println("<?xml version=\"1.0\"?>");
1885
            out.println("<error>");
1886
            out.println(e.getMessage());
1887
            out.println("</error>");
1888
        }
1889 302 bojilova
1890 2098 jones
    }
1891 1360 tao
1892 2098 jones
    /**
1893
     * Handle "getaccesscontrol" action. Read Access Control List from db
1894
     * connection in XML format
1895
     */
1896
    private void handleGetAccessControlAction(PrintWriter out,
1897
            Hashtable params, HttpServletResponse response, String username,
1898
            String[] groupnames)
1899
    {
1900
        DBConnection dbConn = null;
1901
        int serialNumber = -1;
1902
        String docid = ((String[]) params.get("docid"))[0];
1903 302 bojilova
1904 2098 jones
        try {
1905 1360 tao
1906 2098 jones
            // get connection from the pool
1907
            dbConn = DBConnectionPool
1908
                    .getDBConnection("MetaCatServlet.handleGetAccessControlAction");
1909
            serialNumber = dbConn.getCheckOutSerialNumber();
1910
            AccessControlList aclobj = new AccessControlList(dbConn);
1911
            String acltext = aclobj.getACL(docid, username, groupnames);
1912
            out.println(acltext);
1913 302 bojilova
1914 2098 jones
        } catch (Exception e) {
1915
            out.println("<?xml version=\"1.0\"?>");
1916
            out.println("<error>");
1917
            out.println(e.getMessage());
1918
            out.println("</error>");
1919
        } finally {
1920
            // Retrun db connection to pool
1921
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1922
        }
1923 1360 tao
    }
1924
1925 2098 jones
    /**
1926
     * Handle the "getprincipals" action. Read all principals from
1927
     * authentication scheme in XML format
1928
     */
1929
    private void handleGetPrincipalsAction(PrintWriter out, String user,
1930
            String password)
1931
    {
1932
        try {
1933
            AuthSession auth = new AuthSession();
1934
            String principals = auth.getPrincipals(user, password);
1935
            out.println(principals);
1936 302 bojilova
1937 2098 jones
        } catch (Exception e) {
1938
            out.println("<?xml version=\"1.0\"?>");
1939
            out.println("<error>");
1940
            out.println(e.getMessage());
1941
            out.println("</error>");
1942
        }
1943
    }
1944 699 bojilova
1945 2098 jones
    /**
1946
     * Handle "getdoctypes" action. Read all doctypes from db connection in XML
1947
     * format
1948
     */
1949
    private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1950
            HttpServletResponse response)
1951
    {
1952
        try {
1953
            DBUtil dbutil = new DBUtil();
1954
            String doctypes = dbutil.readDoctypes();
1955
            out.println(doctypes);
1956
        } catch (Exception e) {
1957
            out.println("<?xml version=\"1.0\"?>");
1958
            out.println("<error>");
1959
            out.println(e.getMessage());
1960
            out.println("</error>");
1961
        }
1962
    }
1963 1360 tao
1964 2098 jones
    /**
1965
     * Handle the "getdtdschema" action. Read DTD or Schema file for a given
1966
     * doctype from Metacat catalog system
1967
     */
1968
    private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1969
            HttpServletResponse response)
1970
    {
1971 699 bojilova
1972 2098 jones
        String doctype = null;
1973
        String[] doctypeArr = (String[]) params.get("doctype");
1974 699 bojilova
1975 2098 jones
        // get only the first doctype specified in the list of doctypes
1976
        // it could be done for all doctypes in that list
1977
        if (doctypeArr != null) {
1978
            doctype = ((String[]) params.get("doctype"))[0];
1979
        }
1980 699 bojilova
1981 2098 jones
        try {
1982
            DBUtil dbutil = new DBUtil();
1983
            String dtdschema = dbutil.readDTDSchema(doctype);
1984
            out.println(dtdschema);
1985 1360 tao
1986 2098 jones
        } catch (Exception e) {
1987
            out.println("<?xml version=\"1.0\"?>");
1988
            out.println("<error>");
1989
            out.println(e.getMessage());
1990
            out.println("</error>");
1991
        }
1992 699 bojilova
1993 1360 tao
    }
1994
1995 2098 jones
    /**
1996
     * Handle the "getlastdocid" action. Get the latest docid with rev number
1997
     * from db connection in XML format
1998
     */
1999
    private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2000
            HttpServletResponse response)
2001
    {
2002 699 bojilova
2003 2098 jones
        String scope = ((String[]) params.get("scope"))[0];
2004
        if (scope == null) {
2005
            scope = ((String[]) params.get("username"))[0];
2006
        }
2007 793 bojilova
2008 2098 jones
        try {
2009 1217 tao
2010 2098 jones
            DBUtil dbutil = new DBUtil();
2011
            String lastDocid = dbutil.getMaxDocid(scope);
2012
            out.println("<?xml version=\"1.0\"?>");
2013
            out.println("<lastDocid>");
2014
            out.println("  <scope>" + scope + "</scope>");
2015
            out.println("  <docid>" + lastDocid + "</docid>");
2016
            out.println("</lastDocid>");
2017 793 bojilova
2018 2098 jones
        } catch (Exception e) {
2019
            out.println("<?xml version=\"1.0\"?>");
2020
            out.println("<error>");
2021
            out.println(e.getMessage());
2022
            out.println("</error>");
2023
        }
2024 1217 tao
    }
2025 1360 tao
2026 2098 jones
    /**
2027 2113 jones
     * Print a report from the event log based on filter parameters passed in
2028
     * from the web.
2029 2169 sgarg
     *
2030 2113 jones
     * TODO: make sure urlencoding of timestamp params is working
2031 2169 sgarg
     *
2032 2113 jones
     * @param params the parameters from the web request
2033
     * @param request the http request object for getting request details
2034
     * @param response the http response object for writing output
2035
     */
2036
    private void handleGetLogAction(Hashtable params, HttpServletRequest request,
2037
            HttpServletResponse response)
2038
    {
2039
        // Get all of the parameters in the correct formats
2040
        String[] ipAddress = (String[])params.get("ipaddress");
2041
        String[] principal = (String[])params.get("principal");
2042
        String[] docid = (String[])params.get("docid");
2043
        String[] event = (String[])params.get("event");
2044
        String[] startArray = (String[]) params.get("start");
2045
        String[] endArray = (String[]) params.get("end");
2046
        String start = null;
2047
        String end = null;
2048
        if (startArray != null) {
2049
            start = startArray[0];
2050
        }
2051
        if (endArray != null) {
2052
            end = endArray[0];
2053
        }
2054
        Timestamp startDate = null;
2055
        Timestamp endDate = null;
2056
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2057
        try {
2058
            if (start != null) {
2059
                startDate = new Timestamp((format.parse(start)).getTime());
2060
            }
2061
            if (end != null) {
2062
                endDate = new Timestamp((format.parse(end)).getTime());
2063
            }
2064
        } catch (ParseException e) {
2065
            System.out.println("Failed to created Timestamp from input.");
2066
        }
2067 2169 sgarg
2068 2113 jones
        // Request the report by passing the filter parameters
2069
        try {
2070
            response.setContentType("text/xml");
2071
            PrintWriter out = response.getWriter();
2072 2169 sgarg
            out.println(EventLog.getInstance().getReport(ipAddress, principal,
2073 2113 jones
                    docid, event, startDate, endDate));
2074
            out.close();
2075
        } catch (IOException e) {
2076
            MetaCatUtil.debugMessage(
2077 2169 sgarg
                    "Could not open http response for writing: "
2078 2113 jones
                    + e.getMessage(), 5);
2079
        }
2080
    }
2081 2169 sgarg
2082 2113 jones
    /**
2083 2098 jones
     * Handle documents passed to metacat that are encoded using the
2084
     * "multipart/form-data" mime type. This is typically used for uploading
2085
     * data files which may be binary and large.
2086
     */
2087
    private void handleMultipartForm(HttpServletRequest request,
2088
            HttpServletResponse response)
2089
    {
2090
        PrintWriter out = null;
2091
        String action = null;
2092 793 bojilova
2093 2098 jones
        // Parse the multipart form, and save the parameters in a Hashtable and
2094
        // save the FileParts in a hashtable
2095 798 jones
2096 2098 jones
        Hashtable params = new Hashtable();
2097
        Hashtable fileList = new Hashtable();
2098
        int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2099
                .intValue();
2100
        MetaCatUtil.debugMessage(
2101
                "The limit size of data file is: " + sizeLimit, 50);
2102 798 jones
2103 2098 jones
        try {
2104
            // MBJ: need to put filesize limit in Metacat config
2105
            // (metacat.properties)
2106
            MultipartParser mp = new MultipartParser(request,
2107
                    sizeLimit * 1024 * 1024);
2108
            Part part;
2109
            while ((part = mp.readNextPart()) != null) {
2110
                String name = part.getName();
2111 798 jones
2112 2098 jones
                if (part.isParam()) {
2113
                    // it's a parameter part
2114
                    ParamPart paramPart = (ParamPart) part;
2115
                    String value = paramPart.getStringValue();
2116
                    params.put(name, value);
2117
                    if (name.equals("action")) {
2118
                        action = value;
2119
                    }
2120
                } else if (part.isFile()) {
2121
                    // it's a file part
2122
                    FilePart filePart = (FilePart) part;
2123
                    fileList.put(name, filePart);
2124 798 jones
2125 2098 jones
                    // Stop once the first file part is found, otherwise going
2126
                    // onto the
2127
                    // next part prevents access to the file contents. So...for
2128
                    // upload
2129
                    // to work, the datafile must be the last part
2130
                    break;
2131
                }
2132
            }
2133
        } catch (IOException ioe) {
2134
            try {
2135
                out = response.getWriter();
2136
            } catch (IOException ioe2) {
2137
                System.err
2138
                        .println("Fatal Error: couldn't get response output stream.");
2139
            }
2140
            out.println("<?xml version=\"1.0\"?>");
2141
            out.println("<error>");
2142
            out.println("Error: problem reading multipart data.");
2143
            out.println("</error>");
2144 798 jones
        }
2145
2146 2098 jones
        // Get the session information
2147
        String username = null;
2148
        String password = null;
2149
        String[] groupnames = null;
2150
        String sess_id = null;
2151 798 jones
2152 2098 jones
        // be aware of session expiration on every request
2153
        HttpSession sess = request.getSession(true);
2154
        if (sess.isNew()) {
2155
            // session expired or has not been stored b/w user requests
2156
            username = "public";
2157
            sess.setAttribute("username", username);
2158
        } else {
2159
            username = (String) sess.getAttribute("username");
2160
            password = (String) sess.getAttribute("password");
2161
            groupnames = (String[]) sess.getAttribute("groupnames");
2162
            try {
2163
                sess_id = (String) sess.getId();
2164
            } catch (IllegalStateException ise) {
2165
                System.out
2166
                        .println("error in  handleMultipartForm: this shouldn't "
2167
                                + "happen: the session should be valid: "
2168
                                + ise.getMessage());
2169
            }
2170
        }
2171 1360 tao
2172 2098 jones
        // Get the out stream
2173
        try {
2174
            out = response.getWriter();
2175 798 jones
        } catch (IOException ioe2) {
2176 2098 jones
            MetaCatUtil.debugMessage("Fatal Error: couldn't get response "
2177
                    + "output stream.", 30);
2178 798 jones
        }
2179 1360 tao
2180 2098 jones
        if (action.equals("upload")) {
2181
            if (username != null && !username.equals("public")) {
2182
                handleUploadAction(request, out, params, fileList, username,
2183
                        groupnames);
2184
            } else {
2185 1360 tao
2186 2098 jones
                out.println("<?xml version=\"1.0\"?>");
2187
                out.println("<error>");
2188
                out.println("Permission denied for " + action);
2189
                out.println("</error>");
2190
            }
2191
        } else {
2192
            /*
2193
             * try { out = response.getWriter(); } catch (IOException ioe2) {
2194
             * System.err.println("Fatal Error: couldn't get response output
2195
             * stream.");
2196
             */
2197
            out.println("<?xml version=\"1.0\"?>");
2198
            out.println("<error>");
2199
            out.println(
2200
                    "Error: action not registered.  Please report this error.");
2201
            out.println("</error>");
2202
        }
2203
        out.close();
2204 798 jones
    }
2205
2206 2098 jones
    /**
2207
     * Handle the upload action by saving the attached file to disk and
2208
     * registering it in the Metacat db
2209
     */
2210
    private void handleUploadAction(HttpServletRequest request,
2211
            PrintWriter out, Hashtable params, Hashtable fileList,
2212
            String username, String[] groupnames)
2213 1041 tao
    {
2214 2098 jones
        //PrintWriter out = null;
2215
        //Connection conn = null;
2216
        String action = null;
2217
        String docid = null;
2218 798 jones
2219 2098 jones
        /*
2220
         * response.setContentType("text/xml"); try { out =
2221
         * response.getWriter(); } catch (IOException ioe2) {
2222
         * System.err.println("Fatal Error: couldn't get response output
2223
         * stream.");
2224
         */
2225 798 jones
2226 2098 jones
        if (params.containsKey("docid")) {
2227
            docid = (String) params.get("docid");
2228
        }
2229 798 jones
2230 2098 jones
        // Make sure we have a docid and datafile
2231
        if (docid != null && fileList.containsKey("datafile")) {
2232 798 jones
2233 2098 jones
            // Get a reference to the file part of the form
2234
            FilePart filePart = (FilePart) fileList.get("datafile");
2235
            String fileName = filePart.getFileName();
2236
            MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2237 1360 tao
2238 2098 jones
            // Check if the right file existed in the uploaded data
2239
            if (fileName != null) {
2240 1360 tao
2241 2098 jones
                try {
2242
                    //MetaCatUtil.debugMessage("Upload datafile " + docid
2243
                    // +"...", 10);
2244
                    //If document get lock data file grant
2245
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2246
                        // register the file in the database (which generates
2247
                        // an exception
2248
                        //if the docid is not acceptable or other untoward
2249
                        // things happen
2250
                        DocumentImpl.registerDocument(fileName, "BIN", docid,
2251
                                username);
2252 1360 tao
2253 2098 jones
                        // Save the data file to disk using "docid" as the name
2254
                        dataDirectory.mkdirs();
2255
                        File newFile = new File(dataDirectory, docid);
2256
                        long size = filePart.writeTo(newFile);
2257 1360 tao
2258 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
2259 2102 jones
                                username, docid, "upload");
2260 2098 jones
                        // Force replication this data file
2261
                        // To data file, "insert" and update is same
2262
                        // The fourth parameter is null. Because it is
2263
                        // notification server
2264
                        // and this method is in MetaCatServerlet. It is
2265
                        // original command,
2266
                        // not get force replication info from another metacat
2267
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2268
                                docid, "insert", false, null);
2269 1360 tao
2270 2098 jones
                        // set content type and other response header fields
2271
                        // first
2272
                        out.println("<?xml version=\"1.0\"?>");
2273
                        out.println("<success>");
2274
                        out.println("<docid>" + docid + "</docid>");
2275
                        out.println("<size>" + size + "</size>");
2276
                        out.println("</success>");
2277
                    }
2278
2279
                } catch (Exception e) {
2280
                    out.println("<?xml version=\"1.0\"?>");
2281
                    out.println("<error>");
2282
                    out.println(e.getMessage());
2283
                    out.println("</error>");
2284
                }
2285
            } else {
2286
                // the field did not contain a file
2287
                out.println("<?xml version=\"1.0\"?>");
2288
                out.println("<error>");
2289
                out.println("The uploaded data did not contain a valid file.");
2290
                out.println("</error>");
2291
            }
2292
        } else {
2293
            // Error bcse docid missing or file missing
2294
            out.println("<?xml version=\"1.0\"?>");
2295
            out.println("<error>");
2296
            out.println("The uploaded data did not contain a valid docid "
2297
                    + "or valid file.");
2298
            out.println("</error>");
2299 798 jones
        }
2300 2098 jones
    }
2301 1360 tao
2302 2098 jones
    /*
2303
     * A method to handle set access action
2304
     */
2305
    private void handleSetAccessAction(PrintWriter out, Hashtable params,
2306
            String username)
2307 1041 tao
    {
2308 2098 jones
        String[] docList = null;
2309
        String[] principalList = null;
2310
        String[] permissionList = null;
2311
        String[] permTypeList = null;
2312
        String[] permOrderList = null;
2313
        String permission = null;
2314
        String permType = null;
2315
        String permOrder = null;
2316
        Vector errorList = new Vector();
2317
        String error = null;
2318
        Vector successList = new Vector();
2319
        String success = null;
2320 1716 berkley
2321 2098 jones
        // Get parameters
2322
        if (params.containsKey("docid")) {
2323
            docList = (String[]) params.get("docid");
2324
        }
2325
        if (params.containsKey("principal")) {
2326
            principalList = (String[]) params.get("principal");
2327
        }
2328
        if (params.containsKey("permission")) {
2329
            permissionList = (String[]) params.get("permission");
2330 1716 berkley
2331 2098 jones
        }
2332
        if (params.containsKey("permType")) {
2333
            permTypeList = (String[]) params.get("permType");
2334 1716 berkley
2335 2098 jones
        }
2336
        if (params.containsKey("permOrder")) {
2337
            permOrderList = (String[]) params.get("permOrder");
2338 1716 berkley
2339 2098 jones
        }
2340 1716 berkley
2341 2098 jones
        // Make sure the parameter is not null
2342
        if (docList == null || principalList == null || permTypeList == null
2343
                || permissionList == null) {
2344
            error = "Please check your parameter list, it should look like: "
2345
                    + "?action=setaccess&docid=pipeline.1.1&principal=public"
2346
                    + "&permission=read&permType=allow&permOrder=allowFirst";
2347
            errorList.addElement(error);
2348
            outputResponse(successList, errorList, out);
2349
            return;
2350
        }
2351 1716 berkley
2352 2098 jones
        // Only select first element for permission, type and order
2353
        permission = permissionList[0];
2354
        permType = permTypeList[0];
2355
        if (permOrderList != null) {
2356
            permOrder = permOrderList[0];
2357
        }
2358 1716 berkley
2359 2098 jones
        // Get package doctype set
2360
        Vector packageSet = MetaCatUtil.getOptionList(MetaCatUtil
2361
                .getOption("packagedoctypeset"));
2362
        //debug
2363
        if (packageSet != null) {
2364
            for (int i = 0; i < packageSet.size(); i++) {
2365
                MetaCatUtil.debugMessage("doctype in package set: "
2366
                        + (String) packageSet.elementAt(i), 34);
2367
            }
2368
        }
2369 1716 berkley
2370 2098 jones
        // handle every accessionNumber
2371
        for (int i = 0; i < docList.length; i++) {
2372
            String accessionNumber = docList[i];
2373
            String owner = null;
2374
            String publicId = null;
2375
            // Get document owner and public id
2376
            try {
2377
                owner = getFieldValueForDoc(accessionNumber, "user_owner");
2378
                publicId = getFieldValueForDoc(accessionNumber, "doctype");
2379
            } catch (Exception e) {
2380
                MetaCatUtil.debugMessage("Error in handleSetAccessAction: "
2381
                        + e.getMessage(), 30);
2382
                error = "Error in set access control for document - "
2383
                        + accessionNumber + e.getMessage();
2384
                errorList.addElement(error);
2385
                continue;
2386
            }
2387
            //check if user is the owner. Only owner can do owner
2388
            if (username == null || owner == null || !username.equals(owner)) {
2389
                error = "User - " + username
2390
                        + " does not have permission to set "
2391
                        + "access control for docid - " + accessionNumber;
2392
                errorList.addElement(error);
2393
                continue;
2394
            }
2395 1716 berkley
2396 2098 jones
            // If docid publicid is BIN data file or other beta4, 6 package
2397
            // document
2398
            // we could not do set access control. Because we don't want
2399
            // inconsistent
2400
            // to its access docuemnt
2401
            if (publicId != null && packageSet != null
2402
                    && packageSet.contains(publicId)) {
2403
                error = "Could not set access control to document "
2404
                        + accessionNumber
2405
                        + "because it is in a pakcage and it has a access file for it";
2406
                errorList.addElement(error);
2407
                continue;
2408
            }
2409 1716 berkley
2410 2098 jones
            // for every principle
2411
            for (int j = 0; j < principalList.length; j++) {
2412
                String principal = principalList[j];
2413
                try {
2414
                    //insert permission
2415
                    AccessControlForSingleFile accessControl = new AccessControlForSingleFile(
2416
                            accessionNumber, principal, permission, permType,
2417
                            permOrder);
2418
                    accessControl.insertPermissions();
2419
                    success = "Set access control to document "
2420
                            + accessionNumber + " successfully";
2421
                    successList.addElement(success);
2422
                } catch (Exception ee) {
2423
                    MetaCatUtil.debugMessage(
2424
                            "Erorr in handleSetAccessAction2: "
2425
                                    + ee.getMessage(), 30);
2426
                    error = "Faild to set access control for document "
2427
                            + accessionNumber + " because " + ee.getMessage();
2428
                    errorList.addElement(error);
2429
                    continue;
2430
                }
2431
            }
2432 1369 tao
        }
2433 2098 jones
        outputResponse(successList, errorList, out);
2434
    }
2435 1716 berkley
2436 2098 jones
    /*
2437
     * A method try to determin a docid's public id, if couldn't find null will
2438
     * be returned.
2439
     */
2440
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
2441
            throws Exception
2442 1369 tao
    {
2443 2098 jones
        if (accessionNumber == null || accessionNumber.equals("")
2444
                || fieldName == null || fieldName.equals("")) { throw new Exception(
2445
                "Docid or field name was not specified"); }
2446 1716 berkley
2447 2098 jones
        PreparedStatement pstmt = null;
2448
        ResultSet rs = null;
2449
        String fieldValue = null;
2450
        String docId = null;
2451
        DBConnection conn = null;
2452
        int serialNumber = -1;
2453 1716 berkley
2454 2098 jones
        // get rid of revision if access number has
2455
        docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2456
        try {
2457
            //check out DBConnection
2458
            conn = DBConnectionPool
2459
                    .getDBConnection("MetaCatServlet.getPublicIdForDoc");
2460
            serialNumber = conn.getCheckOutSerialNumber();
2461
            pstmt = conn.prepareStatement("SELECT " + fieldName
2462
                    + " FROM xml_documents " + "WHERE docid = ? ");
2463 1716 berkley
2464 2098 jones
            pstmt.setString(1, docId);
2465
            pstmt.execute();
2466
            rs = pstmt.getResultSet();
2467
            boolean hasRow = rs.next();
2468
            int perm = 0;
2469
            if (hasRow) {
2470
                fieldValue = rs.getString(1);
2471
            } else {
2472
                throw new Exception("Could not find document: "
2473
                        + accessionNumber);
2474
            }
2475
        } catch (Exception e) {
2476
            MetaCatUtil.debugMessage(
2477
                    "Exception in MetacatServlet.getPublicIdForDoc: "
2478
                            + e.getMessage(), 30);
2479
            throw e;
2480
        } finally {
2481
            try {
2482
                rs.close();
2483
                pstmt.close();
2484 1716 berkley
2485 2098 jones
            } finally {
2486
                DBConnectionPool.returnDBConnection(conn, serialNumber);
2487
            }
2488
        }
2489
        return fieldValue;
2490 1369 tao
    }
2491 1716 berkley
2492 2098 jones
    /*
2493
     * A method to output setAccess action result
2494
     */
2495
    private void outputResponse(Vector successList, Vector errorList,
2496
            PrintWriter out)
2497 1369 tao
    {
2498 2098 jones
        boolean error = false;
2499
        boolean success = false;
2500
        // Output prolog
2501
        out.println(PROLOG);
2502
        // output success message
2503
        if (successList != null) {
2504
            for (int i = 0; i < successList.size(); i++) {
2505
                out.println(SUCCESS);
2506
                out.println((String) successList.elementAt(i));
2507
                out.println(SUCCESSCLOSE);
2508
                success = true;
2509
            }
2510
        }
2511
        // output error message
2512
        if (errorList != null) {
2513
            for (int i = 0; i < errorList.size(); i++) {
2514
                out.println(ERROR);
2515
                out.println((String) errorList.elementAt(i));
2516
                out.println(ERRORCLOSE);
2517
                error = true;
2518
            }
2519
        }
2520 1716 berkley
2521 2098 jones
        // if no error and no success info, send a error that nothing happened
2522
        if (!error && !success) {
2523
            out.println(ERROR);
2524
            out.println("Nothing happend for setaccess action");
2525
            out.println(ERRORCLOSE);
2526
        }
2527 1369 tao
    }
2528 46 jones
}