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