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