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: tao $'
10
 *     '$Date: 2005-11-22 17:44:29 -0800 (Tue, 22 Nov 2005) $'
11
 * '$Revision: 2776 $'
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.Timer;
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.apache.log4j.Logger;
62
import org.apache.log4j.PropertyConfigurator;
63
import org.ecoinformatics.eml.EMLParser;
64

    
65
import com.oreilly.servlet.multipart.FilePart;
66
import com.oreilly.servlet.multipart.MultipartParser;
67
import com.oreilly.servlet.multipart.ParamPart;
68
import com.oreilly.servlet.multipart.Part;
69

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

    
72
/**
73
 * A metadata catalog server implemented as a Java Servlet
74
 *
75
 * <p>
76
 * Valid parameters are: <br>
77
 * action=query -- query the values of all elements and attributes and return a
78
 * result set of nodes <br>
79
 * action=squery -- structured query (see pathquery.dtd) <br>
80
 * action= -- export a zip format for data packadge <br>
81
 * action=read -- read any metadata/data file from Metacat and from Internet
82
 * <br>
83
 * action=insert -- insert an XML document into the database store <br>
84
 * action=update -- update an XML document that is in the database store <br>
85
 * action=delete -- delete an XML document from the database store <br>
86
 * action=validate -- vallidate the xml contained in valtext <br>
87
 * doctype -- document type list returned by the query (publicID) <br>
88
 * qformat=xml -- display resultset from query in XML <br>
89
 * qformat=html -- display resultset from query in HTML <br>
90
 * qformat=zip -- zip resultset from query <br>
91
 * docid=34 -- display the document with the document ID number 34 <br>
92
 * doctext -- XML text of the document to load into the database <br>
93
 * acltext -- XML access text for a document to load into the database <br>
94
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog <br>
95
 * query -- actual query text (to go with 'action=query' or 'action=squery')
96
 * <br>
97
 * valtext -- XML text to be validated <br>
98
 * action=getaccesscontrol -- retrieve acl info for Metacat document <br>
99
 * action=getdoctypes -- retrieve all doctypes (publicID) <br>
100
 * action=getdtdschema -- retrieve a DTD or Schema file <br>
101
 * action=getdataguide -- retrieve a Data Guide <br>
102
 * action=getprincipals -- retrieve a list of principals in XML <br>
103
 * datadoc -- data document name (id) <br>
104
 * action=getlog -- get a report of events that have occurred in the system<br>
105
 * ipAddress --  filter on one or more IP addresses<br>
106
 * principal -- filter on one or more principals (LDAP DN syntax)<br>
107
 * docid -- filter on one or more document identifiers (with revision)<br>
108
 * event -- filter on event type (e.g., read, insert, update, delete)<br>
109
 * start -- filter out events before the start date-time<br>
110
 * end -- filter out events before the end date-time<br>
111
 * <p>
112
 * The particular combination of parameters that are valid for each particular
113
 * action value is quite specific. This documentation will be reorganized to
114
 * reflect this information.
115
 */
116
public class MetaCatServlet extends HttpServlet
117
{
118
    private static Hashtable sessionHash = new Hashtable();
119
    private Timer timer = null;
120
    
121
    // Constants -- these should be final in a servlet
122
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
123
    private static final String SUCCESS = "<success>";
124
    private static final String SUCCESSCLOSE = "</success>";
125
    private static final String ERROR = "<error>";
126
    private static final String ERRORCLOSE = "</error>";
127
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
128
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
129
    public static final String NAMESPACEKEYWORD = "xmlns";
130
    public static final String EML2KEYWORD = ":eml";
131
    public static final String XMLFORMAT = "xml";
132
    private static final String CONFIG_DIR = "WEB-INF";
133
    private static final String CONFIG_NAME = "metacat.properties"; 
134
    
135
    /**
136
     * Initialize the servlet by creating appropriate database connections
137
     */
138
    public void init(ServletConfig config) throws ServletException
139
    {
140
        try {
141
            super.init(config);
142
            ServletContext context = config.getServletContext();
143

    
144
            // Initialize the properties file for our options
145
            String dirPath = context.getRealPath(CONFIG_DIR);
146
            File propertyFile = new File(dirPath, CONFIG_NAME);
147

    
148
            String LOG_CONFIG_NAME = dirPath + "/log4j.properties";
149
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
150
            
151
            Options options = null;
152
            try {
153
                options = Options.initialize(propertyFile);
154
                MetaCatUtil.printMessage("Options configured: "
155
                        + options.getOption("configured"));
156
            } catch (IOException ioe) {
157
                Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
158
                logMetacat.error("Error in loading options: "
159
                        + ioe.getMessage());
160
            }
161

    
162
            MetaCatUtil util = new MetaCatUtil();
163

    
164
            //initialize DBConnection pool
165
            DBConnectionPool connPool = DBConnectionPool.getInstance();
166
            
167
            // Index the paths specified in the metacat.properties
168
            checkIndexPaths();
169

    
170
            // initiate the indexing Queue
171
            IndexingQueue.getInstance();
172
            
173
            // start the IndexingThread if indexingTimerTaskTime more than 0. 
174
            // It will index all the documents not yet indexed in the database             
175
            int indexingTimerTaskTime = Integer.parseInt(MetaCatUtil.getOption("indexingTimerTaskTime"));
176
            if(indexingTimerTaskTime > 0){
177
            	timer = new Timer();
178
            	timer.schedule(new IndexingTimerTask(), 0, indexingTimerTaskTime);
179
            }
180
            
181
            MetaCatUtil.printMessage("Metacat (" + Version.getVersion()
182
                               + ") initialized.");
183

    
184
        } catch (ServletException ex) {
185
            throw ex;
186
        } catch (SQLException e) {
187
            Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
188
            logMetacat.error("Error in MetacatServlet.init: "
189
                    + e.getMessage());
190
        }
191
    }
192

    
193
    /**
194
     * Close all db connections from the pool
195
     */
196
    public void destroy()
197
    {
198
        // Close all db connection
199
        System.out.println("Destroying MetacatServlet");
200
        timer.cancel();
201
        DBConnectionPool.release();
202
    }
203

    
204
    /** Handle "GET" method requests from HTTP clients */
205
    public void doGet(HttpServletRequest request, HttpServletResponse response)
206
            throws ServletException, IOException
207
    {
208

    
209
        // Process the data and send back the response
210
        handleGetOrPost(request, response);
211
    }
212

    
213
    /** Handle "POST" method requests from HTTP clients */
214
    public void doPost(HttpServletRequest request, HttpServletResponse response)
215
            throws ServletException, IOException
216
    {
217

    
218
        // Process the data and send back the response
219
        handleGetOrPost(request, response);
220
    }
221

    
222
    /**
223
     * Index the paths specified in the metacat.properties
224
     */
225
    private void checkIndexPaths() {
226
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
227
        MetaCatUtil.pathsForIndexing
228
            = MetaCatUtil.getOptionList(MetaCatUtil.getOption("indexPaths"));
229
    
230
        if (MetaCatUtil.pathsForIndexing != null) {
231
    
232
            MetaCatUtil.printMessage("Indexing paths specified in metacat.properties....");
233
    
234
            DBConnection conn = null;
235
            int serialNumber = -1;
236
            PreparedStatement pstmt = null;
237
            PreparedStatement pstmt1 = null;
238
            ResultSet rs = null;
239
    
240
            for (int i = 0; i < MetaCatUtil.pathsForIndexing.size(); i++) {
241
                logMetacat.debug("Checking if '"
242
                           + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
243
                           + "' is indexed.... ");
244
    
245
                try {
246
                    //check out DBConnection
247
                    conn = DBConnectionPool.
248
                        getDBConnection("MetaCatServlet.checkIndexPaths");
249
                    serialNumber = conn.getCheckOutSerialNumber();
250
    
251
                    pstmt = conn.prepareStatement(
252
                        "SELECT * FROM xml_path_index " + "WHERE path = ?");
253
                    pstmt.setString(1, (String) MetaCatUtil.pathsForIndexing
254
                                    .elementAt(i));
255
    
256
                    pstmt.execute();
257
                    rs = pstmt.getResultSet();
258
    
259
                    if (!rs.next()) {
260
                        logMetacat.debug(".....not indexed yet.");
261
                        rs.close();
262
                        pstmt.close();
263
                        conn.increaseUsageCount(1);
264
    
265
                        logMetacat.debug(
266
                              "Inserting following path in xml_path_index: "
267
                              + (String)MetaCatUtil.pathsForIndexing
268
                                                   .elementAt(i));
269
    
270
                        pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
271
                              + "n.nodedata, n.nodedatanumerical, n.parentnodeid"
272
                              + " FROM xml_nodes n, xml_index i WHERE"
273
                              + " i.path = ? and n.parentnodeid=i.nodeid and"
274
                              + " n.nodetype LIKE 'TEXT' order by n.parentnodeid");
275
                        pstmt.setString(1, (String) MetaCatUtil.
276
                                        pathsForIndexing.elementAt(i));
277
                        pstmt.execute();
278
                        rs = pstmt.getResultSet();
279
    
280
                        int count = 0;
281
                        logMetacat.debug(
282
                                       "Executed the select statement for: "
283
                                       + (String) MetaCatUtil.pathsForIndexing
284
                                         .elementAt(i));
285
    
286
                        try {
287
                            while (rs.next()) {
288
    
289
                                String docid = rs.getString(1);
290
                                String nodedata = rs.getString(2);
291
                                float nodedatanumerical = rs.getFloat(3);
292
                                int parentnodeid = rs.getInt(4);
293
    
294
                                if (!nodedata.trim().equals("")) {
295
                                    pstmt1 = conn.prepareStatement(
296
                                        "INSERT INTO xml_path_index"
297
                                        + " (docid, path, nodedata, "
298
                                        + "nodedatanumerical, parentnodeid)"
299
                                        + " VALUES (?, ?, ?, ?, ?)");
300
    
301
                                    pstmt1.setString(1, docid);
302
                                    pstmt1.setString(2, (String) MetaCatUtil.
303
                                                pathsForIndexing.elementAt(i));
304
                                    pstmt1.setString(3, nodedata);
305
                                    pstmt1.setFloat(4, nodedatanumerical);
306
                                    pstmt1.setInt(5, parentnodeid);
307
    
308
                                    pstmt1.execute();
309
                                    pstmt1.close();
310
    
311
                                    count++;
312
    
313
                                }
314
                            }
315
                        }
316
                        catch (Exception e) {
317
                            System.out.println("Exception:" + e.getMessage());
318
                            e.printStackTrace();
319
                        }
320
    
321
                        rs.close();
322
                        pstmt.close();
323
                        conn.increaseUsageCount(1);
324
    
325
                        logMetacat.info("Indexed " + count
326
                                + " records from xml_nodes for '"
327
                                + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
328
                                + "'");
329
    
330
                    } else {
331
                    	logMetacat.debug(".....already indexed.");
332
                    }
333
    
334
                    rs.close();
335
                    pstmt.close();
336
                    conn.increaseUsageCount(1);
337
    
338
                } catch (Exception e) {
339
                    logMetacat.error("Error in MetaCatServlet.checkIndexPaths: "
340
                                             + e.getMessage());
341
                }finally {
342
                    //check in DBonnection
343
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
344
                }
345
    
346
    
347
            }
348
    
349
            MetaCatUtil.printMessage("Path Indexing Completed");
350
        }
351
    }    
352

    
353
    /**
354
     * Control servlet response depending on the action parameter specified
355
     */
356
    private void handleGetOrPost(HttpServletRequest request,
357
            HttpServletResponse response) throws ServletException, IOException
358
    {
359
        MetaCatUtil util = new MetaCatUtil();
360
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
361
        
362
        /*
363
         * logMetacat.debug("Connection pool size: "
364
         * +connPool.getSizeOfDBConnectionPool(),10);
365
         * logMetacat.debug("Free DBConnection number: "
366
         */
367
        //If all DBConnection in the pool are free and DBConnection pool
368
        //size is greater than initial value, shrink the connection pool
369
        //size to initial value
370
        DBConnectionPool.shrinkDBConnectionPoolSize();
371

    
372
        //Debug message to print out the method which have a busy DBConnection
373
        try {
374
            DBConnectionPool pool = DBConnectionPool.getInstance();
375
            pool.printMethodNameHavingBusyDBConnection();
376
        } catch (SQLException e) {
377
            logMetacat.error("Error in MetacatServlet.handleGetOrPost: "
378
                    + e.getMessage());
379
            e.printStackTrace();
380
        }
381

    
382
        String ctype = request.getContentType();
383
        if (ctype != null && ctype.startsWith("multipart/form-data")) {
384
            handleMultipartForm(request, response);
385
        } else {
386

    
387
            String name = null;
388
            String[] value = null;
389
            String[] docid = new String[3];
390
            Hashtable params = new Hashtable();
391
            Enumeration paramlist = request.getParameterNames();
392

    
393
            while (paramlist.hasMoreElements()) {
394

    
395
                name = (String) paramlist.nextElement();
396
                value = request.getParameterValues(name);
397

    
398
                // Decode the docid and mouse click information
399
                if (name.endsWith(".y")) {
400
                    docid[0] = name.substring(0, name.length() - 2);
401
                    params.put("docid", docid);
402
                    name = "ypos";
403
                }
404
                if (name.endsWith(".x")) {
405
                    name = "xpos";
406
                }
407

    
408
                params.put(name, value);
409
            }
410

    
411
            //handle param is emptpy
412
            if (params.isEmpty() || params == null) { return; }
413

    
414
            //if the user clicked on the input images, decode which image
415
            //was clicked then set the action.
416
            if(params.get("action") == null){
417
                PrintWriter out = response.getWriter();
418
                response.setContentType("text/xml");
419
                out.println("<?xml version=\"1.0\"?>");
420
                out.println("<error>");
421
                out.println("Action not specified");
422
                out.println("</error>");
423
                out.close();
424
                return;
425
            }
426

    
427
            String action = ((String[]) params.get("action"))[0];
428
            logMetacat.info("Action is: " + action);
429

    
430
            // This block handles session management for the servlet
431
            // by looking up the current session information for all actions
432
            // other than "login" and "logout"
433
            String username = null;
434
            String password = null;
435
            String[] groupnames = null;
436
            String sess_id = null;
437
            name = null;
438
            
439
            // handle login action
440
            if (action.equals("login")) {
441
                PrintWriter out = response.getWriter();
442
                handleLoginAction(out, params, request, response);
443
                out.close();
444

    
445
                // handle logout action
446
            } else if (action.equals("logout")) {
447
                PrintWriter out = response.getWriter();
448
                handleLogoutAction(out, params, request, response);
449
                out.close();
450

    
451
                // handle shrink DBConnection request
452
            } else if (action.equals("shrink")) {
453
                PrintWriter out = response.getWriter();
454
                boolean success = false;
455
                //If all DBConnection in the pool are free and DBConnection
456
                // pool
457
                //size is greater than initial value, shrink the connection
458
                // pool
459
                //size to initial value
460
                success = DBConnectionPool.shrinkConnectionPoolSize();
461
                if (success) {
462
                    //if successfully shrink the pool size to initial value
463
                    out.println("DBConnection Pool shrunk successfully.");
464
                }//if
465
                else {
466
                    out.println("DBConnection pool not shrunk successfully.");
467
                }
468
                //close out put
469
                out.close();
470

    
471
                // aware of session expiration on every request
472
            } else {
473
                HttpSession sess = request.getSession(true);
474
                if (sess.isNew() && !params.containsKey("sessionid")) {
475
                    // session expired or has not been stored b/w user requests
476
                    logMetacat.info(
477
                            "The session is new or no sessionid is assigned. The user is public");
478
                    username = "public";
479
                    sess.setAttribute("username", username);
480
                } else {
481
                    logMetacat.info("The session is either old or "
482
                            + "has sessionid parameter");
483
                    try {
484
                        if (params.containsKey("sessionid")) {
485
                            sess_id = ((String[]) params.get("sessionid"))[0];
486
                            logMetacat.info("in has sessionid "
487
                                    + sess_id);
488
                            if (sessionHash.containsKey(sess_id)) {
489
                                logMetacat.info("find the id "
490
                                        + sess_id + " in hash table");
491
                                sess = (HttpSession) sessionHash.get(sess_id);
492
                            }
493
                        } else {
494
                            // we already store the session in login, so we
495
                            // don't need here
496
                            /*
497
                             * logMetacat.info("in no sessionid
498
                             * parameter ", 40); sess_id =
499
                             * (String)sess.getId();
500
                             * logMetacat.info("storing the session id "
501
                             * + sess_id + " which has username " +
502
                             * sess.getAttribute("username") + " into session
503
                             * hash in handleGetOrPost method", 35);
504
                             */
505
                        }
506
                    } catch (IllegalStateException ise) {
507
                        logMetacat.error(
508
                                "Error in handleGetOrPost: this shouldn't "
509
                                + "happen: the session should be valid: "
510
                                + ise.getMessage());
511
                    }
512

    
513
                    username = (String) sess.getAttribute("username");
514
                    logMetacat.info("The user name from session is: "
515
                            + username);
516
                    password = (String) sess.getAttribute("password");
517
                    groupnames = (String[]) sess.getAttribute("groupnames");
518
                    name = (String) sess.getAttribute("name");
519
                }
520

    
521
                //make user user username should be public
522
                if (username == null || (username.trim().equals(""))) {
523
                    username = "public";
524
                }
525
                logMetacat.info("The user is : " + username);
526
            }
527
            // Now that we know the session is valid, we can delegate the
528
            // request
529
            // to a particular action handler
530
            if (action.equals("query")) {
531
                PrintWriter out = response.getWriter();
532
                handleQuery(out, params, response, username, groupnames,
533
                        sess_id);
534
                out.close();
535
            } else if (action.equals("squery")) {
536
                PrintWriter out = response.getWriter();
537
                if (params.containsKey("query")) {
538
                    handleSQuery(out, params, response, username, groupnames,
539
                            sess_id);
540
                    out.close();
541
                } else {
542
                    out.println(
543
                            "Illegal action squery without \"query\" parameter");
544
                    out.close();
545
                }
546
            } else if (action.equals("export")) {
547

    
548
                handleExportAction(params, response, username,
549
                        groupnames, password);
550
            } else if (action.equals("read")) {
551
                handleReadAction(params, request, response, username, password,
552
                        groupnames);
553
            } else if (action.equals("readinlinedata")) {
554
                handleReadInlineDataAction(params, request, response, username,
555
                        password, groupnames);
556
            } else if (action.equals("insert") || action.equals("update")) {
557
                PrintWriter out = response.getWriter();
558
                if ((username != null) && !username.equals("public")) {
559
                    handleInsertOrUpdateAction(request, response,
560
                            out, params, username, groupnames);
561
                } else {
562
                    response.setContentType("text/xml");
563
                    out.println("<?xml version=\"1.0\"?>");
564
                    out.println("<error>");
565
                    out.println("Permission denied for user " + username + " "
566
                            + action);
567
                    out.println("</error>");
568
                }
569
                out.close();
570
            } else if (action.equals("delete")) {
571
                PrintWriter out = response.getWriter();
572
                if ((username != null) && !username.equals("public")) {
573
                    handleDeleteAction(out, params, request, response, username,
574
                            groupnames);
575
                } else {
576
                    response.setContentType("text/xml");
577
                    out.println("<?xml version=\"1.0\"?>");
578
                    out.println("<error>");
579
                    out.println("Permission denied for " + action);
580
                    out.println("</error>");
581
                }
582
                out.close();
583
            } else if (action.equals("validate")) {
584
                PrintWriter out = response.getWriter();
585
                handleValidateAction(out, params);
586
                out.close();
587
            } else if (action.equals("setaccess")) {
588
                PrintWriter out = response.getWriter();
589
                handleSetAccessAction(out, params, username);
590
                out.close();
591
            } else if (action.equals("getaccesscontrol")) {
592
                PrintWriter out = response.getWriter();
593
                handleGetAccessControlAction(out, params, response, username,
594
                        groupnames);
595
                out.close();
596
            } else if (action.equals("getprincipals")) {
597
                PrintWriter out = response.getWriter();
598
                handleGetPrincipalsAction(out, username, password);
599
                out.close();
600
            } else if (action.equals("getdoctypes")) {
601
                PrintWriter out = response.getWriter();
602
                handleGetDoctypesAction(out, params, response);
603
                out.close();
604
            } else if (action.equals("getdtdschema")) {
605
                PrintWriter out = response.getWriter();
606
                handleGetDTDSchemaAction(out, params, response);
607
                out.close();
608
            } else if (action.equals("getlastdocid")) {
609
                PrintWriter out = response.getWriter();
610
                handleGetMaxDocidAction(out, params, response);
611
                out.close();
612
            } else if (action.equals("getrevisionanddoctype")) {
613
                PrintWriter out = response.getWriter();
614
                handleGetRevisionAndDocTypeAction(out, params);
615
                out.close();
616
            } else if (action.equals("getversion")) {
617
                response.setContentType("text/xml");
618
                PrintWriter out = response.getWriter();
619
                out.println(Version.getVersionAsXml());
620
                out.close();
621
            } else if (action.equals("getlog")) {
622
                handleGetLogAction(params, request, response, username, groupnames);
623
            } else if (action.equals("getloggedinuserinfo")) {
624
                PrintWriter out = response.getWriter();
625
                response.setContentType("text/xml");
626
                out.println("<?xml version=\"1.0\"?>");
627
                out.println("\n<user>\n");
628
                out.println("\n<username>\n");
629
                out.println(username);
630
                out.println("\n</username>\n");
631
                if(name!=null){
632
                	out.println("\n<name>\n");
633
                	out.println(name);
634
                	out.println("\n</name>\n");
635
                }
636
                if(MetaCatUtil.isAdministrator(username, groupnames)){
637
                	out.println("<isAdministrator></isAdministrator>\n");	
638
                }
639
                if(MetaCatUtil.isModerator(username, groupnames)){
640
                	out.println("<isModerator></isModerator>\n");	
641
                }
642
                out.println("\n</user>\n");
643
                out.close();
644
            } else if (action.equals("buildindex")) {
645
                handleBuildIndexAction(params, request, response, username, groupnames);
646
            } else if (action.equals("login") || action.equals("logout")) {
647
                /*
648
            } else if (action.equals("protocoltest")) {
649
                String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
650
                try {
651
                    testURL = ((String[]) params.get("url"))[0];
652
                } catch (Throwable t) {
653
                }
654
                String phandler = System
655
                        .getProperty("java.protocol.handler.pkgs");
656
                response.setContentType("text/html");
657
                PrintWriter out = response.getWriter();
658
                out.println("<body bgcolor=\"white\">");
659
                out.println("<p>Handler property: <code>" + phandler
660
                        + "</code></p>");
661
                out.println("<p>Starting test for:<br>");
662
                out.println("    " + testURL + "</p>");
663
                try {
664
                    URL u = new URL(testURL);
665
                    out.println("<pre>");
666
                    out.println("Protocol: " + u.getProtocol());
667
                    out.println("    Host: " + u.getHost());
668
                    out.println("    Port: " + u.getPort());
669
                    out.println("    Path: " + u.getPath());
670
                    out.println("     Ref: " + u.getRef());
671
                    String pquery = u.getQuery();
672
                    out.println("   Query: " + pquery);
673
                    out.println("  Params: ");
674
                    if (pquery != null) {
675
                        Hashtable qparams = MetaCatUtil.parseQuery(u.getQuery());
676
                        for (Enumeration en = qparams.keys(); en
677
                                .hasMoreElements();) {
678
                            String pname = (String) en.nextElement();
679
                            String pvalue = (String) qparams.get(pname);
680
                            out.println("    " + pname + ": " + pvalue);
681
                        }
682
                    }
683
                    out.println("</pre>");
684
                    out.println("</body>");
685
                    out.close();
686
                } catch (MalformedURLException mue) {
687
                    System.out.println(
688
                            "bad url from MetacatServlet.handleGetOrPost");
689
                    out.println(mue.getMessage());
690
                    mue.printStackTrace(out);
691
                    out.close();
692
                }
693
                */
694
            } else {
695
                PrintWriter out = response.getWriter();
696
                out.println("<?xml version=\"1.0\"?>");
697
                out.println("<error>");
698
                out.println(
699
                     "Error: action not registered.  Please report this error.");
700
                out.println("</error>");
701
                out.close();
702
            }
703

    
704
            //util.closeConnections();
705
            // Close the stream to the client
706
            //out.close();
707
        }
708
    }
709

    
710
    // LOGIN & LOGOUT SECTION
711
    /**
712
     * Handle the login request. Create a new session object. Do user
713
     * authentication through the session.
714
     */
715
    private void handleLoginAction(PrintWriter out, Hashtable params,
716
            HttpServletRequest request, HttpServletResponse response)
717
    {
718
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
719
        AuthSession sess = null;
720

    
721
        if(params.get("username") == null){
722
            response.setContentType("text/xml");
723
            out.println("<?xml version=\"1.0\"?>");
724
            out.println("<error>");
725
            out.println("Username not specified");
726
            out.println("</error>");
727
            return;
728
        }
729

    
730
        if(params.get("password") == null){
731
            response.setContentType("text/xml");
732
            out.println("<?xml version=\"1.0\"?>");
733
            out.println("<error>");
734
            out.println("Password not specified");
735
            out.println("</error>");
736
            return;
737
        }
738

    
739
        String un = ((String[]) params.get("username"))[0];
740
        logMetacat.info("user " + un + " is trying to login");
741
        String pw = ((String[]) params.get("password"))[0];
742

    
743
        String qformat = "xml";
744
        if(params.get("qformat") != null){
745
            qformat = ((String[]) params.get("qformat"))[0];
746
        }
747

    
748
        try {
749
            sess = new AuthSession();
750
        } catch (Exception e) {
751
            System.out.println("error in MetacatServlet.handleLoginAction: "
752
                    + e.getMessage());
753
            out.println(e.getMessage());
754
            return;
755
        }
756
        boolean isValid = sess.authenticate(request, un, pw);
757

    
758
        //if it is authernticate is true, store the session
759
        if (isValid) {
760
            HttpSession session = sess.getSessions();
761
            String id = session.getId();
762
            logMetacat.info("Store session id " + id
763
                    + "which has username" + session.getAttribute("username")
764
                    + " into hash in login method");
765
            sessionHash.put(id, session);
766
        }
767

    
768
        // format and transform the output
769
        if (qformat.equals("xml")) {
770
            response.setContentType("text/xml");
771
            out.println(sess.getMessage());
772
        } else {
773
            try {
774
                DBTransform trans = new DBTransform();
775
                response.setContentType("text/html");
776
                trans.transformXMLDocument(sess.getMessage(),
777
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
778
                        out, null);
779
            } catch (Exception e) {
780

    
781
                logMetacat.error(
782
                        "Error in MetaCatServlet.handleLoginAction: "
783
                                + e.getMessage());
784
            }
785
        }
786
    }
787

    
788
    /**
789
     * Handle the logout request. Close the connection.
790
     */
791
    private void handleLogoutAction(PrintWriter out, Hashtable params,
792
            HttpServletRequest request, HttpServletResponse response)
793
    {
794
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
795
        String qformat = "xml";
796
        if(params.get("qformat") != null){
797
            qformat = ((String[]) params.get("qformat"))[0];
798
        }
799

    
800
        // close the connection
801
        HttpSession sess = request.getSession(false);
802
        logMetacat.info("After get session in logout request");
803
        if (sess != null) {
804
            logMetacat.info("The session id " + sess.getId()
805
                    + " will be invalidate in logout action");
806
            logMetacat.info("The session contains user "
807
                    + sess.getAttribute("username")
808
                    + " will be invalidate in logout action");
809
            sess.invalidate();
810
        }
811

    
812
        // produce output
813
        StringBuffer output = new StringBuffer();
814
        output.append("<?xml version=\"1.0\"?>");
815
        output.append("<logout>");
816
        output.append("User logged out");
817
        output.append("</logout>");
818

    
819
        //format and transform the output
820
        if (qformat.equals("xml")) {
821
            response.setContentType("text/xml");
822
            out.println(output.toString());
823
        } else {
824
            try {
825
                DBTransform trans = new DBTransform();
826
                response.setContentType("text/html");
827
                trans.transformXMLDocument(output.toString(),
828
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
829
                        out, null);
830
            } catch (Exception e) {
831
                logMetacat.error(
832
                        "Error in MetaCatServlet.handleLogoutAction"
833
                                + e.getMessage());
834
            }
835
        }
836
    }
837

    
838
    // END OF LOGIN & LOGOUT SECTION
839

    
840
    // SQUERY & QUERY SECTION
841
    /**
842
     * Retreive the squery xml, execute it and display it
843
     *
844
     * @param out the output stream to the client
845
     * @param params the Hashtable of parameters that should be included in the
846
     *            squery.
847
     * @param response the response object linked to the client
848
     * @param conn the database connection
849
     */
850
    private void handleSQuery(PrintWriter out, Hashtable params,
851
            HttpServletResponse response, String user, String[] groups,
852
            String sessionid)
853
    {
854
        double startTime = System.currentTimeMillis() / 1000;
855
        DBQuery queryobj = new DBQuery();
856
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
857
        double outPutTime = System.currentTimeMillis() / 1000;
858
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
859
        logMetacat.info("Total search time for action 'squery': "
860
                + (outPutTime - startTime));
861
    }
862

    
863
    /**
864
     * Create the xml query, execute it and display the results.
865
     *
866
     * @param out the output stream to the client
867
     * @param params the Hashtable of parameters that should be included in the
868
     *            squery.
869
     * @param response the response object linked to the client
870
     */
871
    private void handleQuery(PrintWriter out, Hashtable params,
872
            HttpServletResponse response, String user, String[] groups,
873
            String sessionid)
874
    {
875
        //create the query and run it
876
        String xmlquery = DBQuery.createSQuery(params);
877
        String[] queryArray = new String[1];
878
        queryArray[0] = xmlquery;
879
        params.put("query", queryArray);
880
        double startTime = System.currentTimeMillis() / 1000;
881
        DBQuery queryobj = new DBQuery();
882
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
883
        double outPutTime = System.currentTimeMillis() / 1000;
884
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
885
        logMetacat.info("Total search time for action 'query': "
886
                + (outPutTime - startTime));
887

    
888
        //handleSQuery(out, params, response,user, groups, sessionid);
889
    }
890

    
891
    // END OF SQUERY & QUERY SECTION
892

    
893
    //Exoport section
894
    /**
895
     * Handle the "export" request of data package from Metacat in zip format
896
     *
897
     * @param params the Hashtable of HTTP request parameters
898
     * @param response the HTTP response object linked to the client
899
     * @param user the username sent the request
900
     * @param groups the user's groupnames
901
     */
902
    private void handleExportAction(Hashtable params,
903
            HttpServletResponse response,
904
            String user, String[] groups, String passWord)
905
    {
906
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
907
        // Output stream
908
        ServletOutputStream out = null;
909
        // Zip output stream
910
        ZipOutputStream zOut = null;
911
        DBQuery queryObj = null;
912

    
913
        String[] docs = new String[10];
914
        String docId = "";
915

    
916
        try {
917
            // read the params
918
            if (params.containsKey("docid")) {
919
                docs = (String[]) params.get("docid");
920
            }
921
            // Create a DBuery to handle export
922
            queryObj = new DBQuery();
923
            // Get the docid
924
            docId = docs[0];
925
            // Make sure the client specify docid
926
            if (docId == null || docId.equals("")) {
927
                response.setContentType("text/xml"); //MIME type
928
                // Get a printwriter
929
                PrintWriter pw = response.getWriter();
930
                // Send back message
931
                pw.println("<?xml version=\"1.0\"?>");
932
                pw.println("<error>");
933
                pw.println("You didn't specify requested docid");
934
                pw.println("</error>");
935
                // Close printwriter
936
                pw.close();
937
                return;
938
            }
939
            // Get output stream
940
            out = response.getOutputStream();
941
            response.setContentType("application/zip"); //MIME type
942
            response.setHeader("Content-Disposition", 
943
            		"attachment; filename=" 
944
            		+ docId + ".zip"); // Set the name of the zip file
945
            		
946
            zOut = new ZipOutputStream(out);
947
            zOut = queryObj
948
                    .getZippedPackage(docId, out, user, groups, passWord);
949
            zOut.finish(); //terminate the zip file
950
            zOut.close(); //close the zip stream
951

    
952
        } catch (Exception e) {
953
            try {
954
                response.setContentType("text/xml"); //MIME type
955
                // Send error message back
956
                if (out != null) {
957
                    PrintWriter pw = new PrintWriter(out);
958
                    pw.println("<?xml version=\"1.0\"?>");
959
                    pw.println("<error>");
960
                    pw.println(e.getMessage());
961
                    pw.println("</error>");
962
                    // Close printwriter
963
                    pw.close();
964
                    // Close output stream
965
                    out.close();
966
                }
967
                // Close zip output stream
968
                if (zOut != null) {
969
                    zOut.close();
970
                }
971
            } catch (IOException ioe) {
972
                logMetacat.error("Problem with the servlet output "
973
                        + "in MetacatServlet.handleExportAction: "
974
                        + ioe.getMessage());
975
            }
976

    
977
            logMetacat.error(
978
                    "Error in MetacatServlet.handleExportAction: "
979
                            + e.getMessage());
980
            e.printStackTrace(System.out);
981

    
982
        }
983

    
984
    }
985

    
986
    /**
987
     * In eml2 document, the xml can have inline data and data was stripped off
988
     * and store in file system. This action can be used to read inline data
989
     * only
990
     *
991
     * @param params the Hashtable of HTTP request parameters
992
     * @param response the HTTP response object linked to the client
993
     * @param user the username sent the request
994
     * @param groups the user's groupnames
995
     */
996
    private void handleReadInlineDataAction(Hashtable params,
997
            HttpServletRequest request, HttpServletResponse response,
998
            String user, String passWord, String[] groups)
999
    {
1000
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1001
        String[] docs = new String[10];
1002
        String inlineDataId = null;
1003
        String docId = "";
1004
        ServletOutputStream out = null;
1005

    
1006
        try {
1007
            // read the params
1008
            if (params.containsKey("inlinedataid")) {
1009
                docs = (String[]) params.get("inlinedataid");
1010
            }
1011
            // Get the docid
1012
            inlineDataId = docs[0];
1013
            // Make sure the client specify docid
1014
            if (inlineDataId == null || inlineDataId.equals("")) {
1015
                throw new Exception("You didn't specify requested inlinedataid"); }
1016

    
1017
            // check for permission
1018
            docId = MetaCatUtil
1019
                    .getDocIdWithoutRevFromInlineDataID(inlineDataId);
1020
            PermissionController controller = new PermissionController(docId);
1021
            // check top level read permission
1022
            if (!controller.hasPermission(user, groups,
1023
                    AccessControlInterface.READSTRING))
1024
            {
1025
                throw new Exception("User " + user
1026
                        + " doesn't have permission " + " to read document "
1027
                        + docId);
1028
            }
1029
            else
1030
            {
1031
              //check data access level
1032
              try
1033
              {
1034
                Hashtable unReadableInlineDataList =
1035
                    PermissionController.getUnReadableInlineDataIdList(docId,
1036
                    user, groups, false);
1037
                if (unReadableInlineDataList.containsValue(
1038
                          MetaCatUtil.getInlineDataIdWithoutRev(inlineDataId)))
1039
                {
1040
                  throw new Exception("User " + user
1041
                       + " doesn't have permission " + " to read inlinedata "
1042
                       + inlineDataId);
1043

    
1044
                }//if
1045
              }//try
1046
              catch (Exception e)
1047
              {
1048
                throw e;
1049
              }//catch
1050
            }//else
1051

    
1052
            // Get output stream
1053
            out = response.getOutputStream();
1054
            // read the inline data from the file
1055
            String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
1056
            File lineData = new File(inlinePath, inlineDataId);
1057
            FileInputStream input = new FileInputStream(lineData);
1058
            byte[] buffer = new byte[4 * 1024];
1059
            int bytes = input.read(buffer);
1060
            while (bytes != -1) {
1061
                out.write(buffer, 0, bytes);
1062
                bytes = input.read(buffer);
1063
            }
1064
            out.close();
1065

    
1066
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1067
                    inlineDataId, "readinlinedata");
1068
        } catch (Exception e) {
1069
            try {
1070
                PrintWriter pw = null;
1071
                // Send error message back
1072
                if (out != null) {
1073
                    pw = new PrintWriter(out);
1074
                } else {
1075
                    pw = response.getWriter();
1076
                }
1077
                pw.println("<?xml version=\"1.0\"?>");
1078
                pw.println("<error>");
1079
                pw.println(e.getMessage());
1080
                pw.println("</error>");
1081
                // Close printwriter
1082
                pw.close();
1083
                // Close output stream if out is not null
1084
                if (out != null) {
1085
                    out.close();
1086
                }
1087
            } catch (IOException ioe) {
1088
                logMetacat.error("Problem with the servlet output "
1089
                        + "in MetacatServlet.handleExportAction: "
1090
                        + ioe.getMessage());
1091
            }
1092
            logMetacat.error(
1093
                    "Error in MetacatServlet.handleReadInlineDataAction: "
1094
                            + e.getMessage());
1095
        }
1096
    }
1097

    
1098
    /*
1099
     * Get the nodeid from xml_nodes for the inlinedataid
1100
     */
1101
    private long getInlineDataNodeId(String inLineDataId, String docId)
1102
            throws SQLException
1103
    {
1104
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1105
        long nodeId = 0;
1106
        String INLINE = "inline";
1107
        boolean hasRow;
1108
        PreparedStatement pStmt = null;
1109
        DBConnection conn = null;
1110
        int serialNumber = -1;
1111
        String sql = "SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? "
1112
                + "AND nodetype='TEXT' AND parentnodeid IN "
1113
                + "(SELECT nodeid FROM xml_nodes WHERE docid=? AND "
1114
                + "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
1115

    
1116
        try {
1117
            //check out DBConnection
1118
            conn = DBConnectionPool
1119
                    .getDBConnection("AccessControlList.isAllowFirst");
1120
            serialNumber = conn.getCheckOutSerialNumber();
1121

    
1122
            pStmt = conn.prepareStatement(sql);
1123
            //bind value
1124
            pStmt.setString(1, docId);//docid
1125
            pStmt.setString(2, inLineDataId);//inlinedataid
1126
            pStmt.setString(3, docId);
1127
            // excute query
1128
            pStmt.execute();
1129
            ResultSet rs = pStmt.getResultSet();
1130
            hasRow = rs.next();
1131
            // get result
1132
            if (hasRow) {
1133
                nodeId = rs.getLong(1);
1134
            }//if
1135

    
1136
        } catch (SQLException e) {
1137
            throw e;
1138
        } finally {
1139
            try {
1140
                pStmt.close();
1141
            } finally {
1142
                DBConnectionPool.returnDBConnection(conn, serialNumber);
1143
            }
1144
        }
1145
        logMetacat.debug("The nodeid for inlinedataid " + inLineDataId
1146
                + " is: " + nodeId);
1147
        return nodeId;
1148
    }
1149

    
1150
    /**
1151
     * Handle the "read" request of metadata/data files from Metacat or any
1152
     * files from Internet; transformed metadata XML document into HTML
1153
     * presentation if requested; zip files when more than one were requested.
1154
     *
1155
     * @param params the Hashtable of HTTP request parameters
1156
     * @param request the HTTP request object linked to the client
1157
     * @param response the HTTP response object linked to the client
1158
     * @param user the username sent the request
1159
     * @param groups the user's groupnames
1160
     */
1161
    private void handleReadAction(Hashtable params, HttpServletRequest request,
1162
            HttpServletResponse response, String user, String passWord,
1163
            String[] groups)
1164
    {
1165
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1166
        ServletOutputStream out = null;
1167
        ZipOutputStream zout = null;
1168
        PrintWriter pw = null;
1169
        boolean zip = false;
1170
        boolean withInlineData = true;
1171

    
1172
        try {
1173
            String[] docs = new String[0];
1174
            String docid = "";
1175
            String qformat = "";
1176
            String abstrpath = null;
1177

    
1178
            // read the params
1179
            if (params.containsKey("docid")) {
1180
                docs = (String[]) params.get("docid");
1181
            }
1182
            if (params.containsKey("qformat")) {
1183
                qformat = ((String[]) params.get("qformat"))[0];
1184
            }
1185
            // the param for only metadata (eml)
1186
            // we don't support read a eml document without inline data now.
1187
            /*if (params.containsKey("inlinedata")) {
1188

    
1189
                String inlineData = ((String[]) params.get("inlinedata"))[0];
1190
                if (inlineData.equalsIgnoreCase("false")) {
1191
                    withInlineData = false;
1192
                }
1193
            }*/
1194
            if ((docs.length > 1) || qformat.equals("zip")) {
1195
                zip = true;
1196
                out = response.getOutputStream();
1197
                response.setContentType("application/zip"); //MIME type
1198
                zout = new ZipOutputStream(out);
1199
            }
1200
            // go through the list of docs to read
1201
            for (int i = 0; i < docs.length; i++) {
1202
                try {
1203

    
1204
                    URL murl = new URL(docs[i]);
1205
                    Hashtable murlQueryStr = MetaCatUtil.parseQuery(
1206
                            murl.getQuery());
1207
                    // case docid="http://.../?docid=aaa"
1208
                    // or docid="metacat://.../?docid=bbb"
1209
                    if (murlQueryStr.containsKey("docid")) {
1210
                        // get only docid, eliminate the rest
1211
                        docid = (String) murlQueryStr.get("docid");
1212
                        if (zip) {
1213
                            addDocToZip(request, docid, zout, user, groups);
1214
                        } else {
1215
                            readFromMetacat(request, response, docid, qformat,
1216
                                    abstrpath, user, groups, zip, zout,
1217
                                    withInlineData, params);
1218
                        }
1219

    
1220
                        // case docid="http://.../filename"
1221
                    } else {
1222
                        docid = docs[i];
1223
                        if (zip) {
1224
                            addDocToZip(request, docid, zout, user, groups);
1225
                        } else {
1226
                            readFromURLConnection(response, docid);
1227
                        }
1228
                    }
1229

    
1230
                } catch (MalformedURLException mue) {
1231
                    docid = docs[i];
1232
                    if (zip) {
1233
                        addDocToZip(request, docid, zout, user, groups);
1234
                    } else {
1235
                        readFromMetacat(request, response, docid, qformat,
1236
                                abstrpath, user, groups, zip, zout,
1237
                                withInlineData, params);
1238
                    }
1239
                }
1240
            }
1241

    
1242
            if (zip) {
1243
                zout.finish(); //terminate the zip file
1244
                zout.close(); //close the zip stream
1245
            }
1246

    
1247
        } catch (McdbDocNotFoundException notFoundE) {
1248
            // To handle doc not found exception
1249
            // the docid which didn't be found
1250
            String notFoundDocId = notFoundE.getUnfoundDocId();
1251
            String notFoundRevision = notFoundE.getUnfoundRevision();
1252
            logMetacat.warn("Missed id: " + notFoundDocId);
1253
            logMetacat.warn("Missed rev: " + notFoundRevision);
1254
            try {
1255
                // read docid from remote server
1256
                readFromRemoteMetaCat(response, notFoundDocId,
1257
                        notFoundRevision, user, passWord, out, zip, zout);
1258
                // Close zout outputstream
1259
                if (zout != null) {
1260
                    zout.close();
1261
                }
1262
                // close output stream
1263
                if (out != null) {
1264
                    out.close();
1265
                }
1266

    
1267
            } catch (Exception exc) {
1268
                logMetacat.error(
1269
                        "Erorr in MetacatServlet.hanldReadAction: "
1270
                                + exc.getMessage());
1271
                try {
1272
                    if (out != null) {
1273
                        response.setContentType("text/xml");
1274
                        // Send back error message by printWriter
1275
                        pw = new PrintWriter(out);
1276
                        pw.println("<?xml version=\"1.0\"?>");
1277
                        pw.println("<error>");
1278
                        pw.println(notFoundE.getMessage());
1279
                        pw.println("</error>");
1280
                        pw.close();
1281
                        out.close();
1282

    
1283
                    } else {
1284
                        response.setContentType("text/xml"); //MIME type
1285
                        // Send back error message if out = null
1286
                        if (pw == null) {
1287
                            // If pw is null, open the respnose
1288
                            pw = response.getWriter();
1289
                        }
1290
                        pw.println("<?xml version=\"1.0\"?>");
1291
                        pw.println("<error>");
1292
                        pw.println(notFoundE.getMessage());
1293
                        pw.println("</error>");
1294
                        pw.close();
1295
                    }
1296
                    // close zout
1297
                    if (zout != null) {
1298
                        zout.close();
1299
                    }
1300
                } catch (IOException ie) {
1301
                    logMetacat.error("Problem with the servlet output "
1302
                            + "in MetacatServlet.handleReadAction: "
1303
                            + ie.getMessage());
1304
                }
1305
            }
1306
        } catch (Exception e) {
1307
            try {
1308

    
1309
                if (out != null) {
1310
                    response.setContentType("text/xml"); //MIME type
1311
                    pw = new PrintWriter(out);
1312
                    pw.println("<?xml version=\"1.0\"?>");
1313
                    pw.println("<error>");
1314
                    pw.println(e.getMessage());
1315
                    pw.println("</error>");
1316
                    pw.close();
1317
                    out.close();
1318
                } else {
1319
                    response.setContentType("text/xml"); //MIME type
1320
                    // Send back error message if out = null
1321
                    if (pw == null) {
1322
                        pw = response.getWriter();
1323
                    }
1324
                    pw.println("<?xml version=\"1.0\"?>");
1325
                    pw.println("<error>");
1326
                    pw.println(e.getMessage());
1327
                    pw.println("</error>");
1328
                    pw.close();
1329

    
1330
                }
1331
                // Close zip output stream
1332
                if (zout != null) {
1333
                    zout.close();
1334
                }
1335

    
1336
            } catch (IOException ioe) {
1337
                logMetacat.error("Problem with the servlet output "
1338
                        + "in MetacatServlet.handleReadAction: "
1339
                        + ioe.getMessage());
1340
                ioe.printStackTrace(System.out);
1341

    
1342
            }
1343

    
1344
            logMetacat.error(
1345
                    "Error in MetacatServlet.handleReadAction: "
1346
                            + e.getMessage());
1347
            //e.printStackTrace(System.out);
1348
        }
1349
    }
1350

    
1351
    /** read metadata or data from Metacat
1352
     */
1353
    private void readFromMetacat(HttpServletRequest request,
1354
            HttpServletResponse response, String docid, String qformat,
1355
            String abstrpath, String user, String[] groups, boolean zip,
1356
            ZipOutputStream zout, boolean withInlineData, Hashtable params)
1357
            throws ClassNotFoundException, IOException, SQLException,
1358
            McdbException, Exception
1359
    {
1360
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1361
        try {
1362
            
1363
            // here is hack for handle docid=john.10(in order to tell mike.jim.10.1
1364
            // mike.jim.10, we require to provide entire docid with rev). But
1365
            // some old client they only provide docid without rev, so we need
1366
            // to handle this suituation. First we will check how many
1367
            // seperator here, if only one, we will append the rev in xml_documents
1368
            // to the id.
1369
            docid = appendRev(docid);
1370
         
1371
            DocumentImpl doc = new DocumentImpl(docid);
1372

    
1373
            //check the permission for read
1374
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1375
                Exception e = new Exception("User " + user
1376
                        + " does not have permission"
1377
                        + " to read the document with the docid " + docid);
1378

    
1379
                throw e;
1380
            }
1381

    
1382
            if (doc.getRootNodeID() == 0) {
1383
                // this is data file
1384
                String filepath = MetaCatUtil.getOption("datafilepath");
1385
                if (!filepath.endsWith("/")) {
1386
                    filepath += "/";
1387
                }
1388
                String filename = filepath + docid;
1389
                FileInputStream fin = null;
1390
                fin = new FileInputStream(filename);
1391

    
1392
                //MIME type
1393
                String contentType = getServletContext().getMimeType(filename);
1394
                if (contentType == null) {
1395
                    ContentTypeProvider provider = new ContentTypeProvider(
1396
                            docid);
1397
                    contentType = provider.getContentType();
1398
                    logMetacat.info("Final contenttype is: "
1399
                            + contentType);
1400
                }
1401

    
1402
                response.setContentType(contentType);
1403
                // if we decide to use "application/octet-stream" for all data
1404
                // returns
1405
                // response.setContentType("application/octet-stream");
1406

    
1407
                try {
1408

    
1409
                    ServletOutputStream out = response.getOutputStream();
1410
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
1411
                    int b = fin.read(buf);
1412
                    while (b != -1) {
1413
                        out.write(buf, 0, b);
1414
                        b = fin.read(buf);
1415
                    }
1416
                } finally {
1417
                    if (fin != null) fin.close();
1418
                }
1419

    
1420
            } else {
1421
                // this is metadata doc
1422
                if (qformat.equals("xml") || qformat.equals("")) {
1423
                    // if equals "", that means no qformat is specified. hence
1424
                    // by default the document should be returned in xml format
1425
                    // set content type first
1426
                    response.setContentType("text/xml"); //MIME type
1427
                    PrintWriter out = response.getWriter();
1428
                    doc.toXml(out, user, groups, withInlineData);
1429
                } else {
1430
                    response.setContentType("text/html"); //MIME type
1431
                    PrintWriter out = response.getWriter();
1432

    
1433
                    // Look up the document type
1434
                    String doctype = doc.getDoctype();
1435
                    // Transform the document to the new doctype
1436
                    DBTransform dbt = new DBTransform();
1437
                    dbt.transformXMLDocument(doc.toString(user, groups,
1438
                            withInlineData), doctype, "-//W3C//HTML//EN",
1439
                            qformat, out, params);
1440
                }
1441

    
1442
            }
1443
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1444
                    docid, "read");
1445
        } catch (Exception except) {
1446
            throw except;
1447
        }
1448
    }
1449

    
1450
    /**
1451
     * read data from URLConnection
1452
     */
1453
    private void readFromURLConnection(HttpServletResponse response,
1454
            String docid) throws IOException, MalformedURLException
1455
    {
1456
        ServletOutputStream out = response.getOutputStream();
1457
        String contentType = getServletContext().getMimeType(docid); //MIME
1458
                                                                     // type
1459
        if (contentType == null) {
1460
            if (docid.endsWith(".xml")) {
1461
                contentType = "text/xml";
1462
            } else if (docid.endsWith(".css")) {
1463
                contentType = "text/css";
1464
            } else if (docid.endsWith(".dtd")) {
1465
                contentType = "text/plain";
1466
            } else if (docid.endsWith(".xsd")) {
1467
                contentType = "text/xml";
1468
            } else if (docid.endsWith("/")) {
1469
                contentType = "text/html";
1470
            } else {
1471
                File f = new File(docid);
1472
                if (f.isDirectory()) {
1473
                    contentType = "text/html";
1474
                } else {
1475
                    contentType = "application/octet-stream";
1476
                }
1477
            }
1478
        }
1479
        response.setContentType(contentType);
1480
        // if we decide to use "application/octet-stream" for all data returns
1481
        // response.setContentType("application/octet-stream");
1482

    
1483
        // this is http url
1484
        URL url = new URL(docid);
1485
        BufferedInputStream bis = null;
1486
        try {
1487
            bis = new BufferedInputStream(url.openStream());
1488
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1489
            int b = bis.read(buf);
1490
            while (b != -1) {
1491
                out.write(buf, 0, b);
1492
                b = bis.read(buf);
1493
            }
1494
        } finally {
1495
            if (bis != null) bis.close();
1496
        }
1497

    
1498
    }
1499

    
1500
    /**
1501
     * read file/doc and write to ZipOutputStream
1502
     *
1503
     * @param docid
1504
     * @param zout
1505
     * @param user
1506
     * @param groups
1507
     * @throws ClassNotFoundException
1508
     * @throws IOException
1509
     * @throws SQLException
1510
     * @throws McdbException
1511
     * @throws Exception
1512
     */
1513
    private void addDocToZip(HttpServletRequest request, String docid,
1514
            ZipOutputStream zout, String user, String[] groups) throws
1515
            ClassNotFoundException, IOException, SQLException, McdbException,
1516
            Exception
1517
    {
1518
        byte[] bytestring = null;
1519
        ZipEntry zentry = null;
1520

    
1521
        try {
1522
            URL url = new URL(docid);
1523

    
1524
            // this http url; read from URLConnection; add to zip
1525
            zentry = new ZipEntry(docid);
1526
            zout.putNextEntry(zentry);
1527
            BufferedInputStream bis = null;
1528
            try {
1529
                bis = new BufferedInputStream(url.openStream());
1530
                byte[] buf = new byte[4 * 1024]; // 4K buffer
1531
                int b = bis.read(buf);
1532
                while (b != -1) {
1533
                    zout.write(buf, 0, b);
1534
                    b = bis.read(buf);
1535
                }
1536
            } finally {
1537
                if (bis != null) bis.close();
1538
            }
1539
            zout.closeEntry();
1540

    
1541
        } catch (MalformedURLException mue) {
1542

    
1543
            // this is metacat doc (data file or metadata doc)
1544
            try {
1545
                DocumentImpl doc = new DocumentImpl(docid);
1546

    
1547
                //check the permission for read
1548
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1549
                    Exception e = new Exception("User " + user
1550
                            + " does not have "
1551
                            + "permission to read the document with the docid "
1552
                            + docid);
1553
                    throw e;
1554
                }
1555

    
1556
                if (doc.getRootNodeID() == 0) {
1557
                    // this is data file; add file to zip
1558
                    String filepath = MetaCatUtil.getOption("datafilepath");
1559
                    if (!filepath.endsWith("/")) {
1560
                        filepath += "/";
1561
                    }
1562
                    String filename = filepath + docid;
1563
                    FileInputStream fin = null;
1564
                    fin = new FileInputStream(filename);
1565
                    try {
1566

    
1567
                        zentry = new ZipEntry(docid);
1568
                        zout.putNextEntry(zentry);
1569
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
1570
                        int b = fin.read(buf);
1571
                        while (b != -1) {
1572
                            zout.write(buf, 0, b);
1573
                            b = fin.read(buf);
1574
                        }
1575
                    } finally {
1576
                        if (fin != null) fin.close();
1577
                    }
1578
                    zout.closeEntry();
1579

    
1580
                } else {
1581
                    // this is metadata doc; add doc to zip
1582
                    bytestring = doc.toString().getBytes();
1583
                    zentry = new ZipEntry(docid + ".xml");
1584
                    zentry.setSize(bytestring.length);
1585
                    zout.putNextEntry(zentry);
1586
                    zout.write(bytestring, 0, bytestring.length);
1587
                    zout.closeEntry();
1588
                }
1589
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1590
                        docid, "read");
1591
            } catch (Exception except) {
1592
                throw except;
1593
            }
1594
        }
1595
    }
1596

    
1597
    /**
1598
     * If metacat couldn't find a data file or document locally, it will read
1599
     * this docid from its home server. This is for the replication feature
1600
     */
1601
    private void readFromRemoteMetaCat(HttpServletResponse response,
1602
            String docid, String rev, String user, String password,
1603
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
1604
            throws Exception
1605
    {
1606
        // Create a object of RemoteDocument, "" is for zipEntryPath
1607
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
1608
                password, "");
1609
        String docType = remoteDoc.getDocType();
1610
        // Only read data file
1611
        if (docType.equals("BIN")) {
1612
            // If it is zip format
1613
            if (zip) {
1614
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
1615
            } else {
1616
                if (out == null) {
1617
                    out = response.getOutputStream();
1618
                }
1619
                response.setContentType("application/octet-stream");
1620
                remoteDoc.readDocumentFromRemoteServer(out);
1621
            }
1622
        } else {
1623
            throw new Exception("Docid: " + docid + "." + rev
1624
                    + " couldn't find");
1625
        }
1626
    }
1627

    
1628
    /**
1629
     * Handle the database putdocument request and write an XML document to the
1630
     * database connection
1631
     */
1632
    private void handleInsertOrUpdateAction(HttpServletRequest request,
1633
            HttpServletResponse response, PrintWriter out, Hashtable params,
1634
            String user, String[] groups)
1635
    {
1636
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1637
        DBConnection dbConn = null;
1638
        int serialNumber = -1;
1639

    
1640
        if(params.get("docid") == null){
1641
            out.println("<?xml version=\"1.0\"?>");
1642
            out.println("<error>");
1643
            out.println("Docid not specified");
1644
            out.println("</error>");
1645
            logMetacat.error("Docid not specified");
1646
            return;
1647
        }
1648
        
1649
        if(!MetaCatUtil.canInsertOrUpdate(user, groups)){
1650
        	out.println("<?xml version=\"1.0\"?>");
1651
            out.println("<error>");
1652
            out.println("User '" + user + "' not allowed to insert and update");
1653
            out.println("</error>");
1654
            logMetacat.error("User '" + user + "' not allowed to insert and update");
1655
            return;
1656
        }
1657

    
1658
        try {
1659
            // Get the document indicated
1660
            String[] doctext = (String[]) params.get("doctext");
1661
            String pub = null;
1662
            if (params.containsKey("public")) {
1663
                pub = ((String[]) params.get("public"))[0];
1664
            }
1665

    
1666
            StringReader dtd = null;
1667
            if (params.containsKey("dtdtext")) {
1668
                String[] dtdtext = (String[]) params.get("dtdtext");
1669
                try {
1670
                    if (!dtdtext[0].equals("")) {
1671
                        dtd = new StringReader(dtdtext[0]);
1672
                    }
1673
                } catch (NullPointerException npe) {
1674
                }
1675
            }
1676

    
1677
            if(doctext == null){
1678
                out.println("<?xml version=\"1.0\"?>");
1679
                out.println("<error>");
1680
                out.println("Document text not submitted");
1681
                out.println("</error>");
1682
                return;
1683
            }
1684

    
1685
            StringReader xml = new StringReader(doctext[0]);
1686
            boolean validate = false;
1687
            DocumentImplWrapper documentWrapper = null;
1688
            try {
1689
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1690
                // >
1691
                // in order to decide whether to use validation parser
1692
                validate = needDTDValidation(xml);
1693
                if (validate) {
1694
                    // set a dtd base validation parser
1695
                    String rule = DocumentImpl.DTD;
1696
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1697
                } else {
1698

    
1699
                    String namespace = findNamespace(xml);
1700
                    
1701
                	if (namespace != null) {
1702
                		if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1703
                				|| namespace.compareTo(
1704
                				DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1705
                			// set eml2 base	 validation parser
1706
                			String rule = DocumentImpl.EML200;
1707
                			// using emlparser to check id validation
1708
                			EMLParser parser = new EMLParser(doctext[0]);
1709
                			documentWrapper = new DocumentImplWrapper(rule, true);
1710
                		} else if (namespace.compareTo(
1711
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1712
                			// set eml2 base validation parser
1713
                			String rule = DocumentImpl.EML210;
1714
                			// using emlparser to check id validation
1715
                			EMLParser parser = new EMLParser(doctext[0]);
1716
                			documentWrapper = new DocumentImplWrapper(rule, true);
1717
                		} else {
1718
                			// set schema base validation parser
1719
                			String rule = DocumentImpl.SCHEMA;
1720
                			documentWrapper = new DocumentImplWrapper(rule, true);
1721
                		}
1722
                	} else {
1723
                		documentWrapper = new DocumentImplWrapper("", false);
1724
                	}
1725
                }
1726

    
1727
                String[] action = (String[]) params.get("action");
1728
                String[] docid = (String[]) params.get("docid");
1729
                String newdocid = null;
1730

    
1731
                String doAction = null;
1732
                if (action[0].equals("insert")) {
1733
                    doAction = "INSERT";
1734
                } else if (action[0].equals("update")) {
1735
                    doAction = "UPDATE";
1736
                }
1737

    
1738
                try {
1739
                    // get a connection from the pool
1740
                    dbConn = DBConnectionPool
1741
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1742
                    serialNumber = dbConn.getCheckOutSerialNumber();
1743

    
1744
                    // write the document to the database
1745
                    try {
1746
                        String accNumber = docid[0];
1747
                        logMetacat.debug("" + doAction + " "
1748
                                + accNumber + "...");
1749
                        if (accNumber.equals("")) {
1750
                            accNumber = null;
1751
                        }
1752
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1753
                                doAction, accNumber, user, groups);
1754
                        EventLog.getInstance().log(request.getRemoteAddr(),
1755
                                user, accNumber, action[0]);
1756
                    } catch (NullPointerException npe) {
1757
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1758
                                doAction, null, user, groups);
1759
                        EventLog.getInstance().log(request.getRemoteAddr(),
1760
                                user, "", action[0]);
1761
                    }
1762
                }
1763
                finally {
1764
                    // Return db connection
1765
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1766
                }
1767

    
1768
                // set content type and other response header fields first
1769
                //response.setContentType("text/xml");
1770
                out.println("<?xml version=\"1.0\"?>");
1771
                out.println("<success>");
1772
                out.println("<docid>" + newdocid + "</docid>");
1773
                out.println("</success>");
1774

    
1775
            } catch (NullPointerException npe) {
1776
                //response.setContentType("text/xml");
1777
                out.println("<?xml version=\"1.0\"?>");
1778
                out.println("<error>");
1779
                out.println(npe.getMessage());
1780
                out.println("</error>");
1781
                logMetacat.warn("Error in writing eml document to the database" + npe.getMessage());
1782
                npe.printStackTrace();
1783
            }
1784
        } catch (Exception e) {
1785
            //response.setContentType("text/xml");
1786
            out.println("<?xml version=\"1.0\"?>");
1787
            out.println("<error>");
1788
            out.println(e.getMessage());
1789
            out.println("</error>");
1790
            logMetacat.warn("Error in writing eml document to the database" + e.getMessage());
1791
            e.printStackTrace();
1792
        }
1793
    }
1794

    
1795
    /**
1796
     * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > in
1797
     * order to decide whether to use validation parser
1798
     */
1799
    private static boolean needDTDValidation(StringReader xmlreader)
1800
            throws IOException
1801
    {
1802
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1803
        StringBuffer cbuff = new StringBuffer();
1804
        java.util.Stack st = new java.util.Stack();
1805
        boolean validate = false;
1806
        int c;
1807
        int inx;
1808

    
1809
        // read from the stream until find the keywords
1810
        while ((st.empty() || st.size() < 4) && ((c = xmlreader.read()) != -1)) {
1811
            cbuff.append((char) c);
1812

    
1813
            // "<!DOCTYPE" keyword is found; put it in the stack
1814
            if ((inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1) {
1815
                cbuff = new StringBuffer();
1816
                st.push("<!DOCTYPE");
1817
            }
1818
            // "PUBLIC" keyword is found; put it in the stack
1819
            if ((inx = cbuff.toString().indexOf("PUBLIC")) != -1) {
1820
                cbuff = new StringBuffer();
1821
                st.push("PUBLIC");
1822
            }
1823
            // "SYSTEM" keyword is found; put it in the stack
1824
            if ((inx = cbuff.toString().indexOf("SYSTEM")) != -1) {
1825
                cbuff = new StringBuffer();
1826
                st.push("SYSTEM");
1827
            }
1828
            // ">" character is found; put it in the stack
1829
            // ">" is found twice: fisrt from <?xml ...?>
1830
            // and second from <!DOCTYPE ... >
1831
            if ((inx = cbuff.toString().indexOf(">")) != -1) {
1832
                cbuff = new StringBuffer();
1833
                st.push(">");
1834
            }
1835
        }
1836

    
1837
        // close the stream
1838
        xmlreader.reset();
1839

    
1840
        // check the stack whether it contains the keywords:
1841
        // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1842
        if (st.size() == 4) {
1843
            if (((String) st.pop()).equals(">")
1844
                    && (((String) st.peek()).equals("PUBLIC") | ((String) st
1845
                            .pop()).equals("SYSTEM"))
1846
                    && ((String) st.pop()).equals("<!DOCTYPE")) {
1847
                validate = true;
1848
            }
1849
        }
1850

    
1851
        logMetacat.info("Validation for dtd is " + validate);
1852
        return validate;
1853
    }
1854

    
1855
    // END OF INSERT/UPDATE SECTION
1856

    
1857
    /* check if the xml string contains key words to specify schema loocation */
1858
    private String findNamespace(StringReader xml) throws IOException
1859
    {
1860
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1861
        String namespace = null;
1862

    
1863
        String eml2_0_0NameSpace = DocumentImpl.EML2_0_0NAMESPACE;
1864
        String eml2_0_1NameSpace = DocumentImpl.EML2_0_1NAMESPACE;
1865
        String eml2_1_0NameSpace = DocumentImpl.EML2_1_0NAMESPACE;
1866

    
1867
        if (xml == null) {
1868
            logMetacat.debug("Validation for schema is "
1869
                    + namespace);
1870
            return namespace;
1871
        }
1872
        String targetLine = getSchemaLine(xml);
1873

    
1874
        if (targetLine != null) {
1875

    
1876
        	// find if the root element has prefix
1877
        	String prefix = getPrefix(targetLine);
1878
        	logMetacat.info("prefix is:" + prefix);
1879
        	int startIndex = 0;
1880
        	
1881
        	
1882
        	if(prefix != null)
1883
        	{
1884
        		// if prefix found then look for xmlns:prefix
1885
        		// element to find the ns 
1886
        		String namespaceWithPrefix = NAMESPACEKEYWORD 
1887
        					+ ":" + prefix;
1888
        		startIndex = targetLine.indexOf(namespaceWithPrefix);
1889
            	logMetacat.debug("namespaceWithPrefix is:" + namespaceWithPrefix+":");
1890
            	logMetacat.debug("startIndex is:" + startIndex);
1891
        		
1892
        	} else {
1893
        		// if prefix not found then look for xmlns
1894
        		// attribute to find the ns 
1895
        		startIndex = targetLine.indexOf(NAMESPACEKEYWORD);
1896
            	logMetacat.debug("startIndex is:" + startIndex);
1897
        	}
1898
        		
1899
            int start = 1;
1900
            int end = 1;
1901
            String namespaceString = null;
1902
            int count = 0;
1903
            if (startIndex != -1) {
1904
                for (int i = startIndex; i < targetLine.length(); i++) {
1905
                    if (targetLine.charAt(i) == '"') {
1906
                        count++;
1907
                    }
1908
                    if (targetLine.charAt(i) == '"' && count == 1) {
1909
                        start = i;
1910
                    }
1911
                    if (targetLine.charAt(i) == '"' && count == 2) {
1912
                        end = i;
1913
                        break;
1914
                    }
1915
                }
1916
            } 
1917
            // else: xmlns not found. namespace = null will be returned
1918

    
1919
         	logMetacat.debug("targetLine is " + targetLine);
1920
         	logMetacat.debug("start is " + end);
1921
         	logMetacat.debug("end is " + end);
1922
           
1923
            if(start < end){
1924
            	namespaceString = targetLine.substring(start + 1, end);
1925
            	logMetacat.debug("namespaceString is " + namespaceString);
1926
            }
1927
            logMetacat.debug("namespace in xml is: "
1928
                    + namespaceString);
1929
            if(namespaceString != null){
1930
            	if (namespaceString.indexOf(eml2_0_0NameSpace) != -1) {
1931
            		namespace = eml2_0_0NameSpace;
1932
            	} else if (namespaceString.indexOf(eml2_0_1NameSpace) != -1) {
1933
            		namespace = eml2_0_1NameSpace;
1934
            	} else if (namespaceString.indexOf(eml2_1_0NameSpace) != -1) {
1935
            		namespace = eml2_1_0NameSpace;
1936
            	} else {
1937
            		namespace = namespaceString;
1938
            	}
1939
            }
1940
        }
1941

    
1942
        logMetacat.debug("Validation for eml is " + namespace);
1943

    
1944
        return namespace;
1945

    
1946
    }
1947

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

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

    
2001
    private String getPrefix(String schemaLine)
2002
    {
2003
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2004
    	String prefix = null;
2005
    	String rootElement = schemaLine.substring(0, schemaLine.indexOf(" "));
2006
        logMetacat.debug("rootElement:" + rootElement);
2007
        
2008
        if(rootElement.indexOf(":") > 0){
2009
        	prefix = rootElement.substring(rootElement.indexOf(":") + 1,
2010
        			rootElement.length());
2011
        } 
2012
        return prefix.trim();
2013
    }
2014

    
2015
    /**
2016
     * Handle the database delete request and delete an XML document from the
2017
     * database connection
2018
     */
2019
    private void handleDeleteAction(PrintWriter out, Hashtable params,
2020
            HttpServletRequest request, HttpServletResponse response,
2021
            String user, String[] groups)
2022
    {
2023
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2024
        String[] docid = (String[]) params.get("docid");
2025

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

    
2035
            // delete the document from the database
2036
            try {
2037

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

    
2073
    /**
2074
     * Handle the validation request and return the results to the requestor
2075
     */
2076
    private void handleValidateAction(PrintWriter out, Hashtable params)
2077
    {
2078

    
2079
        // Get the document indicated
2080
        String valtext = null;
2081
        DBConnection dbConn = null;
2082
        int serialNumber = -1;
2083

    
2084
        try {
2085
            valtext = ((String[]) params.get("valtext"))[0];
2086
        } catch (Exception nullpe) {
2087

    
2088
            String docid = null;
2089
            try {
2090
                // Find the document id number
2091
                docid = ((String[]) params.get("docid"))[0];
2092

    
2093
                // Get the document indicated from the db
2094
                DocumentImpl xmldoc = new DocumentImpl(docid);
2095
                valtext = xmldoc.toString();
2096

    
2097
            } catch (NullPointerException npe) {
2098

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

    
2105
                out.println(e.getMessage());
2106
            }
2107
        }
2108

    
2109
        try {
2110
            // get a connection from the pool
2111
            dbConn = DBConnectionPool
2112
                    .getDBConnection("MetaCatServlet.handleValidateAction");
2113
            serialNumber = dbConn.getCheckOutSerialNumber();
2114
            DBValidate valobj = new DBValidate(dbConn);
2115
            boolean valid = valobj.validateString(valtext);
2116

    
2117
            // set content type and other response header fields first
2118

    
2119
            out.println(valobj.returnErrors());
2120

    
2121
        } catch (NullPointerException npe2) {
2122
            // set content type and other response header fields first
2123

    
2124
            out.println("<error>Error validating document.</error>");
2125
        } catch (Exception e) {
2126

    
2127
            out.println(e.getMessage());
2128
        } finally {
2129
            // Return db connection
2130
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2131
        }
2132
    }
2133

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

    
2153
        try {
2154
            // Make sure there is a docid
2155
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
2156
                    "User didn't specify docid!"); }//if
2157

    
2158
            // Create a DBUtil object
2159
            DBUtil dbutil = new DBUtil();
2160
            // Get a rev and doctype
2161
            String revAndDocType = dbutil
2162
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
2163
            out.println(revAndDocType);
2164

    
2165
        } catch (Exception e) {
2166
            // Handle exception
2167
            out.println("<?xml version=\"1.0\"?>");
2168
            out.println("<error>");
2169
            out.println(e.getMessage());
2170
            out.println("</error>");
2171
        }
2172

    
2173
    }
2174

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

    
2187
        try {
2188

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

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

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

    
2220
        } catch (Exception e) {
2221
            out.println("<?xml version=\"1.0\"?>");
2222
            out.println("<error>");
2223
            out.println(e.getMessage());
2224
            out.println("</error>");
2225
        }
2226
    }
2227

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

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

    
2255
        String doctype = null;
2256
        String[] doctypeArr = (String[]) params.get("doctype");
2257

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

    
2264
        try {
2265
            DBUtil dbutil = new DBUtil();
2266
            String dtdschema = dbutil.readDTDSchema(doctype);
2267
            out.println(dtdschema);
2268

    
2269
        } catch (Exception e) {
2270
            out.println("<?xml version=\"1.0\"?>");
2271
            out.println("<error>");
2272
            out.println(e.getMessage());
2273
            out.println("</error>");
2274
        }
2275

    
2276
    }
2277

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

    
2286
        String scope = ((String[]) params.get("scope"))[0];
2287
        if (scope == null) {
2288
            scope = ((String[]) params.get("username"))[0];
2289
        }
2290

    
2291
        try {
2292

    
2293
            DBUtil dbutil = new DBUtil();
2294
            String lastDocid = dbutil.getMaxDocid(scope);
2295
            out.println("<?xml version=\"1.0\"?>");
2296
            out.println("<lastDocid>");
2297
            out.println("  <scope>" + scope + "</scope>");
2298
            out.println("  <docid>" + lastDocid + "</docid>");
2299
            out.println("</lastDocid>");
2300

    
2301
        } catch (Exception e) {
2302
            out.println("<?xml version=\"1.0\"?>");
2303
            out.println("<error>");
2304
            out.println(e.getMessage());
2305
            out.println("</error>");
2306
        }
2307
    }
2308

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

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

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

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

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

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

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

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

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

    
2459
    /**
2460
     * Handle documents passed to metacat that are encoded using the
2461
     * "multipart/form-data" mime type. This is typically used for uploading
2462
     * data files which may be binary and large.
2463
     */
2464
    private void handleMultipartForm(HttpServletRequest request,
2465
            HttpServletResponse response)
2466
    {
2467
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
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 size limit of uploaded data files is: " + sizeLimit);
2480

    
2481
        try {
2482
            MultipartParser mp = new MultipartParser(request,
2483
                    sizeLimit * 1024 * 1024);
2484
            Part part;
2485
            while ((part = mp.readNextPart()) != null) {
2486
                String name = part.getName();
2487

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

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

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

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

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

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

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

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

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

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

    
2606
        // Make sure we have a docid and datafile
2607
        if (docid != null && fileList.containsKey("datafile")) {
2608
            logMetacat.info("Uploading data docid: " + docid);
2609
            // Get a reference to the file part of the form
2610
            FilePart filePart = (FilePart) fileList.get("datafile");
2611
            String fileName = filePart.getFileName();
2612
            logMetacat.info("Uploading filename: " + fileName);
2613
            // Check if the right file existed in the uploaded data
2614
            if (fileName != null) {
2615

    
2616
                try {
2617
                    //logMetacat.info("Upload datafile " + docid
2618
                    // +"...", 10);
2619
                    //If document get lock data file grant
2620
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2621
                        // Save the data file to disk using "docid" as the name
2622
                        String datafilepath = MetaCatUtil.getOption("datafilepath");
2623
                        File dataDirectory = new File(datafilepath);
2624
                        dataDirectory.mkdirs();
2625
                        File newFile = null;
2626
                        long size = 0;
2627
                        try
2628
                        {
2629
                          newFile = new File(dataDirectory, docid);
2630
                          size = filePart.writeTo(newFile);
2631
                        
2632
//                        register the file in the database (which generates
2633
                          // an exception
2634
                          //if the docid is not acceptable or other untoward
2635
                          // things happen
2636
                          DocumentImpl.registerDocument(fileName, "BIN", docid,
2637
                                username, groupnames);
2638
                        }
2639
                        catch (Exception ee)
2640
                        {
2641
                           //detelte the file to create
2642
                            newFile.delete();
2643
                            throw ee;
2644
                        }
2645

    
2646
                        EventLog.getInstance().log(request.getRemoteAddr(),
2647
                                username, docid, "upload");
2648
                        // Force replication this data file
2649
                        // To data file, "insert" and update is same
2650
                        // The fourth parameter is null. Because it is
2651
                        // notification server
2652
                        // and this method is in MetaCatServerlet. It is
2653
                        // original command,
2654
                        // not get force replication info from another metacat
2655
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2656
                                docid, "insert", false, null);
2657

    
2658
                        // set content type and other response header fields
2659
                        // first
2660
                        out.println("<?xml version=\"1.0\"?>");
2661
                        out.println("<success>");
2662
                        out.println("<docid>" + docid + "</docid>");
2663
                        out.println("<size>" + size + "</size>");
2664
                        out.println("</success>");
2665
                    }
2666

    
2667
                } catch (Exception e) {
2668
                    
2669
                    out.println("<?xml version=\"1.0\"?>");
2670
                    out.println("<error>");
2671
                    out.println(e.getMessage());
2672
                    out.println("</error>");
2673
                }
2674
            } else {
2675
                // the field did not contain a file
2676
                out.println("<?xml version=\"1.0\"?>");
2677
                out.println("<error>");
2678
                out.println("The uploaded data did not contain a valid file.");
2679
                out.println("</error>");
2680
            }
2681
        } else {
2682
            // Error bcse docid missing or file missing
2683
            out.println("<?xml version=\"1.0\"?>");
2684
            out.println("<error>");
2685
            out.println("The uploaded data did not contain a valid docid "
2686
                    + "or valid file.");
2687
            out.println("</error>");
2688
        }
2689
    }
2690

    
2691
    /*
2692
     * A method to handle set access action
2693
     */
2694
    private void handleSetAccessAction(PrintWriter out, Hashtable params,
2695
            String username)
2696
    {
2697
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2698
        String[] docList = null;
2699
        String[] principalList = null;
2700
        String[] permissionList = null;
2701
        String[] permTypeList = null;
2702
        String[] permOrderList = null;
2703
        String permission = null;
2704
        String permType = null;
2705
        String permOrder = null;
2706
        Vector errorList = new Vector();
2707
        String error = null;
2708
        Vector successList = new Vector();
2709
        String success = null;
2710

    
2711
        // Get parameters
2712
        if (params.containsKey("docid")) {
2713
            docList = (String[]) params.get("docid");
2714
        }
2715
        if (params.containsKey("principal")) {
2716
            principalList = (String[]) params.get("principal");
2717
        }
2718
        if (params.containsKey("permission")) {
2719
            permissionList = (String[]) params.get("permission");
2720

    
2721
        }
2722
        if (params.containsKey("permType")) {
2723
            permTypeList = (String[]) params.get("permType");
2724

    
2725
        }
2726
        if (params.containsKey("permOrder")) {
2727
            permOrderList = (String[]) params.get("permOrder");
2728

    
2729
        }
2730

    
2731
        // Make sure the parameter is not null
2732
        if (docList == null || principalList == null || permTypeList == null
2733
                || permissionList == null) {
2734
            error = "Please check your parameter list, it should look like: "
2735
                    + "?action=setaccess&docid=pipeline.1.1&principal=public"
2736
                    + "&permission=read&permType=allow&permOrder=allowFirst";
2737
            errorList.addElement(error);
2738
            outputResponse(successList, errorList, out);
2739
            return;
2740
        }
2741

    
2742
        // Only select first element for permission, type and order
2743
        permission = permissionList[0];
2744
        permType = permTypeList[0];
2745
        if (permOrderList != null) {
2746
            permOrder = permOrderList[0];
2747
        }
2748

    
2749
        // Get package doctype set
2750
        Vector packageSet = MetaCatUtil.getOptionList(MetaCatUtil
2751
                .getOption("packagedoctypeset"));
2752
        //debug
2753
        if (packageSet != null) {
2754
            for (int i = 0; i < packageSet.size(); i++) {
2755
                logMetacat.debug("doctype in package set: "
2756
                        + (String) packageSet.elementAt(i));
2757
            }
2758
        }
2759

    
2760
        // handle every accessionNumber
2761
        for (int i = 0; i < docList.length; i++) {
2762
            String accessionNumber = docList[i];
2763
            String owner = null;
2764
            String publicId = null;
2765
            // Get document owner and public id
2766
            try {
2767
                owner = getFieldValueForDoc(accessionNumber, "user_owner");
2768
                publicId = getFieldValueForDoc(accessionNumber, "doctype");
2769
            } catch (Exception e) {
2770
                logMetacat.error("Error in handleSetAccessAction: "
2771
                        + e.getMessage());
2772
                error = "Error in set access control for document - "
2773
                        + accessionNumber + e.getMessage();
2774
                errorList.addElement(error);
2775
                continue;
2776
            }
2777
            //check if user is the owner. Only owner can do owner
2778
            if (username == null || owner == null || !username.equals(owner)) {
2779
                error = "User - " + username
2780
                        + " does not have permission to set "
2781
                        + "access control for docid - " + accessionNumber;
2782
                errorList.addElement(error);
2783
                continue;
2784
            }
2785

    
2786
            // If docid publicid is BIN data file or other beta4, 6 package
2787
            // document
2788
            // we could not do set access control. Because we don't want
2789
            // inconsistent
2790
            // to its access docuemnt
2791
            if (publicId != null && packageSet != null
2792
                    && packageSet.contains(publicId)) {
2793
                error = "Could not set access control to document "
2794
                        + accessionNumber
2795
                        + "because it is in a pakcage and it has a access file for it";
2796
                errorList.addElement(error);
2797
                continue;
2798
            }
2799

    
2800
            // for every principle
2801
            for (int j = 0; j < principalList.length; j++) {
2802
                String principal = principalList[j];
2803
                try {
2804
                    //insert permission
2805
                    AccessControlForSingleFile accessControl = new AccessControlForSingleFile(
2806
                            accessionNumber, principal, permission, permType,
2807
                            permOrder);
2808
                    accessControl.insertPermissions();
2809
                    success = "Set access control to document "
2810
                            + accessionNumber + " successfully";
2811
                    successList.addElement(success);
2812
                } catch (Exception ee) {
2813
                    logMetacat.error(
2814
                            "Erorr in handleSetAccessAction2: "
2815
                                    + ee.getMessage());
2816
                    error = "Faild to set access control for document "
2817
                            + accessionNumber + " because " + ee.getMessage();
2818
                    errorList.addElement(error);
2819
                    continue;
2820
                }
2821
            }
2822
        }
2823
        outputResponse(successList, errorList, out);
2824
    }
2825

    
2826
    /*
2827
     * A method try to determin a docid's public id, if couldn't find null will
2828
     * be returned.
2829
     */
2830
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
2831
            throws Exception
2832
    {
2833
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2834
        if (accessionNumber == null || accessionNumber.equals("")
2835
                || fieldName == null || fieldName.equals("")) { throw new Exception(
2836
                "Docid or field name was not specified"); }
2837

    
2838
        PreparedStatement pstmt = null;
2839
        ResultSet rs = null;
2840
        String fieldValue = null;
2841
        String docId = null;
2842
        DBConnection conn = null;
2843
        int serialNumber = -1;
2844

    
2845
        // get rid of revision if access number has
2846
        docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2847
        try {
2848
            //check out DBConnection
2849
            conn = DBConnectionPool
2850
                    .getDBConnection("MetaCatServlet.getPublicIdForDoc");
2851
            serialNumber = conn.getCheckOutSerialNumber();
2852
            pstmt = conn.prepareStatement("SELECT " + fieldName
2853
                    + " FROM xml_documents " + "WHERE docid = ? ");
2854

    
2855
            pstmt.setString(1, docId);
2856
            pstmt.execute();
2857
            rs = pstmt.getResultSet();
2858
            boolean hasRow = rs.next();
2859
            int perm = 0;
2860
            if (hasRow) {
2861
                fieldValue = rs.getString(1);
2862
            } else {
2863
                throw new Exception("Could not find document: "
2864
                        + accessionNumber);
2865
            }
2866
        } catch (Exception e) {
2867
            logMetacat.error(
2868
                    "Exception in MetacatServlet.getPublicIdForDoc: "
2869
                            + e.getMessage());
2870
            throw e;
2871
        } finally {
2872
            try {
2873
                rs.close();
2874
                pstmt.close();
2875

    
2876
            } finally {
2877
                DBConnectionPool.returnDBConnection(conn, serialNumber);
2878
            }
2879
        }
2880
        return fieldValue;
2881
    }
2882

    
2883
    /*
2884
     * Get the list of documents from the database and return the list in an
2885
     * Vector of identifiers.
2886
     *
2887
     * @ returns the array of identifiers
2888
     */
2889
    private Vector getDocumentList() throws SQLException
2890
    {
2891
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2892
        Vector docList = new Vector();
2893
        PreparedStatement pstmt = null;
2894
        ResultSet rs = null;
2895
        DBConnection conn = null;
2896
        int serialNumber = -1;
2897

    
2898
        try {
2899
            //check out DBConnection
2900
            conn = DBConnectionPool
2901
                    .getDBConnection("MetaCatServlet.getDocumentList");
2902
            serialNumber = conn.getCheckOutSerialNumber();
2903
            pstmt = conn.prepareStatement("SELECT docid, rev"
2904
                    + " FROM xml_documents ");
2905
            pstmt.execute();
2906
            rs = pstmt.getResultSet();
2907
            while (rs.next()) {
2908
                String docid = rs.getString(1);
2909
                String rev = rs.getString(2);
2910
                docList.add(docid + "." + rev);
2911
            }
2912
        } catch (SQLException e) {
2913
            logMetacat.error(
2914
                    "Exception in MetacatServlet.getDocumentList: "
2915
                            + e.getMessage());
2916
            throw e;
2917
        } finally {
2918
            try {
2919
                rs.close();
2920
                pstmt.close();
2921

    
2922
            } catch (SQLException se) {
2923
                logMetacat.error(
2924
                    "Exception in MetacatServlet.getDocumentList: "
2925
                            + se.getMessage());
2926
                throw se;
2927
            } finally {
2928
                DBConnectionPool.returnDBConnection(conn, serialNumber);
2929
            }
2930
        }
2931
        return docList;
2932
    }
2933

    
2934
    /*
2935
     * A method to output setAccess action result
2936
     */
2937
    private void outputResponse(Vector successList, Vector errorList,
2938
            PrintWriter out)
2939
    {
2940
        boolean error = false;
2941
        boolean success = false;
2942
        // Output prolog
2943
        out.println(PROLOG);
2944
        // output success message
2945
        if (successList != null) {
2946
            for (int i = 0; i < successList.size(); i++) {
2947
                out.println(SUCCESS);
2948
                out.println((String) successList.elementAt(i));
2949
                out.println(SUCCESSCLOSE);
2950
                success = true;
2951
            }
2952
        }
2953
        // output error message
2954
        if (errorList != null) {
2955
            for (int i = 0; i < errorList.size(); i++) {
2956
                out.println(ERROR);
2957
                out.println((String) errorList.elementAt(i));
2958
                out.println(ERRORCLOSE);
2959
                error = true;
2960
            }
2961
        }
2962

    
2963
        // if no error and no success info, send a error that nothing happened
2964
        if (!error && !success) {
2965
            out.println(ERROR);
2966
            out.println("Nothing happend for setaccess action");
2967
            out.println(ERRORCLOSE);
2968
        }
2969
    }
2970
    
2971
    /**
2972
     * Method to get session table which store the session info
2973
     * @return
2974
     */
2975
    public static Hashtable getSessionHash()
2976
    {
2977
        return sessionHash;
2978
    }
2979
    
2980
    /*
2981
     * If the given docid only have one seperter, we need 
2982
     * append rev for it. The rev come from xml_documents
2983
     */
2984
    private static String appendRev(String docid) throws Exception
2985
    {
2986
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2987
        String newAccNum = null;
2988
        String separator = MetaCatUtil.getOption("accNumSeparator");
2989
        int firstIndex = docid.indexOf(separator);
2990
        int lastIndex = docid.lastIndexOf(separator);
2991
        if (firstIndex == lastIndex)
2992
        {
2993
            
2994
           //only one seperater
2995
            int rev = DBUtil.getLatestRevisionInDocumentTable(docid);
2996
            if (rev == -1)
2997
            {
2998
                throw new Exception("the requested docid '"
2999
                        + docid+ "' does not exist");
3000
            }
3001
            else
3002
            {
3003
                newAccNum = docid+ separator+ rev;
3004
            }
3005
        }
3006
        else
3007
        {
3008
            // in other suituation we don't change the docid
3009
            newAccNum = docid;
3010
        }
3011
        //logMetacat.debug("The docid will be read is "+newAccNum);
3012
        return newAccNum;
3013
    }
3014
}
(43-43/64)