Project

General

Profile

1
/**
2
 *  '$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
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: sgarg $'
10
 *     '$Date: 2005-11-01 14:19:35 -0800 (Tue, 01 Nov 2005) $'
11
 * '$Revision: 2712 $'
12
 *
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
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.io.BufferedInputStream;
31
import java.io.File;
32
import java.io.FileInputStream;
33
import java.io.IOException;
34
import java.io.PrintWriter;
35
import java.io.StringReader;
36
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
import java.sql.Timestamp;
42
import java.text.ParseException;
43
import java.text.SimpleDateFormat;
44
import java.util.Enumeration;
45
import java.util.Hashtable;
46
import java.util.Iterator;
47
import java.util.PropertyResourceBundle;
48
import java.util.Vector;
49
import java.util.zip.ZipEntry;
50
import java.util.zip.ZipOutputStream;
51

    
52
import javax.servlet.ServletConfig;
53
import javax.servlet.ServletContext;
54
import javax.servlet.ServletException;
55
import javax.servlet.ServletOutputStream;
56
import javax.servlet.http.HttpServlet;
57
import javax.servlet.http.HttpServletRequest;
58
import javax.servlet.http.HttpServletResponse;
59
import javax.servlet.http.HttpSession;
60

    
61
import org.ecoinformatics.eml.EMLParser;
62

    
63
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
import org.apache.log4j.Logger;
69
import org.apache.log4j.PropertyConfigurator;
70

    
71
import edu.ucsb.nceas.utilities.Options;
72

    
73
/**
74
 * A metadata catalog server implemented as a Java Servlet
75
 *
76
 * <p>
77
 * 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
 * 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
 * <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
 */
117
public class MetaCatServlet extends HttpServlet
118
{
119

    
120
    private ServletConfig config = null;
121

    
122
    private ServletContext context = null;
123

    
124
    private String resultStyleURL = null;
125

    
126
    private String xmlcatalogfile = null;
127

    
128
    private String saxparser = null;
129

    
130
    private String datafilepath = null;
131

    
132
    private File dataDirectory = null;
133

    
134
    private String servletpath = null;
135

    
136
    private String htmlpath = null;
137

    
138
    private PropertyResourceBundle options = null;
139

    
140
    private MetaCatUtil util = null;
141

    
142
    private DBConnectionPool connPool = null;
143

    
144
    private static Hashtable sessionHash = new Hashtable();
145

    
146
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
147

    
148
    private static final String SUCCESS = "<success>";
149

    
150
    private static final String SUCCESSCLOSE = "</success>";
151

    
152
    private static final String ERROR = "<error>";
153

    
154
    private static final String ERRORCLOSE = "</error>";
155

    
156
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
157

    
158
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
159

    
160
    public static final String NAMESPACEKEYWORD = "xmlns";
161

    
162
    public static final String EML2KEYWORD = ":eml";
163

    
164
    public static final String XMLFORMAT = "xml";
165

    
166
    private static final String CONFIG_DIR = "WEB-INF";
167

    
168
    private static final String CONFIG_NAME = "metacat.properties";
169
     	 
170
    private static Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
171
    
172
    /**
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

    
182
            // Initialize the properties file for our options
183
            String dirPath = context.getRealPath(CONFIG_DIR);
184
            File propertyFile = new File(dirPath, CONFIG_NAME);
185

    
186
            String LOG_CONFIG_NAME = dirPath + "/log4j.properties";
187
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
188
            
189
            Options options = null;
190
            try {
191
                options = Options.initialize(propertyFile);
192
                MetaCatUtil.printMessage("Options configured: "
193
                        + options.getOption("configured"));
194
            } catch (IOException ioe) {
195
                logMetacat.error("Error in loading options: "
196
                        + ioe.getMessage());
197
            }
198

    
199
            util = new MetaCatUtil();
200

    
201
            //initial DBConnection pool
202
            connPool = DBConnectionPool.getInstance();
203

    
204
            // 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

    
213
            // Index the paths specified in the metacat.properties
214
            checkIndexPaths();
215

    
216
            MetaCatUtil.printMessage("Metacat (" + Version.getVersion()
217
                               + ") initialized.");
218

    
219
        } catch (ServletException ex) {
220
            throw ex;
221
        } catch (SQLException e) {
222
            logMetacat.error("Error in MetacatServlet.init: "
223
                    + e.getMessage());
224
        }
225
    }
226

    
227
    /**
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

    
237
    /** 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
    /**
256
     * Index the paths specified in the metacat.properties
257
     */
258
    private void checkIndexPaths(){
259
        MetaCatUtil.pathsForIndexing
260
            = MetaCatUtil.getOptionList(MetaCatUtil.getOption("indexed_paths"));
261
    
262
        if (MetaCatUtil.pathsForIndexing != null) {
263
    
264
            MetaCatUtil.printMessage("Indexing paths specified in metacat.properties....");
265
    
266
            DBConnection conn = null;
267
            int serialNumber = -1;
268
            PreparedStatement pstmt = null;
269
            PreparedStatement pstmt1 = null;
270
            ResultSet rs = null;
271
    
272
            for (int i = 0; i < MetaCatUtil.pathsForIndexing.size(); i++) {
273
                logMetacat.info("Checking if '"
274
                           + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
275
                           + "' is indexed.... ");
276
    
277
                try {
278
                    //check out DBConnection
279
                    conn = DBConnectionPool.
280
                        getDBConnection("MetaCatServlet.checkIndexPaths");
281
                    serialNumber = conn.getCheckOutSerialNumber();
282
    
283
                    pstmt = conn.prepareStatement(
284
                        "SELECT * FROM xml_path_index " + "WHERE path = ?");
285
                    pstmt.setString(1, (String) MetaCatUtil.pathsForIndexing
286
                                    .elementAt(i));
287
    
288
                    pstmt.execute();
289
                    rs = pstmt.getResultSet();
290
    
291
                    if (!rs.next()) {
292
                        logMetacat.info(".....not indexed yet.");
293
                        rs.close();
294
                        pstmt.close();
295
                        conn.increaseUsageCount(1);
296
    
297
                        logMetacat.debug(
298
                              "Inserting following path in xml_path_index: "
299
                              + (String)MetaCatUtil.pathsForIndexing
300
                                                   .elementAt(i));
301
    
302
                        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
    
312
                        int count = 0;
313
                        logMetacat.debug(
314
                                       "Executed the select statement for: "
315
                                       + (String) MetaCatUtil.pathsForIndexing
316
                                         .elementAt(i));
317
    
318
                        try {
319
                            while (rs.next()) {
320
    
321
                                String docid = rs.getString(1);
322
                                String nodedata = rs.getString(2);
323
                                float nodedatanumerical = rs.getFloat(3);
324
                                int parentnodeid = rs.getInt(4);
325
    
326
                                if (!nodedata.trim().equals("")) {
327
                                    pstmt1 = conn.prepareStatement(
328
                                        "INSERT INTO xml_path_index"
329
                                        + " (docid, path, nodedata, "
330
                                        + "nodedatanumerical, parentnodeid)"
331
                                        + " VALUES (?, ?, ?, ?, ?)");
332
    
333
                                    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
                                    pstmt1.setInt(5, parentnodeid);
339
    
340
                                    pstmt1.execute();
341
                                    pstmt1.close();
342
    
343
                                    count++;
344
    
345
                                }
346
                            }
347
                        }
348
                        catch (Exception e) {
349
                            System.out.println("Exception:" + e.getMessage());
350
                            e.printStackTrace();
351
                        }
352
    
353
                        rs.close();
354
                        pstmt.close();
355
                        conn.increaseUsageCount(1);
356
    
357
                        logMetacat.warn("Indexed " + count
358
                                + " records from xml_nodes for '"
359
                                + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
360
                                + "'");
361
    
362
                    } else {
363
                    	logMetacat.info(".....already indexed.");
364
                    }
365
    
366
                    rs.close();
367
                    pstmt.close();
368
                    conn.increaseUsageCount(1);
369
    
370
                } catch (Exception e) {
371
                    logMetacat.error("Error in MetaCatServlet.checkIndexPaths: "
372
                                             + e.getMessage());
373
                }finally {
374
                    //check in DBonnection
375
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
376
                }
377
    
378
    
379
            }
380
    
381
            MetaCatUtil.printMessage("Path Indexing Completed");
382
        }
383
    }    
384

    
385
    /**
386
     * Control servlet response depending on the action parameter specified
387
     */
388
    private void handleGetOrPost(HttpServletRequest request,
389
            HttpServletResponse response) throws ServletException, IOException
390
    {
391

    
392
        if (util == null) {
393
            util = new MetaCatUtil();
394
        }
395
        /*
396
         * logMetacat.info("Connection pool size: "
397
         * +connPool.getSizeOfDBConnectionPool(),10);
398
         * logMetacat.info("Free DBConnection number: "
399
         */
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

    
405
        //Debug message to print out the method which have a busy DBConnection
406
        connPool.printMethodNameHavingBusyDBConnection();
407

    
408
        String ctype = request.getContentType();
409
        if (ctype != null && ctype.startsWith("multipart/form-data")) {
410
            handleMultipartForm(request, response);
411
        } else {
412

    
413
            String name = null;
414
            String[] value = null;
415
            String[] docid = new String[3];
416
            Hashtable params = new Hashtable();
417
            Enumeration paramlist = request.getParameterNames();
418

    
419
            while (paramlist.hasMoreElements()) {
420

    
421
                name = (String) paramlist.nextElement();
422
                value = request.getParameterValues(name);
423

    
424
                // 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

    
434
                params.put(name, value);
435
            }
436

    
437
            //handle param is emptpy
438
            if (params.isEmpty() || params == null) { return; }
439

    
440
            //if the user clicked on the input images, decode which image
441
            //was clicked then set the action.
442
            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
            String action = ((String[]) params.get("action"))[0];
454
            logMetacat.warn("Action is: " + action);
455

    
456
            // 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
            name = null;
464
            
465
            // handle login action
466
            if (action.equals("login")) {
467
                PrintWriter out = response.getWriter();
468
                handleLoginAction(out, params, request, response);
469
                out.close();
470

    
471
                // handle logout action
472
            } else if (action.equals("logout")) {
473
                PrintWriter out = response.getWriter();
474
                handleLogoutAction(out, params, request, response);
475
                out.close();
476

    
477
                // 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

    
497
                // 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
                    logMetacat.warn(
503
                            "The session is new or no sessionid is assigned. The user is public");
504
                    username = "public";
505
                    sess.setAttribute("username", username);
506
                } else {
507
                    logMetacat.warn("The session is either old or "
508
                            + "has sessionid parameter");
509
                    try {
510
                        if (params.containsKey("sessionid")) {
511
                            sess_id = ((String[]) params.get("sessionid"))[0];
512
                            logMetacat.info("in has sessionid "
513
                                    + sess_id);
514
                            if (sessionHash.containsKey(sess_id)) {
515
                                logMetacat.info("find the id "
516
                                        + sess_id + " in hash table");
517
                                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
                             * logMetacat.info("in no sessionid
524
                             * parameter ", 40); sess_id =
525
                             * (String)sess.getId();
526
                             * logMetacat.info("storing the session id "
527
                             * + sess_id + " which has username " +
528
                             * sess.getAttribute("username") + " into session
529
                             * hash in handleGetOrPost method", 35);
530
                             */
531
                        }
532
                    } catch (IllegalStateException ise) {
533
                        logMetacat.error(
534
                                "Error in handleGetOrPost: this shouldn't "
535
                                + "happen: the session should be valid: "
536
                                + ise.getMessage());
537
                    }
538

    
539
                    username = (String) sess.getAttribute("username");
540
                    logMetacat.info("The user name from session is: "
541
                            + username);
542
                    password = (String) sess.getAttribute("password");
543
                    groupnames = (String[]) sess.getAttribute("groupnames");
544
                    name = (String) sess.getAttribute("name");
545
                }
546

    
547
                //make user user username should be public
548
                if (username == null || (username.trim().equals(""))) {
549
                    username = "public";
550
                }
551
                logMetacat.warn("The user is : " + username);
552
            }
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

    
574
                handleExportAction(params, response, username,
575
                        groupnames, password);
576
            } else if (action.equals("read")) {
577
                handleReadAction(params, request, response, username, password,
578
                        groupnames);
579
            } else if (action.equals("readinlinedata")) {
580
                handleReadInlineDataAction(params, request, response, username,
581
                        password, groupnames);
582
            } else if (action.equals("insert") || action.equals("update")) {
583
                PrintWriter out = response.getWriter();
584
                if ((username != null) && !username.equals("public")) {
585
                    handleInsertOrUpdateAction(request, response,
586
                            out, params, username, groupnames);
587
                } else {
588
                    response.setContentType("text/xml");
589
                    out.println("<?xml version=\"1.0\"?>");
590
                    out.println("<error>");
591
                    out.println("Permission denied for user " + username + " "
592
                            + action);
593
                    out.println("</error>");
594
                }
595
                out.close();
596
            } else if (action.equals("delete")) {
597
                PrintWriter out = response.getWriter();
598
                if ((username != null) && !username.equals("public")) {
599
                    handleDeleteAction(out, params, request, response, username,
600
                            groupnames);
601
                } else {
602
                    response.setContentType("text/xml");
603
                    out.println("<?xml version=\"1.0\"?>");
604
                    out.println("<error>");
605
                    out.println("Permission denied for " + action);
606
                    out.println("</error>");
607
                }
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
            } else if (action.equals("getlog")) {
648
                handleGetLogAction(params, request, response, username, groupnames);
649
            } 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
            } else if (action.equals("buildindex")) {
671
                handleBuildIndexAction(params, request, response, username, groupnames);
672
            } else if (action.equals("login") || action.equals("logout")) {
673
                /*
674
            } 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
                        Hashtable qparams = MetaCatUtil.parseQuery(u.getQuery());
702
                        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
                */
720
            } 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

    
730
            //util.closeConnections();
731
            // Close the stream to the client
732
            //out.close();
733
        }
734
    }
735

    
736
    // 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
    {
744

    
745
        AuthSession sess = null;
746

    
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
        String un = ((String[]) params.get("username"))[0];
766
        logMetacat.warn("user " + un + " is trying to login");
767
        String pw = ((String[]) params.get("password"))[0];
768

    
769
        String qformat = "xml";
770
        if(params.get("qformat") != null){
771
            qformat = ((String[]) params.get("qformat"))[0];
772
        }
773

    
774
        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

    
784
        //if it is authernticate is true, store the session
785
        if (isValid) {
786
            HttpSession session = sess.getSessions();
787
            String id = session.getId();
788
            logMetacat.info("Store session id " + id
789
                    + "which has username" + session.getAttribute("username")
790
                    + " into hash in login method");
791
            sessionHash.put(id, session);
792
        }
793

    
794
        // 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

    
807
                logMetacat.error(
808
                        "Error in MetaCatServlet.handleLoginAction: "
809
                                + e.getMessage());
810
            }
811
        }
812
    }
813

    
814
    /**
815
     * Handle the logout request. Close the connection.
816
     */
817
    private void handleLogoutAction(PrintWriter out, Hashtable params,
818
            HttpServletRequest request, HttpServletResponse response)
819
    {
820

    
821
        String qformat = "xml";
822
        if(params.get("qformat") != null){
823
            qformat = ((String[]) params.get("qformat"))[0];
824
        }
825

    
826
        // close the connection
827
        HttpSession sess = request.getSession(false);
828
        logMetacat.info("After get session in logout request");
829
        if (sess != null) {
830
            logMetacat.info("The session id " + sess.getId()
831
                    + " will be invalidate in logout action");
832
            logMetacat.warn("The session contains user "
833
                    + sess.getAttribute("username")
834
                    + " will be invalidate in logout action");
835
            sess.invalidate();
836
        }
837

    
838
        // 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

    
845
        //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
                logMetacat.error(
858
                        "Error in MetaCatServlet.handleLogoutAction"
859
                                + e.getMessage());
860
            }
861
        }
862
    }
863

    
864
    // END OF LOGIN & LOGOUT SECTION
865

    
866
    // SQUERY & QUERY SECTION
867
    /**
868
     * Retreive the squery xml, execute it and display it
869
     *
870
     * @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
    private void handleSQuery(PrintWriter out, Hashtable params,
877
            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
        logMetacat.warn("Total search time for action 'squery': "
885
                + (outPutTime - startTime));
886

    
887
    }
888

    
889
    /**
890
     * Create the xml query, execute it and display the results.
891
     *
892
     * @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
    private void handleQuery(PrintWriter out, Hashtable params,
898
            HttpServletResponse response, String user, String[] groups,
899
            String sessionid)
900
    {
901
        //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
        logMetacat.warn("Total search time for action 'query': "
911
                + (outPutTime - startTime));
912

    
913
        //handleSQuery(out, params, response,user, groups, sessionid);
914
    }
915

    
916
    // END OF SQUERY & QUERY SECTION
917

    
918
    //Exoport section
919
    /**
920
     * Handle the "export" request of data package from Metacat in zip format
921
     *
922
     * @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
    private void handleExportAction(Hashtable params,
928
            HttpServletResponse response,
929
            String user, String[] groups, String passWord)
930
    {
931
        // Output stream
932
        ServletOutputStream out = null;
933
        // Zip output stream
934
        ZipOutputStream zOut = null;
935
        DBQuery queryObj = null;
936

    
937
        String[] docs = new String[10];
938
        String docId = "";
939

    
940
        try {
941
            // read the params
942
            if (params.containsKey("docid")) {
943
                docs = (String[]) params.get("docid");
944
            }
945
            // 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
            response.setHeader("Content-Disposition", 
967
            		"attachment; filename=" 
968
            		+ docId + ".zip"); // Set the name of the zip file
969
            		
970
            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

    
976
        } 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
                logMetacat.error("Problem with the servlet output "
997
                        + "in MetacatServlet.handleExportAction: "
998
                        + ioe.getMessage());
999
            }
1000

    
1001
            logMetacat.error(
1002
                    "Error in MetacatServlet.handleExportAction: "
1003
                            + e.getMessage());
1004
            e.printStackTrace(System.out);
1005

    
1006
        }
1007

    
1008
    }
1009

    
1010
    /**
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
     *
1015
     * @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
            HttpServletRequest request, HttpServletResponse response,
1022
            String user, String passWord, String[] groups)
1023
    {
1024
        String[] docs = new String[10];
1025
        String inlineDataId = null;
1026
        String docId = "";
1027
        ServletOutputStream out = null;
1028

    
1029
        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
            if (inlineDataId == null || inlineDataId.equals("")) {
1038
                throw new Exception("You didn't specify requested inlinedataid"); }
1039

    
1040
            // 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
                    AccessControlInterface.READSTRING))
1047
            {
1048
                throw new Exception("User " + user
1049
                        + " doesn't have permission " + " to read document "
1050
                        + docId);
1051
            }
1052
            else
1053
            {
1054
              //check data access level
1055
              try
1056
              {
1057
                Hashtable unReadableInlineDataList =
1058
                    PermissionController.getUnReadableInlineDataIdList(docId,
1059
                    user, groups, false);
1060
                if (unReadableInlineDataList.containsValue(
1061
                          MetaCatUtil.getInlineDataIdWithoutRev(inlineDataId)))
1062
                {
1063
                  throw new Exception("User " + user
1064
                       + " doesn't have permission " + " to read inlinedata "
1065
                       + inlineDataId);
1066

    
1067
                }//if
1068
              }//try
1069
              catch (Exception e)
1070
              {
1071
                throw e;
1072
              }//catch
1073
            }//else
1074

    
1075
            // 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
            out.close();
1088

    
1089
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1090
                    inlineDataId, "readinlinedata");
1091
        } 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
                logMetacat.error("Problem with the servlet output "
1112
                        + "in MetacatServlet.handleExportAction: "
1113
                        + ioe.getMessage());
1114
            }
1115
            logMetacat.error(
1116
                    "Error in MetacatServlet.handleReadInlineDataAction: "
1117
                            + e.getMessage());
1118
        }
1119
    }
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
    {
1127
        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

    
1138
        try {
1139
            //check out DBConnection
1140
            conn = DBConnectionPool
1141
                    .getDBConnection("AccessControlList.isAllowFirst");
1142
            serialNumber = conn.getCheckOutSerialNumber();
1143

    
1144
            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
        }
1167
        logMetacat.info("The nodeid for inlinedataid " + inLineDataId
1168
                + " is: " + nodeId);
1169
        return nodeId;
1170
    }
1171

    
1172
    /**
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
     *
1177
     * @param params the Hashtable of HTTP request parameters
1178
     * @param request the HTTP request object linked to the client
1179
     * @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
    private void handleReadAction(Hashtable params, HttpServletRequest request,
1184
            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

    
1193
        try {
1194
            String[] docs = new String[0];
1195
            String docid = "";
1196
            String qformat = "";
1197
            String abstrpath = null;
1198

    
1199
            // 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
            // we don't support read a eml document without inline data now.
1208
            /*if (params.containsKey("inlinedata")) {
1209

    
1210
                String inlineData = ((String[]) params.get("inlinedata"))[0];
1211
                if (inlineData.equalsIgnoreCase("false")) {
1212
                    withInlineData = false;
1213
                }
1214
            }*/
1215
            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

    
1225
                    URL murl = new URL(docs[i]);
1226
                    Hashtable murlQueryStr = MetaCatUtil.parseQuery(
1227
                            murl.getQuery());
1228
                    // 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
                            addDocToZip(request, docid, zout, user, groups);
1235
                        } else {
1236
                            readFromMetacat(request, response, docid, qformat,
1237
                                    abstrpath, user, groups, zip, zout,
1238
                                    withInlineData, params);
1239
                        }
1240

    
1241
                        // case docid="http://.../filename"
1242
                    } else {
1243
                        docid = docs[i];
1244
                        if (zip) {
1245
                            addDocToZip(request, docid, zout, user, groups);
1246
                        } else {
1247
                            readFromURLConnection(response, docid);
1248
                        }
1249
                    }
1250

    
1251
                } catch (MalformedURLException mue) {
1252
                    docid = docs[i];
1253
                    if (zip) {
1254
                        addDocToZip(request, docid, zout, user, groups);
1255
                    } else {
1256
                        readFromMetacat(request, response, docid, qformat,
1257
                                abstrpath, user, groups, zip, zout,
1258
                                withInlineData, params);
1259
                    }
1260
                }
1261
            }
1262

    
1263
            if (zip) {
1264
                zout.finish(); //terminate the zip file
1265
                zout.close(); //close the zip stream
1266
            }
1267

    
1268
        } 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
            logMetacat.warn("Missed id: " + notFoundDocId);
1274
            logMetacat.warn("Missed rev: " + notFoundRevision);
1275
            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

    
1288
            } catch (Exception exc) {
1289
                logMetacat.error(
1290
                        "Erorr in MetacatServlet.hanldReadAction: "
1291
                                + exc.getMessage());
1292
                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

    
1304
                    } 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
                    logMetacat.error("Problem with the servlet output "
1323
                            + "in MetacatServlet.handleReadAction: "
1324
                            + ie.getMessage());
1325
                }
1326
            }
1327
        } catch (Exception e) {
1328
            try {
1329

    
1330
                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

    
1351
                }
1352
                // Close zip output stream
1353
                if (zout != null) {
1354
                    zout.close();
1355
                }
1356

    
1357
            } catch (IOException ioe) {
1358
                logMetacat.error("Problem with the servlet output "
1359
                        + "in MetacatServlet.handleReadAction: "
1360
                        + ioe.getMessage());
1361
                ioe.printStackTrace(System.out);
1362

    
1363
            }
1364

    
1365
            logMetacat.error(
1366
                    "Error in MetacatServlet.handleReadAction: "
1367
                            + e.getMessage());
1368
            //e.printStackTrace(System.out);
1369
        }
1370
    }
1371

    
1372
    /** read metadata or data from Metacat
1373
     */
1374
    private void readFromMetacat(HttpServletRequest request,
1375
            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
    {
1381

    
1382
        try {
1383
            
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
            DocumentImpl doc = new DocumentImpl(docid);
1393

    
1394
            //check the permission for read
1395
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1396
                Exception e = new Exception("User " + user
1397
                        + " does not have permission"
1398
                        + " to read the document with the docid " + docid);
1399

    
1400
                throw e;
1401
            }
1402

    
1403
            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

    
1413
                //MIME type
1414
                String contentType = getServletContext().getMimeType(filename);
1415
                if (contentType == null) {
1416
                    ContentTypeProvider provider = new ContentTypeProvider(
1417
                            docid);
1418
                    contentType = provider.getContentType();
1419
                    logMetacat.warn("Final contenttype is: "
1420
                            + contentType);
1421
                }
1422

    
1423
                response.setContentType(contentType);
1424
                // if we decide to use "application/octet-stream" for all data
1425
                // returns
1426
                // response.setContentType("application/octet-stream");
1427

    
1428
                try {
1429

    
1430
                    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

    
1441
            } else {
1442
                // this is metadata doc
1443
                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
                    // 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

    
1454
                    // 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

    
1463
            }
1464
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1465
                    docid, "read");
1466
        } catch (Exception except) {
1467
            throw except;
1468
        }
1469
    }
1470

    
1471
    /**
1472
     * read data from URLConnection
1473
     */
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
        }
1500
        response.setContentType(contentType);
1501
        // if we decide to use "application/octet-stream" for all data returns
1502
        // response.setContentType("application/octet-stream");
1503

    
1504
        // this is http url
1505
        URL url = new URL(docid);
1506
        BufferedInputStream bis = null;
1507
        try {
1508
            bis = new BufferedInputStream(url.openStream());
1509
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1510
            int b = bis.read(buf);
1511
            while (b != -1) {
1512
                out.write(buf, 0, b);
1513
                b = bis.read(buf);
1514
            }
1515
        } finally {
1516
            if (bis != null) bis.close();
1517
        }
1518

    
1519
    }
1520

    
1521
    /**
1522
     * read file/doc and write to ZipOutputStream
1523
     *
1524
     * @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
    private void addDocToZip(HttpServletRequest request, String docid,
1535
            ZipOutputStream zout, String user, String[] groups) throws
1536
            ClassNotFoundException, IOException, SQLException, McdbException,
1537
            Exception
1538
    {
1539
        byte[] bytestring = null;
1540
        ZipEntry zentry = null;
1541

    
1542
        try {
1543
            URL url = new URL(docid);
1544

    
1545
            // 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

    
1562
        } catch (MalformedURLException mue) {
1563

    
1564
            // this is metacat doc (data file or metadata doc)
1565
            try {
1566
                DocumentImpl doc = new DocumentImpl(docid);
1567

    
1568
                //check the permission for read
1569
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1570
                    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

    
1577
                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

    
1588
                        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

    
1601
                } 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
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1611
                        docid, "read");
1612
            } catch (Exception except) {
1613
                throw except;
1614
            }
1615
        }
1616
    }
1617

    
1618
    /**
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
    {
1627
        // 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
    }
1648

    
1649
    /**
1650
     * Handle the database putdocument request and write an XML document to the
1651
     * database connection
1652
     */
1653
    private void handleInsertOrUpdateAction(HttpServletRequest request,
1654
            HttpServletResponse response, PrintWriter out, Hashtable params,
1655
            String user, String[] groups)
1656
    {
1657
        DBConnection dbConn = null;
1658
        int serialNumber = -1;
1659

    
1660
        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
            logMetacat.error("Docid not specified");
1666
            return;
1667
        }
1668
        
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
            logMetacat.error("User '" + user + "' not allowed to insert and update");
1675
            return;
1676
        }
1677

    
1678
        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

    
1686
            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

    
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
            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
                } else {
1718

    
1719
                    String namespace = findNamespace(xml);
1720
                    
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
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1732
                			// 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
                }
1746

    
1747
                String[] action = (String[]) params.get("action");
1748
                String[] docid = (String[]) params.get("docid");
1749
                String newdocid = null;
1750

    
1751
                String doAction = null;
1752
                if (action[0].equals("insert")) {
1753
                    doAction = "INSERT";
1754
                } else if (action[0].equals("update")) {
1755
                    doAction = "UPDATE";
1756
                }
1757

    
1758
                try {
1759
                    // get a connection from the pool
1760
                    dbConn = DBConnectionPool
1761
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1762
                    serialNumber = dbConn.getCheckOutSerialNumber();
1763

    
1764
                    // write the document to the database
1765
                    try {
1766
                        String accNumber = docid[0];
1767
                        logMetacat.warn("" + doAction + " "
1768
                                + accNumber + "...");
1769
                        if (accNumber.equals("")) {
1770
                            accNumber = null;
1771
                        }
1772
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1773
                                doAction, accNumber, user, groups);
1774
                        EventLog.getInstance().log(request.getRemoteAddr(),
1775
                                user, accNumber, action[0]);
1776
                    } catch (NullPointerException npe) {
1777
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1778
                                doAction, null, user, groups);
1779
                        EventLog.getInstance().log(request.getRemoteAddr(),
1780
                                user, "", action[0]);
1781
                    }
1782
                }
1783
                finally {
1784
                    // Return db connection
1785
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1786
                }
1787

    
1788
                // 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

    
1795
            } 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
                logMetacat.warn("Error in writing eml document to the database" + npe.getMessage());
1802
            }
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
            logMetacat.warn("Error in writing eml document to the database" + e.getMessage());
1810
        }
1811
    }
1812

    
1813
    /**
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
    {
1820

    
1821
        StringBuffer cbuff = new StringBuffer();
1822
        java.util.Stack st = new java.util.Stack();
1823
        boolean validate = false;
1824
        int c;
1825
        int inx;
1826

    
1827
        // 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

    
1831
            // "<!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

    
1855
        // close the stream
1856
        xmlreader.reset();
1857

    
1858
        // 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

    
1869
        logMetacat.warn("Validation for dtd is " + validate);
1870
        return validate;
1871
    }
1872

    
1873
    // END OF INSERT/UPDATE SECTION
1874

    
1875
    /* check if the xml string contains key words to specify schema loocation */
1876
    private String findNamespace(StringReader xml) throws IOException
1877
    {
1878
        String namespace = null;
1879

    
1880
        String eml2_0_0NameSpace = DocumentImpl.EML2_0_0NAMESPACE;
1881
        String eml2_0_1NameSpace = DocumentImpl.EML2_0_1NAMESPACE;
1882
        String eml2_1_0NameSpace = DocumentImpl.EML2_1_0NAMESPACE;
1883

    
1884
        if (xml == null) {
1885
            logMetacat.warn("Validation for schema is "
1886
                    + namespace);
1887
            return namespace;
1888
        }
1889
        String targetLine = getSchemaLine(xml);
1890

    
1891
        if (targetLine != null) {
1892

    
1893
        	// 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 
1902
        					+ ":" + prefix;
1903
        		startIndex = targetLine.indexOf(namespaceWithPrefix);
1904
        		
1905
        	} else {
1906
        		// if prefix not found then look for xmlns
1907
        		// attribute to find the ns 
1908
        		startIndex = targetLine.indexOf(NAMESPACEKEYWORD);
1909
        	}
1910
        		
1911
            int start = 1;
1912
            int end = 1;
1913
            String namespaceString = null;
1914
            int count = 0;
1915
            if (startIndex != -1) {
1916
                for (int i = startIndex; i < targetLine.length(); i++) {
1917
                    if (targetLine.charAt(i) == '"') {
1918
                        count++;
1919
                    }
1920
                    if (targetLine.charAt(i) == '"' && count == 1) {
1921
                        start = i;
1922
                    }
1923
                    if (targetLine.charAt(i) == '"' && count == 2) {
1924
                        end = i;
1925
                        break;
1926
                    }
1927
                }
1928
            } 
1929
            // else: xmlns not found. namespace = null will be returned
1930

    
1931
            if(start < end){
1932
            	namespaceString = targetLine.substring(start + 1, end);
1933
            }
1934
            logMetacat.info("namespace in xml is: "
1935
                    + namespaceString);
1936
            if (namespaceString.indexOf(eml2_0_0NameSpace) != -1) {
1937
                namespace = eml2_0_0NameSpace;
1938
            } else if (namespaceString.indexOf(eml2_0_1NameSpace) != -1) {
1939
                namespace = eml2_0_1NameSpace;
1940
            } else if (namespaceString.indexOf(eml2_1_0NameSpace) != -1) {
1941
                namespace = eml2_1_0NameSpace;
1942
            } else {
1943
            	namespace = namespaceString;
1944
            }
1945
        }
1946

    
1947
        logMetacat.warn("Validation for eml is " + namespace);
1948

    
1949
        return namespace;
1950

    
1951
    }
1952

    
1953
    private String getSchemaLine(StringReader xml) throws IOException
1954
    {
1955
        // find the line
1956
        String secondLine = null;
1957
        int count = 0;
1958
        int endIndex = 0;
1959
        int startIndex = 0;
1960
        final int TARGETNUM = 2;
1961
        StringBuffer buffer = new StringBuffer();
1962
        boolean comment = false;
1963
        char thirdPreviousCharacter = '?';
1964
        char secondPreviousCharacter = '?';
1965
        char previousCharacter = '?';
1966
        char currentCharacter = '?';
1967
        int tmp = xml.read();
1968
        while (tmp != -1) {
1969
            currentCharacter = (char)tmp;
1970
            //in a comment
1971
            if (currentCharacter == '-' && previousCharacter == '-'
1972
                    && secondPreviousCharacter == '!'
1973
                    && thirdPreviousCharacter == '<') {
1974
                comment = true;
1975
            }
1976
            //out of comment
1977
            if (comment && currentCharacter == '>' && previousCharacter == '-'
1978
                    && secondPreviousCharacter == '-') {
1979
                comment = false;
1980
            }
1981

    
1982
            //this is not comment
1983
            if (currentCharacter != '!' && previousCharacter == '<' && !comment) {
1984
                count++;
1985
            }
1986
            // get target line
1987
            if (count == TARGETNUM && currentCharacter != '>') {
1988
                buffer.append(currentCharacter);
1989
            }
1990
            if (count == TARGETNUM && currentCharacter == '>') {
1991
                break;
1992
            }
1993
            thirdPreviousCharacter = secondPreviousCharacter;
1994
            secondPreviousCharacter = previousCharacter;
1995
            previousCharacter = currentCharacter;
1996
            tmp = xml.read();
1997
        }
1998
        secondLine = buffer.toString();
1999
        logMetacat.info("the second line string is: " + secondLine);
2000
        
2001
        xml.reset();
2002
        return secondLine;
2003
    }
2004

    
2005
    private String getPrefix(String schemaLine)
2006
    {
2007
    	String prefix = null;
2008
    	String rootElement = schemaLine.substring(0, schemaLine.indexOf(" "));
2009
        logMetacat.warn("rootElement:" + rootElement);
2010
        
2011
        if(rootElement.indexOf(":") > 0){
2012
        	prefix = rootElement.substring(rootElement.indexOf(":") + 1,
2013
        			rootElement.length());
2014
        } 
2015
        logMetacat.warn("prefix:" + prefix);        
2016
        return prefix;
2017
    }
2018

    
2019
    /**
2020
     * Handle the database delete request and delete an XML document from the
2021
     * database connection
2022
     */
2023
    private void handleDeleteAction(PrintWriter out, Hashtable params,
2024
            HttpServletRequest request, HttpServletResponse response,
2025
            String user, String[] groups)
2026
    {
2027

    
2028
        String[] docid = (String[]) params.get("docid");
2029

    
2030
        if(docid == null){
2031
          response.setContentType("text/xml");
2032
          out.println("<?xml version=\"1.0\"?>");
2033
          out.println("<error>");
2034
          out.println("Docid not specified.");
2035
          out.println("</error>");
2036
          logMetacat.error("Docid not specified for the document to be deleted.");
2037
        } else {
2038

    
2039
            // delete the document from the database
2040
            try {
2041

    
2042
                try {
2043
                    // null means notify server is null
2044
                    DocumentImpl.delete(docid[0], user, groups, null);
2045
                    EventLog.getInstance().log(request.getRemoteAddr(),
2046
                                               user, docid[0], "delete");
2047
                    response.setContentType("text/xml");
2048
                    out.println("<?xml version=\"1.0\"?>");
2049
                    out.println("<success>");
2050
                    out.println("Document deleted.");
2051
                    out.println("</success>");
2052
                    logMetacat.warn("Document deleted.");
2053
                }
2054
                catch (AccessionNumberException ane) {
2055
                    response.setContentType("text/xml");
2056
                    out.println("<?xml version=\"1.0\"?>");
2057
                    out.println("<error>");
2058
                    //out.println("Error deleting document!!!");
2059
                    out.println(ane.getMessage());
2060
                    out.println("</error>");
2061
                    logMetacat.error("Document could not be deleted: " 
2062
                    		+ ane.getMessage());
2063
                }
2064
            }
2065
            catch (Exception e) {
2066
                response.setContentType("text/xml");
2067
                out.println("<?xml version=\"1.0\"?>");
2068
                out.println("<error>");
2069
                out.println(e.getMessage());
2070
                out.println("</error>");
2071
                logMetacat.error("Document could not be deleted: " 
2072
                		+ e.getMessage());
2073
            }
2074
        }
2075
    }
2076

    
2077
    /**
2078
     * Handle the validation request and return the results to the requestor
2079
     */
2080
    private void handleValidateAction(PrintWriter out, Hashtable params)
2081
    {
2082

    
2083
        // Get the document indicated
2084
        String valtext = null;
2085
        DBConnection dbConn = null;
2086
        int serialNumber = -1;
2087

    
2088
        try {
2089
            valtext = ((String[]) params.get("valtext"))[0];
2090
        } catch (Exception nullpe) {
2091

    
2092
            String docid = null;
2093
            try {
2094
                // Find the document id number
2095
                docid = ((String[]) params.get("docid"))[0];
2096

    
2097
                // Get the document indicated from the db
2098
                DocumentImpl xmldoc = new DocumentImpl(docid);
2099
                valtext = xmldoc.toString();
2100

    
2101
            } catch (NullPointerException npe) {
2102

    
2103
                out.println("<error>Error getting document ID: " + docid
2104
                        + "</error>");
2105
                //if ( conn != null ) { util.returnConnection(conn); }
2106
                return;
2107
            } catch (Exception e) {
2108

    
2109
                out.println(e.getMessage());
2110
            }
2111
        }
2112

    
2113
        try {
2114
            // get a connection from the pool
2115
            dbConn = DBConnectionPool
2116
                    .getDBConnection("MetaCatServlet.handleValidateAction");
2117
            serialNumber = dbConn.getCheckOutSerialNumber();
2118
            DBValidate valobj = new DBValidate(saxparser, dbConn);
2119
            boolean valid = valobj.validateString(valtext);
2120

    
2121
            // set content type and other response header fields first
2122

    
2123
            out.println(valobj.returnErrors());
2124

    
2125
        } catch (NullPointerException npe2) {
2126
            // set content type and other response header fields first
2127

    
2128
            out.println("<error>Error validating document.</error>");
2129
        } catch (Exception e) {
2130

    
2131
            out.println(e.getMessage());
2132
        } finally {
2133
            // Return db connection
2134
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2135
        }
2136
    }
2137

    
2138
    /**
2139
     * Handle "getrevsionanddoctype" action Given a docid, return it's current
2140
     * revision and doctype from data base The output is String look like
2141
     * "rev;doctype"
2142
     */
2143
    private void handleGetRevisionAndDocTypeAction(PrintWriter out,
2144
            Hashtable params)
2145
    {
2146
        // To store doc parameter
2147
        String[] docs = new String[10];
2148
        // Store a single doc id
2149
        String givenDocId = null;
2150
        // Get docid from parameters
2151
        if (params.containsKey("docid")) {
2152
            docs = (String[]) params.get("docid");
2153
        }
2154
        // Get first docid form string array
2155
        givenDocId = docs[0];
2156

    
2157
        try {
2158
            // Make sure there is a docid
2159
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
2160
                    "User didn't specify docid!"); }//if
2161

    
2162
            // Create a DBUtil object
2163
            DBUtil dbutil = new DBUtil();
2164
            // Get a rev and doctype
2165
            String revAndDocType = dbutil
2166
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
2167
            out.println(revAndDocType);
2168

    
2169
        } catch (Exception e) {
2170
            // Handle exception
2171
            out.println("<?xml version=\"1.0\"?>");
2172
            out.println("<error>");
2173
            out.println(e.getMessage());
2174
            out.println("</error>");
2175
        }
2176

    
2177
    }
2178

    
2179
    /**
2180
     * Handle "getaccesscontrol" action. Read Access Control List from db
2181
     * connection in XML format
2182
     */
2183
    private void handleGetAccessControlAction(PrintWriter out,
2184
            Hashtable params, HttpServletResponse response, String username,
2185
            String[] groupnames)
2186
    {
2187
        DBConnection dbConn = null;
2188
        int serialNumber = -1;
2189
        String docid = ((String[]) params.get("docid"))[0];
2190

    
2191
        try {
2192

    
2193
            // get connection from the pool
2194
            dbConn = DBConnectionPool
2195
                    .getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2196
            serialNumber = dbConn.getCheckOutSerialNumber();
2197
            AccessControlList aclobj = new AccessControlList(dbConn);
2198
            String acltext = aclobj.getACL(docid, username, groupnames);
2199
            out.println(acltext);
2200

    
2201
        } catch (Exception e) {
2202
            out.println("<?xml version=\"1.0\"?>");
2203
            out.println("<error>");
2204
            out.println(e.getMessage());
2205
            out.println("</error>");
2206
        } finally {
2207
            // Retrun db connection to pool
2208
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2209
        }
2210
    }
2211

    
2212
    /**
2213
     * Handle the "getprincipals" action. Read all principals from
2214
     * authentication scheme in XML format
2215
     */
2216
    private void handleGetPrincipalsAction(PrintWriter out, String user,
2217
            String password)
2218
    {
2219
        try {
2220
            AuthSession auth = new AuthSession();
2221
            String principals = auth.getPrincipals(user, password);
2222
            out.println(principals);
2223

    
2224
        } catch (Exception e) {
2225
            out.println("<?xml version=\"1.0\"?>");
2226
            out.println("<error>");
2227
            out.println(e.getMessage());
2228
            out.println("</error>");
2229
        }
2230
    }
2231

    
2232
    /**
2233
     * Handle "getdoctypes" action. Read all doctypes from db connection in XML
2234
     * format
2235
     */
2236
    private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
2237
            HttpServletResponse response)
2238
    {
2239
        try {
2240
            DBUtil dbutil = new DBUtil();
2241
            String doctypes = dbutil.readDoctypes();
2242
            out.println(doctypes);
2243
        } catch (Exception e) {
2244
            out.println("<?xml version=\"1.0\"?>");
2245
            out.println("<error>");
2246
            out.println(e.getMessage());
2247
            out.println("</error>");
2248
        }
2249
    }
2250

    
2251
    /**
2252
     * Handle the "getdtdschema" action. Read DTD or Schema file for a given
2253
     * doctype from Metacat catalog system
2254
     */
2255
    private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2256
            HttpServletResponse response)
2257
    {
2258

    
2259
        String doctype = null;
2260
        String[] doctypeArr = (String[]) params.get("doctype");
2261

    
2262
        // get only the first doctype specified in the list of doctypes
2263
        // it could be done for all doctypes in that list
2264
        if (doctypeArr != null) {
2265
            doctype = ((String[]) params.get("doctype"))[0];
2266
        }
2267

    
2268
        try {
2269
            DBUtil dbutil = new DBUtil();
2270
            String dtdschema = dbutil.readDTDSchema(doctype);
2271
            out.println(dtdschema);
2272

    
2273
        } catch (Exception e) {
2274
            out.println("<?xml version=\"1.0\"?>");
2275
            out.println("<error>");
2276
            out.println(e.getMessage());
2277
            out.println("</error>");
2278
        }
2279

    
2280
    }
2281

    
2282
    /**
2283
     * Handle the "getlastdocid" action. Get the latest docid with rev number
2284
     * from db connection in XML format
2285
     */
2286
    private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2287
            HttpServletResponse response)
2288
    {
2289

    
2290
        String scope = ((String[]) params.get("scope"))[0];
2291
        if (scope == null) {
2292
            scope = ((String[]) params.get("username"))[0];
2293
        }
2294

    
2295
        try {
2296

    
2297
            DBUtil dbutil = new DBUtil();
2298
            String lastDocid = dbutil.getMaxDocid(scope);
2299
            out.println("<?xml version=\"1.0\"?>");
2300
            out.println("<lastDocid>");
2301
            out.println("  <scope>" + scope + "</scope>");
2302
            out.println("  <docid>" + lastDocid + "</docid>");
2303
            out.println("</lastDocid>");
2304

    
2305
        } catch (Exception e) {
2306
            out.println("<?xml version=\"1.0\"?>");
2307
            out.println("<error>");
2308
            out.println(e.getMessage());
2309
            out.println("</error>");
2310
        }
2311
    }
2312

    
2313
    /**
2314
     * Print a report from the event log based on filter parameters passed in
2315
     * from the web.
2316
     *
2317
     * @param params the parameters from the web request
2318
     * @param request the http request object for getting request details
2319
     * @param response the http response object for writing output
2320
     */
2321
    private void handleGetLogAction(Hashtable params, HttpServletRequest request,
2322
            HttpServletResponse response, String username, String[] groups)
2323
    {
2324
        try {
2325
            response.setContentType("text/xml");
2326
            PrintWriter out = response.getWriter();
2327

    
2328
            // Check that the user is authenticated as an administrator account
2329
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2330
                out.print("<error>");
2331
                out.print("The user \"" + username +
2332
                        "\" is not authorized for this action.");
2333
                out.print("</error>");
2334
                return;
2335
            }
2336

    
2337
            // Get all of the parameters in the correct formats
2338
            String[] ipAddress = (String[])params.get("ipaddress");
2339
            String[] principal = (String[])params.get("principal");
2340
            String[] docid = (String[])params.get("docid");
2341
            String[] event = (String[])params.get("event");
2342
            String[] startArray = (String[]) params.get("start");
2343
            String[] endArray = (String[]) params.get("end");
2344
            String start = null;
2345
            String end = null;
2346
            if (startArray != null) {
2347
                start = startArray[0];
2348
            }
2349
            if (endArray != null) {
2350
                end = endArray[0];
2351
            }
2352
            Timestamp startDate = null;
2353
            Timestamp endDate = null;
2354
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2355
            try {
2356
                if (start != null) {
2357
                    startDate = new Timestamp((format.parse(start)).getTime());
2358
                }
2359
                if (end != null) {
2360
                    endDate = new Timestamp((format.parse(end)).getTime());
2361
                }
2362
            } catch (ParseException e) {
2363
                System.out.println("Failed to created Timestamp from input.");
2364
            }
2365

    
2366
            // Request the report by passing the filter parameters
2367
            out.println(EventLog.getInstance().getReport(ipAddress, principal,
2368
                    docid, event, startDate, endDate));
2369
            out.close();
2370
        } catch (IOException e) {
2371
            logMetacat.error(
2372
                    "Could not open http response for writing: " + e.getMessage());
2373
        }
2374
    }
2375

    
2376
    /**
2377
     * Rebuild the index for one or more documents. If the docid parameter is
2378
     * provided, rebuild for just that one document or list of documents. If
2379
     * not, then rebuild the index for all documents in the xml_documents
2380
     * table.
2381
     *
2382
     * @param params the parameters from the web request
2383
     * @param request the http request object for getting request details
2384
     * @param response the http response object for writing output
2385
     * @param username the username of the authenticated user
2386
     */
2387
    private void handleBuildIndexAction(Hashtable params,
2388
            HttpServletRequest request, HttpServletResponse response,
2389
            String username, String[] groups)
2390
    {
2391
        // Get all of the parameters in the correct formats
2392
        String[] docid = (String[])params.get("docid");
2393

    
2394
        // Rebuild the indices for appropriate documents
2395
        try {
2396
            response.setContentType("text/xml");
2397
            PrintWriter out = response.getWriter();
2398

    
2399
            // Check that the user is authenticated as an administrator account
2400
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2401
                out.print("<error>");
2402
                out.print("The user \"" + username +
2403
                        "\" is not authorized for this action.");
2404
                out.print("</error>");
2405
                return;
2406
            }
2407

    
2408
            // Process the documents
2409
            out.println("<success>");
2410
            if (docid == null || docid.length == 0) {
2411
                // Process all of the documents
2412
                try {
2413
                    Vector documents = getDocumentList();
2414
                    Iterator it = documents.iterator();
2415
                    while (it.hasNext()) {
2416
                        String id = (String) it.next();
2417
                        buildDocumentIndex(id, out);
2418
                    }
2419
                } catch (SQLException se) {
2420
                    out.print("<error>");
2421
                    out.print(se.getMessage());
2422
                    out.println("</error>");
2423
                }
2424
            } else {
2425
                // Only process the requested documents
2426
                for (int i = 0; i < docid.length; i++) {
2427
                    buildDocumentIndex(docid[i], out);
2428
                }
2429
            }
2430
            out.println("</success>");
2431
            out.close();
2432
        } catch (IOException e) {
2433
            logMetacat.error(
2434
                    "Could not open http response for writing: "
2435
                    + e.getMessage());
2436
        }
2437
    }
2438

    
2439
    /**
2440
     * Build the index for one document by reading the document and
2441
     * calling its buildIndex() method.
2442
     *
2443
     * @param docid the document (with revision) to rebuild
2444
     * @param out the PrintWriter to which output is printed
2445
     */
2446
    private void buildDocumentIndex(String docid, PrintWriter out)
2447
    {
2448
        try {
2449
            DocumentImpl doc = new DocumentImpl(docid, false);
2450
            doc.buildIndex();
2451
            out.print("<docid>" + docid);
2452
            out.println("</docid>");
2453
        } catch (McdbException me) {
2454
            out.print("<error>");
2455
            out.print(me.getMessage());
2456
            out.println("</error>");
2457
        }
2458
    }
2459

    
2460
    /**
2461
     * Handle documents passed to metacat that are encoded using the
2462
     * "multipart/form-data" mime type. This is typically used for uploading
2463
     * data files which may be binary and large.
2464
     */
2465
    private void handleMultipartForm(HttpServletRequest request,
2466
            HttpServletResponse response)
2467
    {
2468
        PrintWriter out = null;
2469
        String action = null;
2470

    
2471
        // Parse the multipart form, and save the parameters in a Hashtable and
2472
        // save the FileParts in a hashtable
2473

    
2474
        Hashtable params = new Hashtable();
2475
        Hashtable fileList = new Hashtable();
2476
        int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2477
                .intValue();
2478
        logMetacat.info(
2479
                "The limit size of data file is: " + sizeLimit);
2480

    
2481
        try {
2482
            // MBJ: need to put filesize limit in Metacat config
2483
            // (metacat.properties)
2484
            MultipartParser mp = new MultipartParser(request,
2485
                    sizeLimit * 1024 * 1024);
2486
            Part part;
2487
            while ((part = mp.readNextPart()) != null) {
2488
                String name = part.getName();
2489

    
2490
                if (part.isParam()) {
2491
                    // it's a parameter part
2492
                    ParamPart paramPart = (ParamPart) part;
2493
                    String value = paramPart.getStringValue();
2494
                    params.put(name, value);
2495
                    if (name.equals("action")) {
2496
                        action = value;
2497
                    }
2498
                } else if (part.isFile()) {
2499
                    // it's a file part
2500
                    FilePart filePart = (FilePart) part;
2501
                    fileList.put(name, filePart);
2502

    
2503
                    // Stop once the first file part is found, otherwise going
2504
                    // onto the
2505
                    // next part prevents access to the file contents. So...for
2506
                    // upload
2507
                    // to work, the datafile must be the last part
2508
                    break;
2509
                }
2510
            }
2511
        } catch (IOException ioe) {
2512
            try {
2513
                out = response.getWriter();
2514
            } catch (IOException ioe2) {
2515
                logMetacat.fatal("Fatal Error: couldn't get response output stream.");
2516
            }
2517
            out.println("<?xml version=\"1.0\"?>");
2518
            out.println("<error>");
2519
            out.println("Error: problem reading multipart data.");
2520
            out.println("</error>");
2521
        }
2522

    
2523
        // Get the session information
2524
        String username = null;
2525
        String password = null;
2526
        String[] groupnames = null;
2527
        String sess_id = null;
2528

    
2529
        // be aware of session expiration on every request
2530
        HttpSession sess = request.getSession(true);
2531
        if (sess.isNew()) {
2532
            // session expired or has not been stored b/w user requests
2533
            username = "public";
2534
            sess.setAttribute("username", username);
2535
        } else {
2536
            username = (String) sess.getAttribute("username");
2537
            password = (String) sess.getAttribute("password");
2538
            groupnames = (String[]) sess.getAttribute("groupnames");
2539
            try {
2540
                sess_id = (String) sess.getId();
2541
            } catch (IllegalStateException ise) {
2542
                System.out
2543
                        .println("error in  handleMultipartForm: this shouldn't "
2544
                                + "happen: the session should be valid: "
2545
                                + ise.getMessage());
2546
            }
2547
        }
2548

    
2549
        // Get the out stream
2550
        try {
2551
            out = response.getWriter();
2552
        } catch (IOException ioe2) {
2553
            logMetacat.error("Fatal Error: couldn't get response "
2554
                    + "output stream.");
2555
        }
2556

    
2557
        if (action.equals("upload")) {
2558
            if (username != null && !username.equals("public")) {
2559
                handleUploadAction(request, out, params, fileList, username,
2560
                        groupnames);
2561
            } else {
2562

    
2563
                out.println("<?xml version=\"1.0\"?>");
2564
                out.println("<error>");
2565
                out.println("Permission denied for " + action);
2566
                out.println("</error>");
2567
            }
2568
        } else {
2569
            /*
2570
             * try { out = response.getWriter(); } catch (IOException ioe2) {
2571
             * System.err.println("Fatal Error: couldn't get response output
2572
             * stream.");
2573
             */
2574
            out.println("<?xml version=\"1.0\"?>");
2575
            out.println("<error>");
2576
            out.println(
2577
                    "Error: action not registered.  Please report this error.");
2578
            out.println("</error>");
2579
        }
2580
        out.close();
2581
    }
2582

    
2583
    /**
2584
     * Handle the upload action by saving the attached file to disk and
2585
     * registering it in the Metacat db
2586
     */
2587
    private void handleUploadAction(HttpServletRequest request,
2588
            PrintWriter out, Hashtable params, Hashtable fileList,
2589
            String username, String[] groupnames)
2590
    {
2591
        //PrintWriter out = null;
2592
        //Connection conn = null;
2593
        String action = null;
2594
        String docid = null;
2595

    
2596
        /*
2597
         * response.setContentType("text/xml"); try { out =
2598
         * response.getWriter(); } catch (IOException ioe2) {
2599
         * System.err.println("Fatal Error: couldn't get response output
2600
         * stream.");
2601
         */
2602

    
2603
        if (params.containsKey("docid")) {
2604
            docid = (String) params.get("docid");
2605
        }
2606

    
2607
        // Make sure we have a docid and datafile
2608
        if (docid != null && fileList.containsKey("datafile")) {
2609

    
2610
            // Get a reference to the file part of the form
2611
            FilePart filePart = (FilePart) fileList.get("datafile");
2612
            String fileName = filePart.getFileName();
2613
            logMetacat.warn("Uploading filename: " + fileName);
2614

    
2615
            // Check if the right file existed in the uploaded data
2616
            if (fileName != null) {
2617

    
2618
                try {
2619
                    //logMetacat.info("Upload datafile " + docid
2620
                    // +"...", 10);
2621
                    //If document get lock data file grant
2622
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2623
                        // register the file in the database (which generates
2624
                        // an exception
2625
                        //if the docid is not acceptable or other untoward
2626
                        // things happen
2627
                        DocumentImpl.registerDocument(fileName, "BIN", docid,
2628
                                username, groupnames);
2629

    
2630
                        // Save the data file to disk using "docid" as the name
2631
                        dataDirectory.mkdirs();
2632
                        File newFile = new File(dataDirectory, docid);
2633
                        long size = filePart.writeTo(newFile);
2634

    
2635
                        EventLog.getInstance().log(request.getRemoteAddr(),
2636
                                username, docid, "upload");
2637
                        // Force replication this data file
2638
                        // To data file, "insert" and update is same
2639
                        // The fourth parameter is null. Because it is
2640
                        // notification server
2641
                        // and this method is in MetaCatServerlet. It is
2642
                        // original command,
2643
                        // not get force replication info from another metacat
2644
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2645
                                docid, "insert", false, null);
2646

    
2647
                        // set content type and other response header fields
2648
                        // first
2649
                        out.println("<?xml version=\"1.0\"?>");
2650
                        out.println("<success>");
2651
                        out.println("<docid>" + docid + "</docid>");
2652
                        out.println("<size>" + size + "</size>");
2653
                        out.println("</success>");
2654
                    }
2655

    
2656
                } catch (Exception e) {
2657
                    out.println("<?xml version=\"1.0\"?>");
2658
                    out.println("<error>");
2659
                    out.println(e.getMessage());
2660
                    out.println("</error>");
2661
                }
2662
            } else {
2663
                // the field did not contain a file
2664
                out.println("<?xml version=\"1.0\"?>");
2665
                out.println("<error>");
2666
                out.println("The uploaded data did not contain a valid file.");
2667
                out.println("</error>");
2668
            }
2669
        } else {
2670
            // Error bcse docid missing or file missing
2671
            out.println("<?xml version=\"1.0\"?>");
2672
            out.println("<error>");
2673
            out.println("The uploaded data did not contain a valid docid "
2674
                    + "or valid file.");
2675
            out.println("</error>");
2676
        }
2677
    }
2678

    
2679
    /*
2680
     * A method to handle set access action
2681
     */
2682
    private void handleSetAccessAction(PrintWriter out, Hashtable params,
2683
            String username)
2684
    {
2685
        String[] docList = null;
2686
        String[] principalList = null;
2687
        String[] permissionList = null;
2688
        String[] permTypeList = null;
2689
        String[] permOrderList = null;
2690
        String permission = null;
2691
        String permType = null;
2692
        String permOrder = null;
2693
        Vector errorList = new Vector();
2694
        String error = null;
2695
        Vector successList = new Vector();
2696
        String success = null;
2697

    
2698
        // Get parameters
2699
        if (params.containsKey("docid")) {
2700
            docList = (String[]) params.get("docid");
2701
        }
2702
        if (params.containsKey("principal")) {
2703
            principalList = (String[]) params.get("principal");
2704
        }
2705
        if (params.containsKey("permission")) {
2706
            permissionList = (String[]) params.get("permission");
2707

    
2708
        }
2709
        if (params.containsKey("permType")) {
2710
            permTypeList = (String[]) params.get("permType");
2711

    
2712
        }
2713
        if (params.containsKey("permOrder")) {
2714
            permOrderList = (String[]) params.get("permOrder");
2715

    
2716
        }
2717

    
2718
        // Make sure the parameter is not null
2719
        if (docList == null || principalList == null || permTypeList == null
2720
                || permissionList == null) {
2721
            error = "Please check your parameter list, it should look like: "
2722
                    + "?action=setaccess&docid=pipeline.1.1&principal=public"
2723
                    + "&permission=read&permType=allow&permOrder=allowFirst";
2724
            errorList.addElement(error);
2725
            outputResponse(successList, errorList, out);
2726
            return;
2727
        }
2728

    
2729
        // Only select first element for permission, type and order
2730
        permission = permissionList[0];
2731
        permType = permTypeList[0];
2732
        if (permOrderList != null) {
2733
            permOrder = permOrderList[0];
2734
        }
2735

    
2736
        // Get package doctype set
2737
        Vector packageSet = MetaCatUtil.getOptionList(MetaCatUtil
2738
                .getOption("packagedoctypeset"));
2739
        //debug
2740
        if (packageSet != null) {
2741
            for (int i = 0; i < packageSet.size(); i++) {
2742
                logMetacat.info("doctype in package set: "
2743
                        + (String) packageSet.elementAt(i));
2744
            }
2745
        }
2746

    
2747
        // handle every accessionNumber
2748
        for (int i = 0; i < docList.length; i++) {
2749
            String accessionNumber = docList[i];
2750
            String owner = null;
2751
            String publicId = null;
2752
            // Get document owner and public id
2753
            try {
2754
                owner = getFieldValueForDoc(accessionNumber, "user_owner");
2755
                publicId = getFieldValueForDoc(accessionNumber, "doctype");
2756
            } catch (Exception e) {
2757
                logMetacat.error("Error in handleSetAccessAction: "
2758
                        + e.getMessage());
2759
                error = "Error in set access control for document - "
2760
                        + accessionNumber + e.getMessage();
2761
                errorList.addElement(error);
2762
                continue;
2763
            }
2764
            //check if user is the owner. Only owner can do owner
2765
            if (username == null || owner == null || !username.equals(owner)) {
2766
                error = "User - " + username
2767
                        + " does not have permission to set "
2768
                        + "access control for docid - " + accessionNumber;
2769
                errorList.addElement(error);
2770
                continue;
2771
            }
2772

    
2773
            // If docid publicid is BIN data file or other beta4, 6 package
2774
            // document
2775
            // we could not do set access control. Because we don't want
2776
            // inconsistent
2777
            // to its access docuemnt
2778
            if (publicId != null && packageSet != null
2779
                    && packageSet.contains(publicId)) {
2780
                error = "Could not set access control to document "
2781
                        + accessionNumber
2782
                        + "because it is in a pakcage and it has a access file for it";
2783
                errorList.addElement(error);
2784
                continue;
2785
            }
2786

    
2787
            // for every principle
2788
            for (int j = 0; j < principalList.length; j++) {
2789
                String principal = principalList[j];
2790
                try {
2791
                    //insert permission
2792
                    AccessControlForSingleFile accessControl = new AccessControlForSingleFile(
2793
                            accessionNumber, principal, permission, permType,
2794
                            permOrder);
2795
                    accessControl.insertPermissions();
2796
                    success = "Set access control to document "
2797
                            + accessionNumber + " successfully";
2798
                    successList.addElement(success);
2799
                } catch (Exception ee) {
2800
                    logMetacat.error(
2801
                            "Erorr in handleSetAccessAction2: "
2802
                                    + ee.getMessage());
2803
                    error = "Faild to set access control for document "
2804
                            + accessionNumber + " because " + ee.getMessage();
2805
                    errorList.addElement(error);
2806
                    continue;
2807
                }
2808
            }
2809
        }
2810
        outputResponse(successList, errorList, out);
2811
    }
2812

    
2813
    /*
2814
     * A method try to determin a docid's public id, if couldn't find null will
2815
     * be returned.
2816
     */
2817
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
2818
            throws Exception
2819
    {
2820
        if (accessionNumber == null || accessionNumber.equals("")
2821
                || fieldName == null || fieldName.equals("")) { throw new Exception(
2822
                "Docid or field name was not specified"); }
2823

    
2824
        PreparedStatement pstmt = null;
2825
        ResultSet rs = null;
2826
        String fieldValue = null;
2827
        String docId = null;
2828
        DBConnection conn = null;
2829
        int serialNumber = -1;
2830

    
2831
        // get rid of revision if access number has
2832
        docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2833
        try {
2834
            //check out DBConnection
2835
            conn = DBConnectionPool
2836
                    .getDBConnection("MetaCatServlet.getPublicIdForDoc");
2837
            serialNumber = conn.getCheckOutSerialNumber();
2838
            pstmt = conn.prepareStatement("SELECT " + fieldName
2839
                    + " FROM xml_documents " + "WHERE docid = ? ");
2840

    
2841
            pstmt.setString(1, docId);
2842
            pstmt.execute();
2843
            rs = pstmt.getResultSet();
2844
            boolean hasRow = rs.next();
2845
            int perm = 0;
2846
            if (hasRow) {
2847
                fieldValue = rs.getString(1);
2848
            } else {
2849
                throw new Exception("Could not find document: "
2850
                        + accessionNumber);
2851
            }
2852
        } catch (Exception e) {
2853
            logMetacat.error(
2854
                    "Exception in MetacatServlet.getPublicIdForDoc: "
2855
                            + e.getMessage());
2856
            throw e;
2857
        } finally {
2858
            try {
2859
                rs.close();
2860
                pstmt.close();
2861

    
2862
            } finally {
2863
                DBConnectionPool.returnDBConnection(conn, serialNumber);
2864
            }
2865
        }
2866
        return fieldValue;
2867
    }
2868

    
2869
    /*
2870
     * Get the list of documents from the database and return the list in an
2871
     * Vector of identifiers.
2872
     *
2873
     * @ returns the array of identifiers
2874
     */
2875
    private Vector getDocumentList() throws SQLException
2876
    {
2877
        Vector docList = new Vector();
2878
        PreparedStatement pstmt = null;
2879
        ResultSet rs = null;
2880
        DBConnection conn = null;
2881
        int serialNumber = -1;
2882

    
2883
        try {
2884
            //check out DBConnection
2885
            conn = DBConnectionPool
2886
                    .getDBConnection("MetaCatServlet.getDocumentList");
2887
            serialNumber = conn.getCheckOutSerialNumber();
2888
            pstmt = conn.prepareStatement("SELECT docid, rev"
2889
                    + " FROM xml_documents ");
2890
            pstmt.execute();
2891
            rs = pstmt.getResultSet();
2892
            while (rs.next()) {
2893
                String docid = rs.getString(1);
2894
                String rev = rs.getString(2);
2895
                docList.add(docid + "." + rev);
2896
            }
2897
        } catch (SQLException e) {
2898
            logMetacat.error(
2899
                    "Exception in MetacatServlet.getDocumentList: "
2900
                            + e.getMessage());
2901
            throw e;
2902
        } finally {
2903
            try {
2904
                rs.close();
2905
                pstmt.close();
2906

    
2907
            } catch (SQLException se) {
2908
                logMetacat.error(
2909
                    "Exception in MetacatServlet.getDocumentList: "
2910
                            + se.getMessage());
2911
                throw se;
2912
            } finally {
2913
                DBConnectionPool.returnDBConnection(conn, serialNumber);
2914
            }
2915
        }
2916
        return docList;
2917
    }
2918

    
2919
    /*
2920
     * A method to output setAccess action result
2921
     */
2922
    private void outputResponse(Vector successList, Vector errorList,
2923
            PrintWriter out)
2924
    {
2925
        boolean error = false;
2926
        boolean success = false;
2927
        // Output prolog
2928
        out.println(PROLOG);
2929
        // output success message
2930
        if (successList != null) {
2931
            for (int i = 0; i < successList.size(); i++) {
2932
                out.println(SUCCESS);
2933
                out.println((String) successList.elementAt(i));
2934
                out.println(SUCCESSCLOSE);
2935
                success = true;
2936
            }
2937
        }
2938
        // output error message
2939
        if (errorList != null) {
2940
            for (int i = 0; i < errorList.size(); i++) {
2941
                out.println(ERROR);
2942
                out.println((String) errorList.elementAt(i));
2943
                out.println(ERRORCLOSE);
2944
                error = true;
2945
            }
2946
        }
2947

    
2948
        // if no error and no success info, send a error that nothing happened
2949
        if (!error && !success) {
2950
            out.println(ERROR);
2951
            out.println("Nothing happend for setaccess action");
2952
            out.println(ERRORCLOSE);
2953
        }
2954
    }
2955
    
2956
    /**
2957
     * Method to get session table which store the session info
2958
     * @return
2959
     */
2960
    public static Hashtable getSessionHash()
2961
    {
2962
        return sessionHash;
2963
    }
2964
    
2965
    /*
2966
     * If the given docid only have one seperter, we need 
2967
     * append rev for it. The rev come from xml_documents
2968
     */
2969
    private static String appendRev(String docid) throws Exception
2970
    {
2971
        String newAccNum = null;
2972
        String separator = MetaCatUtil.getOption("accNumSeparator");
2973
        int firstIndex = docid.indexOf(separator);
2974
        int lastIndex = docid.lastIndexOf(separator);
2975
        if (firstIndex == lastIndex)
2976
        {
2977
            
2978
           //only one seperater
2979
            int rev = DBUtil.getLatestRevisionInDocumentTable(docid);
2980
            if (rev == -1)
2981
            {
2982
                throw new Exception("Couldn't find the document "+docid);
2983
            }
2984
            else
2985
            {
2986
                newAccNum = docid+ separator+ rev;
2987
            }
2988
        }
2989
        else
2990
        {
2991
            // in other suituation we don't change the docid
2992
            newAccNum = docid;
2993
        }
2994
        logMetacat.warn("The docid will be read is "+newAccNum);
2995
        return newAccNum;
2996
    }
2997
}
(42-42/63)