Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
7
 *    Release: @release@
8
 *
9
 *   '$Author: sgarg $'
10
 *     '$Date: 2004-07-22 15:32:48 -0700 (Thu, 22 Jul 2004) $'
11
 * '$Revision: 2225 $'
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.PropertyResourceBundle;
47
import java.util.Vector;
48
import java.util.zip.ZipEntry;
49
import java.util.zip.ZipOutputStream;
50

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

    
60
import edu.ucsb.nceas.utilities.Options;
61

    
62
import org.ecoinformatics.eml.EMLParser;
63

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

    
69
/**
70
 * A metadata catalog server implemented as a Java Servlet
71
 *
72
 * <p>
73
 * Valid parameters are: <br>
74
 * action=query -- query the values of all elements and attributes and return a
75
 * result set of nodes <br>
76
 * action=squery -- structured query (see pathquery.dtd) <br>
77
 * action= -- export a zip format for data packadge <br>
78
 * action=read -- read any metadata/data file from Metacat and from Internet
79
 * <br>
80
 * action=insert -- insert an XML document into the database store <br>
81
 * action=update -- update an XML document that is in the database store <br>
82
 * action=delete -- delete an XML document from the database store <br>
83
 * action=validate -- vallidate the xml contained in valtext <br>
84
 * doctype -- document type list returned by the query (publicID) <br>
85
 * qformat=xml -- display resultset from query in XML <br>
86
 * qformat=html -- display resultset from query in HTML <br>
87
 * qformat=zip -- zip resultset from query <br>
88
 * docid=34 -- display the document with the document ID number 34 <br>
89
 * doctext -- XML text of the document to load into the database <br>
90
 * acltext -- XML access text for a document to load into the database <br>
91
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog <br>
92
 * query -- actual query text (to go with 'action=query' or 'action=squery')
93
 * <br>
94
 * valtext -- XML text to be validated <br>
95
 * action=getaccesscontrol -- retrieve acl info for Metacat document <br>
96
 * action=getdoctypes -- retrieve all doctypes (publicID) <br>
97
 * action=getdtdschema -- retrieve a DTD or Schema file <br>
98
 * action=getdataguide -- retrieve a Data Guide <br>
99
 * action=getprincipals -- retrieve a list of principals in XML <br>
100
 * datadoc -- data document name (id) <br>
101
 * action=getlog -- get a report of events that have occurred in the system<br>
102
 * ipAddress --  filter on one or more IP addresses<br>
103
 * principal -- filter on one or more principals (LDAP DN syntax)<br>
104
 * docid -- filter on one or more document identifiers (with revision)<br>
105
 * event -- filter on event type (e.g., read, insert, update, delete)<br>
106
 * start -- filter out events before the start date-time<br>
107
 * end -- filter out events before the end date-time<br>
108
 * <p>
109
 * The particular combination of parameters that are valid for each particular
110
 * action value is quite specific. This documentation will be reorganized to
111
 * reflect this information.
112
 */
113
public class MetaCatServlet extends HttpServlet
114
{
115

    
116
    private ServletConfig config = null;
117

    
118
    private ServletContext context = null;
119

    
120
    private String resultStyleURL = null;
121

    
122
    private String xmlcatalogfile = null;
123

    
124
    private String saxparser = null;
125

    
126
    private String datafilepath = null;
127

    
128
    private File dataDirectory = null;
129

    
130
    private String servletpath = null;
131

    
132
    private String htmlpath = null;
133

    
134
    private PropertyResourceBundle options = null;
135

    
136
    private MetaCatUtil util = null;
137

    
138
    private DBConnectionPool connPool = null;
139

    
140
    private Hashtable sessionHash = new Hashtable();
141

    
142
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
143

    
144
    private static final String SUCCESS = "<success>";
145

    
146
    private static final String SUCCESSCLOSE = "</success>";
147

    
148
    private static final String ERROR = "<error>";
149

    
150
    private static final String ERRORCLOSE = "</error>";
151

    
152
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
153

    
154
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
155

    
156
    public static final String EML2KEYWORD = ":eml";
157

    
158
    public static final String XMLFORMAT = "xml";
159

    
160
    private static final String CONFIG_DIR = "WEB-INF";
161

    
162
    private static final String CONFIG_NAME = "metacat.properties";
163

    
164
    /**
165
     * Initialize the servlet by creating appropriate database connections
166
     */
167
    public void init(ServletConfig config) throws ServletException
168
    {
169
        try {
170
            super.init(config);
171
            this.config = config;
172
            this.context = config.getServletContext();
173

    
174
            // Initialize the properties file for our options
175
            String dirPath = context.getRealPath(CONFIG_DIR);
176
            File propertyFile = new File(dirPath, CONFIG_NAME);
177
            Options options = null;
178
            try {
179
                options = Options.initialize(propertyFile);
180
                MetaCatUtil.debugMessage("Options configured: "
181
                        + options.getOption("configured"), 20);
182
            } catch (IOException ioe) {
183
                MetaCatUtil.debugMessage("Error in loading options: "
184
                        + ioe.getMessage(), 20);
185
            }
186

    
187
            util = new MetaCatUtil();
188

    
189
            //initial DBConnection pool
190
            connPool = DBConnectionPool.getInstance();
191

    
192
            // Get the configuration file information
193
            resultStyleURL = MetaCatUtil.getOption("resultStyleURL");
194
            xmlcatalogfile = MetaCatUtil.getOption("xmlcatalogfile");
195
            saxparser = MetaCatUtil.getOption("saxparser");
196
            datafilepath = MetaCatUtil.getOption("datafilepath");
197
            dataDirectory = new File(datafilepath);
198
            servletpath = MetaCatUtil.getOption("servletpath");
199
            htmlpath = MetaCatUtil.getOption("htmlpath");
200

    
201
            System.out.println("Metacat (" + Version.getVersion()
202
                    + ") initialized.");
203
        } catch (ServletException ex) {
204
            throw ex;
205
        } catch (SQLException e) {
206
            MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
207
                    + e.getMessage(), 20);
208
        }
209
    }
210

    
211
    /**
212
     * Close all db connections from the pool
213
     */
214
    public void destroy()
215
    {
216
        // Close all db connection
217
        System.out.println("Destroying MetacatServlet");
218
        DBConnectionPool.release();
219
    }
220

    
221
    /** Handle "GET" method requests from HTTP clients */
222
    public void doGet(HttpServletRequest request, HttpServletResponse response)
223
            throws ServletException, IOException
224
    {
225

    
226
        // Process the data and send back the response
227
        handleGetOrPost(request, response);
228
    }
229

    
230
    /** Handle "POST" method requests from HTTP clients */
231
    public void doPost(HttpServletRequest request, HttpServletResponse response)
232
            throws ServletException, IOException
233
    {
234

    
235
        // Process the data and send back the response
236
        handleGetOrPost(request, response);
237
    }
238

    
239
    /**
240
     * Control servlet response depending on the action parameter specified
241
     */
242
    private void handleGetOrPost(HttpServletRequest request,
243
            HttpServletResponse response) throws ServletException, IOException
244
    {
245

    
246
        if (util == null) {
247
            util = new MetaCatUtil();
248
        }
249
        /*
250
         * MetaCatUtil.debugMessage("Connection pool size: "
251
         * +connPool.getSizeOfDBConnectionPool(),10);
252
         * MetaCatUtil.debugMessage("Free DBConnection number: "
253
         */
254
        //If all DBConnection in the pool are free and DBConnection pool
255
        //size is greater than initial value, shrink the connection pool
256
        //size to initial value
257
        DBConnectionPool.shrinkDBConnectionPoolSize();
258

    
259
        //Debug message to print out the method which have a busy DBConnection
260
        connPool.printMethodNameHavingBusyDBConnection();
261

    
262
        String ctype = request.getContentType();
263
        if (ctype != null && ctype.startsWith("multipart/form-data")) {
264
            handleMultipartForm(request, response);
265
        } else {
266

    
267
            String name = null;
268
            String[] value = null;
269
            String[] docid = new String[3];
270
            Hashtable params = new Hashtable();
271
            Enumeration paramlist = request.getParameterNames();
272

    
273
            while (paramlist.hasMoreElements()) {
274

    
275
                name = (String) paramlist.nextElement();
276
                value = request.getParameterValues(name);
277

    
278
                // Decode the docid and mouse click information
279
                if (name.endsWith(".y")) {
280
                    docid[0] = name.substring(0, name.length() - 2);
281
                    params.put("docid", docid);
282
                    name = "ypos";
283
                }
284
                if (name.endsWith(".x")) {
285
                    name = "xpos";
286
                }
287

    
288
                params.put(name, value);
289
            }
290

    
291
            //handle param is emptpy
292
            if (params.isEmpty() || params == null) { return; }
293

    
294
            //if the user clicked on the input images, decode which image
295
            //was clicked then set the action.
296
            String action = ((String[]) params.get("action"))[0];
297
            MetaCatUtil.debugMessage("Line 230: Action is: " + action, 1);
298

    
299
            // This block handles session management for the servlet
300
            // by looking up the current session information for all actions
301
            // other than "login" and "logout"
302
            String username = null;
303
            String password = null;
304
            String[] groupnames = null;
305
            String sess_id = null;
306

    
307
            // handle login action
308
            if (action.equals("login")) {
309
                PrintWriter out = response.getWriter();
310
                handleLoginAction(out, params, request, response);
311
                out.close();
312

    
313
                // handle logout action
314
            } else if (action.equals("logout")) {
315
                PrintWriter out = response.getWriter();
316
                handleLogoutAction(out, params, request, response);
317
                out.close();
318

    
319
                // handle shrink DBConnection request
320
            } else if (action.equals("shrink")) {
321
                PrintWriter out = response.getWriter();
322
                boolean success = false;
323
                //If all DBConnection in the pool are free and DBConnection
324
                // pool
325
                //size is greater than initial value, shrink the connection
326
                // pool
327
                //size to initial value
328
                success = DBConnectionPool.shrinkConnectionPoolSize();
329
                if (success) {
330
                    //if successfully shrink the pool size to initial value
331
                    out.println("DBConnection Pool shrunk successfully.");
332
                }//if
333
                else {
334
                    out.println("DBConnection pool not shrunk successfully.");
335
                }
336
                //close out put
337
                out.close();
338

    
339
                // aware of session expiration on every request
340
            } else {
341
                HttpSession sess = request.getSession(true);
342
                if (sess.isNew() && !params.containsKey("sessionid")) {
343
                    // session expired or has not been stored b/w user requests
344
                    MetaCatUtil.debugMessage(
345
                            "in session is new or no sessionid", 40);
346
                    username = "public";
347
                    sess.setAttribute("username", username);
348
                } else {
349
                    MetaCatUtil.debugMessage("in session is not new or "
350
                            + " has sessionid parameter", 40);
351
                    try {
352
                        if (params.containsKey("sessionid")) {
353
                            sess_id = ((String[]) params.get("sessionid"))[0];
354
                            MetaCatUtil.debugMessage("in has sessionid "
355
                                    + sess_id, 40);
356
                            if (sessionHash.containsKey(sess_id)) {
357
                                MetaCatUtil.debugMessage("find the id "
358
                                        + sess_id + " in hash table", 40);
359
                                sess = (HttpSession) sessionHash.get(sess_id);
360
                            }
361
                        } else {
362
                            // we already store the session in login, so we
363
                            // don't need here
364
                            /*
365
                             * MetaCatUtil.debugMessage("in no sessionid
366
                             * parameter ", 40); sess_id =
367
                             * (String)sess.getId();
368
                             * MetaCatUtil.debugMessage("storing the session id "
369
                             * + sess_id + " which has username " +
370
                             * sess.getAttribute("username") + " into session
371
                             * hash in handleGetOrPost method", 35);
372
                             */
373
                        }
374
                    } catch (IllegalStateException ise) {
375
                        System.out.println(
376
                                "error in handleGetOrPost: this shouldn't "
377
                                + "happen: the session should be valid: "
378
                                + ise.getMessage());
379
                    }
380

    
381
                    username = (String) sess.getAttribute("username");
382
                    MetaCatUtil.debugMessage("The user name from session is: "
383
                            + username, 20);
384
                    password = (String) sess.getAttribute("password");
385
                    groupnames = (String[]) sess.getAttribute("groupnames");
386
                }
387

    
388
                //make user user username should be public
389
                if (username == null || (username.trim().equals(""))) {
390
                    username = "public";
391
                }
392
                MetaCatUtil.debugMessage("The user is : " + username, 5);
393
            }
394
            // Now that we know the session is valid, we can delegate the
395
            // request
396
            // to a particular action handler
397
            if (action.equals("query")) {
398
                PrintWriter out = response.getWriter();
399
                handleQuery(out, params, response, username, groupnames,
400
                        sess_id);
401
                out.close();
402
            } else if (action.equals("squery")) {
403
                PrintWriter out = response.getWriter();
404
                if (params.containsKey("query")) {
405
                    handleSQuery(out, params, response, username, groupnames,
406
                            sess_id);
407
                    out.close();
408
                } else {
409
                    out.println(
410
                            "Illegal action squery without \"query\" parameter");
411
                    out.close();
412
                }
413
            } else if (action.equals("export")) {
414

    
415
                handleExportAction(params, response, username,
416
                        groupnames, password);
417
            } else if (action.equals("read")) {
418
                handleReadAction(params, request, response, username, password,
419
                        groupnames);
420
            } else if (action.equals("readinlinedata")) {
421
                handleReadInlineDataAction(params, request, response, username,
422
                        password, groupnames);
423
            } else if (action.equals("insert") || action.equals("update")) {
424
                PrintWriter out = response.getWriter();
425
                if ((username != null) && !username.equals("public")) {
426
                    handleInsertOrUpdateAction(request, response,
427
                            out, params, username, groupnames);
428
                } else {
429
                    out.println("Permission denied for user " + username + " "
430
                            + action);
431
                }
432
                out.close();
433
            } else if (action.equals("delete")) {
434
                PrintWriter out = response.getWriter();
435
                if ((username != null) && !username.equals("public")) {
436
                    handleDeleteAction(out, params, request, response, username,
437
                            groupnames);
438
                } else {
439
                    out.println("Permission denied for " + action);
440
                }
441
                out.close();
442
            } else if (action.equals("validate")) {
443
                PrintWriter out = response.getWriter();
444
                handleValidateAction(out, params);
445
                out.close();
446
            } else if (action.equals("setaccess")) {
447
                PrintWriter out = response.getWriter();
448
                handleSetAccessAction(out, params, username);
449
                out.close();
450
            } else if (action.equals("getaccesscontrol")) {
451
                PrintWriter out = response.getWriter();
452
                handleGetAccessControlAction(out, params, response, username,
453
                        groupnames);
454
                out.close();
455
            } else if (action.equals("getprincipals")) {
456
                PrintWriter out = response.getWriter();
457
                handleGetPrincipalsAction(out, username, password);
458
                out.close();
459
            } else if (action.equals("getdoctypes")) {
460
                PrintWriter out = response.getWriter();
461
                handleGetDoctypesAction(out, params, response);
462
                out.close();
463
            } else if (action.equals("getdtdschema")) {
464
                PrintWriter out = response.getWriter();
465
                handleGetDTDSchemaAction(out, params, response);
466
                out.close();
467
            } else if (action.equals("getlastdocid")) {
468
                PrintWriter out = response.getWriter();
469
                handleGetMaxDocidAction(out, params, response);
470
                out.close();
471
            } else if (action.equals("getrevisionanddoctype")) {
472
                PrintWriter out = response.getWriter();
473
                handleGetRevisionAndDocTypeAction(out, params);
474
                out.close();
475
            } else if (action.equals("getversion")) {
476
                response.setContentType("text/xml");
477
                PrintWriter out = response.getWriter();
478
                out.println(Version.getVersionAsXml());
479
                out.close();
480
            } else if (action.equals("getlog")) {
481
                handleGetLogAction(params, request, response);
482
            } else if (action.equals("login") || action.equals("logout")) {
483
            } else if (action.equals("protocoltest")) {
484
                String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
485
                try {
486
                    testURL = ((String[]) params.get("url"))[0];
487
                } catch (Throwable t) {
488
                }
489
                String phandler = System
490
                        .getProperty("java.protocol.handler.pkgs");
491
                response.setContentType("text/html");
492
                PrintWriter out = response.getWriter();
493
                out.println("<body bgcolor=\"white\">");
494
                out.println("<p>Handler property: <code>" + phandler
495
                        + "</code></p>");
496
                out.println("<p>Starting test for:<br>");
497
                out.println("    " + testURL + "</p>");
498
                try {
499
                    URL u = new URL(testURL);
500
                    out.println("<pre>");
501
                    out.println("Protocol: " + u.getProtocol());
502
                    out.println("    Host: " + u.getHost());
503
                    out.println("    Port: " + u.getPort());
504
                    out.println("    Path: " + u.getPath());
505
                    out.println("     Ref: " + u.getRef());
506
                    String pquery = u.getQuery();
507
                    out.println("   Query: " + pquery);
508
                    out.println("  Params: ");
509
                    if (pquery != null) {
510
                        Hashtable qparams = MetaCatUtil.parseQuery(u.getQuery());
511
                        for (Enumeration en = qparams.keys(); en
512
                                .hasMoreElements();) {
513
                            String pname = (String) en.nextElement();
514
                            String pvalue = (String) qparams.get(pname);
515
                            out.println("    " + pname + ": " + pvalue);
516
                        }
517
                    }
518
                    out.println("</pre>");
519
                    out.println("</body>");
520
                    out.close();
521
                } catch (MalformedURLException mue) {
522
                    System.out.println(
523
                            "bad url from MetacatServlet.handleGetOrPost");
524
                    out.println(mue.getMessage());
525
                    mue.printStackTrace(out);
526
                    out.close();
527
                }
528
            } else {
529
                PrintWriter out = response.getWriter();
530
                out.println("<?xml version=\"1.0\"?>");
531
                out.println("<error>");
532
                out.println(
533
                     "Error: action not registered.  Please report this error.");
534
                out.println("</error>");
535
                out.close();
536
            }
537

    
538
            //util.closeConnections();
539
            // Close the stream to the client
540
            //out.close();
541
        }
542
    }
543

    
544
    // LOGIN & LOGOUT SECTION
545
    /**
546
     * Handle the login request. Create a new session object. Do user
547
     * authentication through the session.
548
     */
549
    private void handleLoginAction(PrintWriter out, Hashtable params,
550
            HttpServletRequest request, HttpServletResponse response)
551
    {
552

    
553
        AuthSession sess = null;
554
        String un = ((String[]) params.get("username"))[0];
555
        MetaCatUtil.debugMessage("user " + un + " try to login", 20);
556
        String pw = ((String[]) params.get("password"))[0];
557
        String action = ((String[]) params.get("action"))[0];
558
        String qformat = ((String[]) params.get("qformat"))[0];
559

    
560
        try {
561
            sess = new AuthSession();
562
        } catch (Exception e) {
563
            System.out.println("error in MetacatServlet.handleLoginAction: "
564
                    + e.getMessage());
565
            out.println(e.getMessage());
566
            return;
567
        }
568
        boolean isValid = sess.authenticate(request, un, pw);
569

    
570
        //if it is authernticate is true, store the session
571
        if (isValid) {
572
            HttpSession session = sess.getSessions();
573
            String id = session.getId();
574
            MetaCatUtil.debugMessage("Store session id " + id
575
                    + "which has username" + session.getAttribute("username")
576
                    + " into hash in login method", 35);
577
            sessionHash.put(id, session);
578
        }
579

    
580
        // format and transform the output
581
        if (qformat.equals("xml")) {
582
            response.setContentType("text/xml");
583
            out.println(sess.getMessage());
584
        } else {
585
            try {
586
                DBTransform trans = new DBTransform();
587
                response.setContentType("text/html");
588
                trans.transformXMLDocument(sess.getMessage(),
589
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
590
                        out, null);
591
            } catch (Exception e) {
592

    
593
                MetaCatUtil.debugMessage(
594
                        "Error in MetaCatServlet.handleLoginAction: "
595
                                + e.getMessage(), 30);
596
            }
597
        }
598
    }
599

    
600
    /**
601
     * Handle the logout request. Close the connection.
602
     */
603
    private void handleLogoutAction(PrintWriter out, Hashtable params,
604
            HttpServletRequest request, HttpServletResponse response)
605
    {
606

    
607
        String qformat = ((String[]) params.get("qformat"))[0];
608

    
609
        // close the connection
610
        HttpSession sess = request.getSession(false);
611
        MetaCatUtil.debugMessage("After get session in logout request", 40);
612
        if (sess != null) {
613
            MetaCatUtil.debugMessage("The session id " + sess.getId()
614
                    + " will be invalidate in logout action", 30);
615
            MetaCatUtil.debugMessage("The session contains user "
616
                    + sess.getAttribute("username")
617
                    + " will be invalidate in logout action", 30);
618
            sess.invalidate();
619
        }
620

    
621
        // produce output
622
        StringBuffer output = new StringBuffer();
623
        output.append("<?xml version=\"1.0\"?>");
624
        output.append("<logout>");
625
        output.append("User logged out");
626
        output.append("</logout>");
627

    
628
        //format and transform the output
629
        if (qformat.equals("xml")) {
630
            response.setContentType("text/xml");
631
            out.println(output.toString());
632
        } else {
633
            try {
634
                DBTransform trans = new DBTransform();
635
                response.setContentType("text/html");
636
                trans.transformXMLDocument(output.toString(),
637
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
638
                        out, null);
639
            } catch (Exception e) {
640
                MetaCatUtil.debugMessage(
641
                        "Error in MetaCatServlet.handleLogoutAction"
642
                                + e.getMessage(), 30);
643
            }
644
        }
645
    }
646

    
647
    // END OF LOGIN & LOGOUT SECTION
648

    
649
    // SQUERY & QUERY SECTION
650
    /**
651
     * Retreive the squery xml, execute it and display it
652
     *
653
     * @param out the output stream to the client
654
     * @param params the Hashtable of parameters that should be included in the
655
     *            squery.
656
     * @param response the response object linked to the client
657
     * @param conn the database connection
658
     */
659
    protected void handleSQuery(PrintWriter out, Hashtable params,
660
            HttpServletResponse response, String user, String[] groups,
661
            String sessionid)
662
    {
663
        double startTime = System.currentTimeMillis() / 1000;
664
        DBQuery queryobj = new DBQuery(saxparser);
665
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
666
        double outPutTime = System.currentTimeMillis() / 1000;
667
        MetaCatUtil.debugMessage("total search time: "
668
                + (outPutTime - startTime), 30);
669

    
670
    }
671

    
672
    /**
673
     * Create the xml query, execute it and display the results.
674
     *
675
     * @param out the output stream to the client
676
     * @param params the Hashtable of parameters that should be included in the
677
     *            squery.
678
     * @param response the response object linked to the client
679
     */
680
    protected void handleQuery(PrintWriter out, Hashtable params,
681
            HttpServletResponse response, String user, String[] groups,
682
            String sessionid)
683
    {
684
        //create the query and run it
685
        String xmlquery = DBQuery.createSQuery(params);
686
        String[] queryArray = new String[1];
687
        queryArray[0] = xmlquery;
688
        params.put("query", queryArray);
689
        double startTime = System.currentTimeMillis() / 1000;
690
        DBQuery queryobj = new DBQuery(saxparser);
691
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
692
        double outPutTime = System.currentTimeMillis() / 1000;
693
        MetaCatUtil.debugMessage("total search time: "
694
                + (outPutTime - startTime), 30);
695

    
696
        //handleSQuery(out, params, response,user, groups, sessionid);
697
    }
698

    
699
    // END OF SQUERY & QUERY SECTION
700

    
701
    //Exoport section
702
    /**
703
     * Handle the "export" request of data package from Metacat in zip format
704
     *
705
     * @param params the Hashtable of HTTP request parameters
706
     * @param response the HTTP response object linked to the client
707
     * @param user the username sent the request
708
     * @param groups the user's groupnames
709
     */
710
    private void handleExportAction(Hashtable params,
711
            HttpServletResponse response,
712
            String user, String[] groups, String passWord)
713
    {
714
        // Output stream
715
        ServletOutputStream out = null;
716
        // Zip output stream
717
        ZipOutputStream zOut = null;
718
        DocumentImpl docImpls = null;
719
        DBQuery queryObj = null;
720

    
721
        String[] docs = new String[10];
722
        String docId = "";
723

    
724
        try {
725
            // read the params
726
            if (params.containsKey("docid")) {
727
                docs = (String[]) params.get("docid");
728
            }
729
            // Create a DBuery to handle export
730
            queryObj = new DBQuery(saxparser);
731
            // Get the docid
732
            docId = docs[0];
733
            // Make sure the client specify docid
734
            if (docId == null || docId.equals("")) {
735
                response.setContentType("text/xml"); //MIME type
736
                // Get a printwriter
737
                PrintWriter pw = response.getWriter();
738
                // Send back message
739
                pw.println("<?xml version=\"1.0\"?>");
740
                pw.println("<error>");
741
                pw.println("You didn't specify requested docid");
742
                pw.println("</error>");
743
                // Close printwriter
744
                pw.close();
745
                return;
746
            }
747
            // Get output stream
748
            out = response.getOutputStream();
749
            response.setContentType("application/zip"); //MIME type
750
            zOut = new ZipOutputStream(out);
751
            zOut = queryObj
752
                    .getZippedPackage(docId, out, user, groups, passWord);
753
            zOut.finish(); //terminate the zip file
754
            zOut.close(); //close the zip stream
755

    
756
        } catch (Exception e) {
757
            try {
758
                response.setContentType("text/xml"); //MIME type
759
                // Send error message back
760
                if (out != null) {
761
                    PrintWriter pw = new PrintWriter(out);
762
                    pw.println("<?xml version=\"1.0\"?>");
763
                    pw.println("<error>");
764
                    pw.println(e.getMessage());
765
                    pw.println("</error>");
766
                    // Close printwriter
767
                    pw.close();
768
                    // Close output stream
769
                    out.close();
770
                }
771
                // Close zip output stream
772
                if (zOut != null) {
773
                    zOut.close();
774
                }
775
            } catch (IOException ioe) {
776
                MetaCatUtil.debugMessage("Problem with the servlet output "
777
                        + "in MetacatServlet.handleExportAction: "
778
                        + ioe.getMessage(), 30);
779
            }
780

    
781
            MetaCatUtil.debugMessage(
782
                    "Error in MetacatServlet.handleExportAction: "
783
                            + e.getMessage(), 30);
784
            e.printStackTrace(System.out);
785

    
786
        }
787

    
788
    }
789

    
790
    /**
791
     * In eml2 document, the xml can have inline data and data was stripped off
792
     * and store in file system. This action can be used to read inline data
793
     * only
794
     *
795
     * @param params the Hashtable of HTTP request parameters
796
     * @param response the HTTP response object linked to the client
797
     * @param user the username sent the request
798
     * @param groups the user's groupnames
799
     */
800
    private void handleReadInlineDataAction(Hashtable params,
801
            HttpServletRequest request, HttpServletResponse response,
802
            String user, String passWord, String[] groups)
803
    {
804
        String[] docs = new String[10];
805
        String inlineDataId = null;
806
        String docId = "";
807
        ServletOutputStream out = null;
808

    
809
        try {
810
            // read the params
811
            if (params.containsKey("inlinedataid")) {
812
                docs = (String[]) params.get("inlinedataid");
813
            }
814
            // Get the docid
815
            inlineDataId = docs[0];
816
            // Make sure the client specify docid
817
            if (inlineDataId == null || inlineDataId.equals("")) {
818
                throw new Exception("You didn't specify requested inlinedataid"); }
819

    
820
            // check for permission
821
            docId = MetaCatUtil
822
                    .getDocIdWithoutRevFromInlineDataID(inlineDataId);
823
            PermissionController controller = new PermissionController(docId);
824
            // check top level read permission
825
            if (!controller.hasPermission(user, groups,
826
                    AccessControlInterface.READSTRING)) {
827
                throw new Exception("User " + user
828
                        + " doesn't have permission " + " to read document "
829
                        + docId);
830
            } else if (controller.hasSubTreeAccessControl()) {
831
                // if the document has subtree control, we need to check
832
                // subtree control
833
                // get node id for inlinedata
834
                long nodeId = getInlineDataNodeId(inlineDataId, docId);
835
                if (!controller.hasPermissionForSubTreeNode(user, groups,
836
                    AccessControlInterface.READSTRING, nodeId)) {
837
                    throw new Exception(
838
                    "User " + user + " doesn't have permission "
839
                    + " to read inlinedata " + inlineDataId);
840
                }
841
            }
842

    
843
            // Get output stream
844
            out = response.getOutputStream();
845
            // read the inline data from the file
846
            String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
847
            File lineData = new File(inlinePath, inlineDataId);
848
            FileInputStream input = new FileInputStream(lineData);
849
            byte[] buffer = new byte[4 * 1024];
850
            int bytes = input.read(buffer);
851
            while (bytes != -1) {
852
                out.write(buffer, 0, bytes);
853
                bytes = input.read(buffer);
854
            }
855
            out.close();
856

    
857
            EventLog.getInstance().log(request.getRemoteAddr(), user,
858
                    inlineDataId, "readinlinedata");
859
        } catch (Exception e) {
860
            try {
861
                PrintWriter pw = null;
862
                // Send error message back
863
                if (out != null) {
864
                    pw = new PrintWriter(out);
865
                } else {
866
                    pw = response.getWriter();
867
                }
868
                pw.println("<?xml version=\"1.0\"?>");
869
                pw.println("<error>");
870
                pw.println(e.getMessage());
871
                pw.println("</error>");
872
                // Close printwriter
873
                pw.close();
874
                // Close output stream if out is not null
875
                if (out != null) {
876
                    out.close();
877
                }
878
            } catch (IOException ioe) {
879
                MetaCatUtil.debugMessage("Problem with the servlet output "
880
                        + "in MetacatServlet.handleExportAction: "
881
                        + ioe.getMessage(), 30);
882
            }
883
            MetaCatUtil.debugMessage(
884
                    "Error in MetacatServlet.handleReadInlineDataAction: "
885
                            + e.getMessage(), 30);
886
        }
887
    }
888

    
889
    /*
890
     * Get the nodeid from xml_nodes for the inlinedataid
891
     */
892
    private long getInlineDataNodeId(String inLineDataId, String docId)
893
            throws SQLException
894
    {
895
        long nodeId = 0;
896
        String INLINE = "inline";
897
        boolean hasRow;
898
        PreparedStatement pStmt = null;
899
        DBConnection conn = null;
900
        int serialNumber = -1;
901
        String sql = "SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? "
902
                + "AND nodetype='TEXT' AND parentnodeid IN "
903
                + "(SELECT nodeid FROM xml_nodes WHERE docid=? AND "
904
                + "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
905

    
906
        try {
907
            //check out DBConnection
908
            conn = DBConnectionPool
909
                    .getDBConnection("AccessControlList.isAllowFirst");
910
            serialNumber = conn.getCheckOutSerialNumber();
911

    
912
            pStmt = conn.prepareStatement(sql);
913
            //bind value
914
            pStmt.setString(1, docId);//docid
915
            pStmt.setString(2, inLineDataId);//inlinedataid
916
            pStmt.setString(3, docId);
917
            // excute query
918
            pStmt.execute();
919
            ResultSet rs = pStmt.getResultSet();
920
            hasRow = rs.next();
921
            // get result
922
            if (hasRow) {
923
                nodeId = rs.getLong(1);
924
            }//if
925

    
926
        } catch (SQLException e) {
927
            throw e;
928
        } finally {
929
            try {
930
                pStmt.close();
931
            } finally {
932
                DBConnectionPool.returnDBConnection(conn, serialNumber);
933
            }
934
        }
935
        MetaCatUtil.debugMessage("The nodeid for inlinedataid " + inLineDataId
936
                + " is: " + nodeId, 35);
937
        return nodeId;
938
    }
939

    
940
    /**
941
     * Handle the "read" request of metadata/data files from Metacat or any
942
     * files from Internet; transformed metadata XML document into HTML
943
     * presentation if requested; zip files when more than one were requested.
944
     *
945
     * @param params the Hashtable of HTTP request parameters
946
     * @param request the HTTP request object linked to the client
947
     * @param response the HTTP response object linked to the client
948
     * @param user the username sent the request
949
     * @param groups the user's groupnames
950
     */
951
    private void handleReadAction(Hashtable params, HttpServletRequest request,
952
            HttpServletResponse response, String user, String passWord,
953
            String[] groups)
954
    {
955
        ServletOutputStream out = null;
956
        ZipOutputStream zout = null;
957
        PrintWriter pw = null;
958
        boolean zip = false;
959
        boolean withInlineData = true;
960

    
961
        try {
962
            String[] docs = new String[0];
963
            String docid = "";
964
            String qformat = "";
965
            String abstrpath = null;
966

    
967
            // read the params
968
            if (params.containsKey("docid")) {
969
                docs = (String[]) params.get("docid");
970
            }
971
            if (params.containsKey("qformat")) {
972
                qformat = ((String[]) params.get("qformat"))[0];
973
            }
974
            // the param for only metadata (eml)
975
            if (params.containsKey("inlinedata")) {
976

    
977
                String inlineData = ((String[]) params.get("inlinedata"))[0];
978
                if (inlineData.equalsIgnoreCase("false")) {
979
                    withInlineData = false;
980
                }
981
            }
982
            if ((docs.length > 1) || qformat.equals("zip")) {
983
                zip = true;
984
                out = response.getOutputStream();
985
                response.setContentType("application/zip"); //MIME type
986
                zout = new ZipOutputStream(out);
987
            }
988
            // go through the list of docs to read
989
            for (int i = 0; i < docs.length; i++) {
990
                try {
991

    
992
                    URL murl = new URL(docs[i]);
993
                    Hashtable murlQueryStr = MetaCatUtil.parseQuery(
994
                            murl.getQuery());
995
                    // case docid="http://.../?docid=aaa"
996
                    // or docid="metacat://.../?docid=bbb"
997
                    if (murlQueryStr.containsKey("docid")) {
998
                        // get only docid, eliminate the rest
999
                        docid = (String) murlQueryStr.get("docid");
1000
                        if (zip) {
1001
                            addDocToZip(request, docid, zout, user, groups);
1002
                        } else {
1003
                            readFromMetacat(request, response, docid, qformat,
1004
                                    abstrpath, user, groups, zip, zout,
1005
                                    withInlineData, params);
1006
                        }
1007

    
1008
                        // case docid="http://.../filename"
1009
                    } else {
1010
                        docid = docs[i];
1011
                        if (zip) {
1012
                            addDocToZip(request, docid, zout, user, groups);
1013
                        } else {
1014
                            readFromURLConnection(response, docid);
1015
                        }
1016
                    }
1017

    
1018
                } catch (MalformedURLException mue) {
1019
                    docid = docs[i];
1020
                    if (zip) {
1021
                        addDocToZip(request, docid, zout, user, groups);
1022
                    } else {
1023
                        readFromMetacat(request, response, docid, qformat,
1024
                                abstrpath, user, groups, zip, zout,
1025
                                withInlineData, params);
1026
                    }
1027
                }
1028
            }
1029

    
1030
            if (zip) {
1031
                zout.finish(); //terminate the zip file
1032
                zout.close(); //close the zip stream
1033
            }
1034

    
1035
        } catch (McdbDocNotFoundException notFoundE) {
1036
            // To handle doc not found exception
1037
            // the docid which didn't be found
1038
            String notFoundDocId = notFoundE.getUnfoundDocId();
1039
            String notFoundRevision = notFoundE.getUnfoundRevision();
1040
            MetaCatUtil.debugMessage("Missed id: " + notFoundDocId, 30);
1041
            MetaCatUtil.debugMessage("Missed rev: " + notFoundRevision, 30);
1042
            try {
1043
                // read docid from remote server
1044
                readFromRemoteMetaCat(response, notFoundDocId,
1045
                        notFoundRevision, user, passWord, out, zip, zout);
1046
                // Close zout outputstream
1047
                if (zout != null) {
1048
                    zout.close();
1049
                }
1050
                // close output stream
1051
                if (out != null) {
1052
                    out.close();
1053
                }
1054

    
1055
            } catch (Exception exc) {
1056
                MetaCatUtil.debugMessage(
1057
                        "Erorr in MetacatServlet.hanldReadAction: "
1058
                                + exc.getMessage(), 30);
1059
                try {
1060
                    if (out != null) {
1061
                        response.setContentType("text/xml");
1062
                        // Send back error message by printWriter
1063
                        pw = new PrintWriter(out);
1064
                        pw.println("<?xml version=\"1.0\"?>");
1065
                        pw.println("<error>");
1066
                        pw.println(notFoundE.getMessage());
1067
                        pw.println("</error>");
1068
                        pw.close();
1069
                        out.close();
1070

    
1071
                    } else {
1072
                        response.setContentType("text/xml"); //MIME type
1073
                        // Send back error message if out = null
1074
                        if (pw == null) {
1075
                            // If pw is null, open the respnose
1076
                            pw = response.getWriter();
1077
                        }
1078
                        pw.println("<?xml version=\"1.0\"?>");
1079
                        pw.println("<error>");
1080
                        pw.println(notFoundE.getMessage());
1081
                        pw.println("</error>");
1082
                        pw.close();
1083
                    }
1084
                    // close zout
1085
                    if (zout != null) {
1086
                        zout.close();
1087
                    }
1088
                } catch (IOException ie) {
1089
                    MetaCatUtil.debugMessage("Problem with the servlet output "
1090
                            + "in MetacatServlet.handleReadAction: "
1091
                            + ie.getMessage(), 30);
1092
                }
1093
            }
1094
        } catch (Exception e) {
1095
            try {
1096

    
1097
                if (out != null) {
1098
                    response.setContentType("text/xml"); //MIME type
1099
                    pw = new PrintWriter(out);
1100
                    pw.println("<?xml version=\"1.0\"?>");
1101
                    pw.println("<error>");
1102
                    pw.println(e.getMessage());
1103
                    pw.println("</error>");
1104
                    pw.close();
1105
                    out.close();
1106
                } else {
1107
                    response.setContentType("text/xml"); //MIME type
1108
                    // Send back error message if out = null
1109
                    if (pw == null) {
1110
                        pw = response.getWriter();
1111
                    }
1112
                    pw.println("<?xml version=\"1.0\"?>");
1113
                    pw.println("<error>");
1114
                    pw.println(e.getMessage());
1115
                    pw.println("</error>");
1116
                    pw.close();
1117

    
1118
                }
1119
                // Close zip output stream
1120
                if (zout != null) {
1121
                    zout.close();
1122
                }
1123

    
1124
            } catch (IOException ioe) {
1125
                MetaCatUtil.debugMessage("Problem with the servlet output "
1126
                        + "in MetacatServlet.handleReadAction: "
1127
                        + ioe.getMessage(), 30);
1128
                ioe.printStackTrace(System.out);
1129

    
1130
            }
1131

    
1132
            MetaCatUtil.debugMessage(
1133
                    "Error in MetacatServlet.handleReadAction: "
1134
                            + e.getMessage(), 30);
1135
            //e.printStackTrace(System.out);
1136
        }
1137
    }
1138

    
1139
    /** read metadata or data from Metacat
1140
     */
1141
    private void readFromMetacat(HttpServletRequest request,
1142
            HttpServletResponse response, String docid, String qformat,
1143
            String abstrpath, String user, String[] groups, boolean zip,
1144
            ZipOutputStream zout, boolean withInlineData, Hashtable params)
1145
            throws ClassNotFoundException, IOException, SQLException,
1146
            McdbException, Exception
1147
    {
1148

    
1149
        try {
1150

    
1151
            DocumentImpl doc = new DocumentImpl(docid);
1152

    
1153
            //check the permission for read
1154
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1155
                Exception e = new Exception("User " + user
1156
                        + " does not have permission"
1157
                        + " to read the document with the docid " + docid);
1158

    
1159
                throw e;
1160
            }
1161

    
1162
            if (doc.getRootNodeID() == 0) {
1163
                // this is data file
1164
                String filepath = MetaCatUtil.getOption("datafilepath");
1165
                if (!filepath.endsWith("/")) {
1166
                    filepath += "/";
1167
                }
1168
                String filename = filepath + docid;
1169
                FileInputStream fin = null;
1170
                fin = new FileInputStream(filename);
1171

    
1172
                //MIME type
1173
                String contentType = getServletContext().getMimeType(filename);
1174
                if (contentType == null) {
1175
                    ContentTypeProvider provider = new ContentTypeProvider(
1176
                            docid);
1177
                    contentType = provider.getContentType();
1178
                    MetaCatUtil.debugMessage("Final contenttype is: "
1179
                            + contentType, 30);
1180
                }
1181

    
1182
                response.setContentType(contentType);
1183
                // if we decide to use "application/octet-stream" for all data
1184
                // returns
1185
                // response.setContentType("application/octet-stream");
1186

    
1187
                try {
1188

    
1189
                    ServletOutputStream out = response.getOutputStream();
1190
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
1191
                    int b = fin.read(buf);
1192
                    while (b != -1) {
1193
                        out.write(buf, 0, b);
1194
                        b = fin.read(buf);
1195
                    }
1196
                } finally {
1197
                    if (fin != null) fin.close();
1198
                }
1199

    
1200
            } else {
1201
                // this is metadata doc
1202
                if (qformat.equals("xml")) {
1203

    
1204
                    // set content type first
1205
                    response.setContentType("text/xml"); //MIME type
1206
                    PrintWriter out = response.getWriter();
1207
                    doc.toXml(out, user, groups, withInlineData);
1208
                } else {
1209
                    response.setContentType("text/html"); //MIME type
1210
                    PrintWriter out = response.getWriter();
1211

    
1212
                    // Look up the document type
1213
                    String doctype = doc.getDoctype();
1214
                    // Transform the document to the new doctype
1215
                    DBTransform dbt = new DBTransform();
1216
                    dbt.transformXMLDocument(doc.toString(user, groups,
1217
                            withInlineData), doctype, "-//W3C//HTML//EN",
1218
                            qformat, out, params);
1219
                }
1220

    
1221
            }
1222
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1223
                    docid, "read");
1224
        } catch (Exception except) {
1225
            throw except;
1226
        }
1227
    }
1228

    
1229
    /**
1230
     * read data from URLConnection
1231
     */
1232
    private void readFromURLConnection(HttpServletResponse response,
1233
            String docid) throws IOException, MalformedURLException
1234
    {
1235
        ServletOutputStream out = response.getOutputStream();
1236
        String contentType = getServletContext().getMimeType(docid); //MIME
1237
                                                                     // type
1238
        if (contentType == null) {
1239
            if (docid.endsWith(".xml")) {
1240
                contentType = "text/xml";
1241
            } else if (docid.endsWith(".css")) {
1242
                contentType = "text/css";
1243
            } else if (docid.endsWith(".dtd")) {
1244
                contentType = "text/plain";
1245
            } else if (docid.endsWith(".xsd")) {
1246
                contentType = "text/xml";
1247
            } else if (docid.endsWith("/")) {
1248
                contentType = "text/html";
1249
            } else {
1250
                File f = new File(docid);
1251
                if (f.isDirectory()) {
1252
                    contentType = "text/html";
1253
                } else {
1254
                    contentType = "application/octet-stream";
1255
                }
1256
            }
1257
        }
1258
        response.setContentType(contentType);
1259
        // if we decide to use "application/octet-stream" for all data returns
1260
        // response.setContentType("application/octet-stream");
1261

    
1262
        // this is http url
1263
        URL url = new URL(docid);
1264
        BufferedInputStream bis = null;
1265
        try {
1266
            bis = new BufferedInputStream(url.openStream());
1267
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1268
            int b = bis.read(buf);
1269
            while (b != -1) {
1270
                out.write(buf, 0, b);
1271
                b = bis.read(buf);
1272
            }
1273
        } finally {
1274
            if (bis != null) bis.close();
1275
        }
1276

    
1277
    }
1278

    
1279
    /**
1280
     * read file/doc and write to ZipOutputStream
1281
     *
1282
     * @param docid
1283
     * @param zout
1284
     * @param user
1285
     * @param groups
1286
     * @throws ClassNotFoundException
1287
     * @throws IOException
1288
     * @throws SQLException
1289
     * @throws McdbException
1290
     * @throws Exception
1291
     */
1292
    private void addDocToZip(HttpServletRequest request, String docid,
1293
            ZipOutputStream zout, String user, String[] groups) throws
1294
            ClassNotFoundException, IOException, SQLException, McdbException,
1295
            Exception
1296
    {
1297
        byte[] bytestring = null;
1298
        ZipEntry zentry = null;
1299

    
1300
        try {
1301
            URL url = new URL(docid);
1302

    
1303
            // this http url; read from URLConnection; add to zip
1304
            zentry = new ZipEntry(docid);
1305
            zout.putNextEntry(zentry);
1306
            BufferedInputStream bis = null;
1307
            try {
1308
                bis = new BufferedInputStream(url.openStream());
1309
                byte[] buf = new byte[4 * 1024]; // 4K buffer
1310
                int b = bis.read(buf);
1311
                while (b != -1) {
1312
                    zout.write(buf, 0, b);
1313
                    b = bis.read(buf);
1314
                }
1315
            } finally {
1316
                if (bis != null) bis.close();
1317
            }
1318
            zout.closeEntry();
1319

    
1320
        } catch (MalformedURLException mue) {
1321

    
1322
            // this is metacat doc (data file or metadata doc)
1323
            try {
1324
                DocumentImpl doc = new DocumentImpl(docid);
1325

    
1326
                //check the permission for read
1327
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1328
                    Exception e = new Exception("User " + user
1329
                            + " does not have "
1330
                            + "permission to read the document with the docid "
1331
                            + docid);
1332
                    throw e;
1333
                }
1334

    
1335
                if (doc.getRootNodeID() == 0) {
1336
                    // this is data file; add file to zip
1337
                    String filepath = MetaCatUtil.getOption("datafilepath");
1338
                    if (!filepath.endsWith("/")) {
1339
                        filepath += "/";
1340
                    }
1341
                    String filename = filepath + docid;
1342
                    FileInputStream fin = null;
1343
                    fin = new FileInputStream(filename);
1344
                    try {
1345

    
1346
                        zentry = new ZipEntry(docid);
1347
                        zout.putNextEntry(zentry);
1348
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
1349
                        int b = fin.read(buf);
1350
                        while (b != -1) {
1351
                            zout.write(buf, 0, b);
1352
                            b = fin.read(buf);
1353
                        }
1354
                    } finally {
1355
                        if (fin != null) fin.close();
1356
                    }
1357
                    zout.closeEntry();
1358

    
1359
                } else {
1360
                    // this is metadata doc; add doc to zip
1361
                    bytestring = doc.toString().getBytes();
1362
                    zentry = new ZipEntry(docid + ".xml");
1363
                    zentry.setSize(bytestring.length);
1364
                    zout.putNextEntry(zentry);
1365
                    zout.write(bytestring, 0, bytestring.length);
1366
                    zout.closeEntry();
1367
                }
1368
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1369
                        docid, "read");
1370
            } catch (Exception except) {
1371
                throw except;
1372
            }
1373
        }
1374
    }
1375

    
1376
    /**
1377
     * If metacat couldn't find a data file or document locally, it will read
1378
     * this docid from its home server. This is for the replication feature
1379
     */
1380
    private void readFromRemoteMetaCat(HttpServletResponse response,
1381
            String docid, String rev, String user, String password,
1382
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
1383
            throws Exception
1384
    {
1385
        // Create a object of RemoteDocument, "" is for zipEntryPath
1386
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
1387
                password, "");
1388
        String docType = remoteDoc.getDocType();
1389
        // Only read data file
1390
        if (docType.equals("BIN")) {
1391
            // If it is zip format
1392
            if (zip) {
1393
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
1394
            } else {
1395
                if (out == null) {
1396
                    out = response.getOutputStream();
1397
                }
1398
                response.setContentType("application/octet-stream");
1399
                remoteDoc.readDocumentFromRemoteServer(out);
1400
            }
1401
        } else {
1402
            throw new Exception("Docid: " + docid + "." + rev
1403
                    + " couldn't find");
1404
        }
1405
    }
1406

    
1407
    /**
1408
     * Handle the database putdocument request and write an XML document to the
1409
     * database connection
1410
     */
1411
    private void handleInsertOrUpdateAction(HttpServletRequest request,
1412
            HttpServletResponse response, PrintWriter out, Hashtable params,
1413
            String user, String[] groups)
1414
    {
1415
        DBConnection dbConn = null;
1416
        int serialNumber = -1;
1417

    
1418
        try {
1419
            // Get the document indicated
1420
            String[] doctext = (String[]) params.get("doctext");
1421

    
1422
            String pub = null;
1423
            if (params.containsKey("public")) {
1424
                pub = ((String[]) params.get("public"))[0];
1425
            }
1426

    
1427
            StringReader dtd = null;
1428
            if (params.containsKey("dtdtext")) {
1429
                String[] dtdtext = (String[]) params.get("dtdtext");
1430
                try {
1431
                    if (!dtdtext[0].equals("")) {
1432
                        dtd = new StringReader(dtdtext[0]);
1433
                    }
1434
                } catch (NullPointerException npe) {
1435
                }
1436
            }
1437

    
1438
            StringReader xml = new StringReader(doctext[0]);
1439
            boolean validate = false;
1440
            DocumentImplWrapper documentWrapper = null;
1441
            try {
1442
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1443
                // >
1444
                // in order to decide whether to use validation parser
1445
                validate = needDTDValidation(xml);
1446
                if (validate) {
1447
                    // set a dtd base validation parser
1448
                    String rule = DocumentImpl.DTD;
1449
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1450
                } else if (needSchemaValidation(xml)) {
1451
                    // for eml2
1452
                    String namespace = findNamespace(xml);
1453
                    if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1454
                                || namespace.compareTo(
1455
                                DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1456
                        // set eml2 base validation parser
1457
                        String rule = DocumentImpl.EML200;
1458
                        // using emlparser to check id validation
1459
                        EMLParser parser = new EMLParser(doctext[0]);
1460
                        documentWrapper = new DocumentImplWrapper(rule, true);
1461
                    } else if (namespace.compareTo(
1462
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1463
                        // set eml2 base validation parser
1464
                        String rule = DocumentImpl.EML210;
1465
                        // using emlparser to check id validation
1466
                        EMLParser parser = new EMLParser(doctext[0]);
1467
                        documentWrapper = new DocumentImplWrapper(rule, true);
1468
                    } else {
1469
                        // set schema base validation parser
1470
                        String rule = DocumentImpl.SCHEMA;
1471
                        documentWrapper = new DocumentImplWrapper(rule, true);
1472
                    }
1473
                } else {
1474
                    documentWrapper = new DocumentImplWrapper("", false);
1475
                }
1476

    
1477
                String[] action = (String[]) params.get("action");
1478
                String[] docid = (String[]) params.get("docid");
1479
                String newdocid = null;
1480

    
1481
                String doAction = null;
1482
                if (action[0].equals("insert")) {
1483
                    doAction = "INSERT";
1484
                } else if (action[0].equals("update")) {
1485
                    doAction = "UPDATE";
1486
                }
1487

    
1488
                try {
1489
                    // get a connection from the pool
1490
                    dbConn = DBConnectionPool
1491
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1492
                    serialNumber = dbConn.getCheckOutSerialNumber();
1493

    
1494
                    // write the document to the database
1495
                    try {
1496
                        String accNumber = docid[0];
1497
                        MetaCatUtil.debugMessage("" + doAction + " "
1498
                                + accNumber + "...", 10);
1499
                        if (accNumber.equals("")) {
1500
                            accNumber = null;
1501
                        }
1502
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1503
                                doAction, accNumber, user, groups);
1504
                        EventLog.getInstance().log(request.getRemoteAddr(),
1505
                                user, accNumber, action[0]);
1506
                    } catch (NullPointerException npe) {
1507
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1508
                                doAction, null, user, groups);
1509
                        EventLog.getInstance().log(request.getRemoteAddr(),
1510
                                user, "", action[0]);
1511
                    }
1512
                }
1513
                finally {
1514
                    // Return db connection
1515
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1516
                }
1517

    
1518
                // set content type and other response header fields first
1519
                //response.setContentType("text/xml");
1520
                out.println("<?xml version=\"1.0\"?>");
1521
                out.println("<success>");
1522
                out.println("<docid>" + newdocid + "</docid>");
1523
                out.println("</success>");
1524

    
1525
            } catch (NullPointerException npe) {
1526
                //response.setContentType("text/xml");
1527
                out.println("<?xml version=\"1.0\"?>");
1528
                out.println("<error>");
1529
                out.println(npe.getMessage());
1530
                out.println("</error>");
1531
            }
1532
        } catch (Exception e) {
1533
            //response.setContentType("text/xml");
1534
            out.println("<?xml version=\"1.0\"?>");
1535
            out.println("<error>");
1536
            out.println(e.getMessage());
1537
            out.println("</error>");
1538
        }
1539
    }
1540

    
1541
    /**
1542
     * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > in
1543
     * order to decide whether to use validation parser
1544
     */
1545
    private static boolean needDTDValidation(StringReader xmlreader)
1546
            throws IOException
1547
    {
1548

    
1549
        StringBuffer cbuff = new StringBuffer();
1550
        java.util.Stack st = new java.util.Stack();
1551
        boolean validate = false;
1552
        int c;
1553
        int inx;
1554

    
1555
        // read from the stream until find the keywords
1556
        while ((st.empty() || st.size() < 4) && ((c = xmlreader.read()) != -1)) {
1557
            cbuff.append((char) c);
1558

    
1559
            // "<!DOCTYPE" keyword is found; put it in the stack
1560
            if ((inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1) {
1561
                cbuff = new StringBuffer();
1562
                st.push("<!DOCTYPE");
1563
            }
1564
            // "PUBLIC" keyword is found; put it in the stack
1565
            if ((inx = cbuff.toString().indexOf("PUBLIC")) != -1) {
1566
                cbuff = new StringBuffer();
1567
                st.push("PUBLIC");
1568
            }
1569
            // "SYSTEM" keyword is found; put it in the stack
1570
            if ((inx = cbuff.toString().indexOf("SYSTEM")) != -1) {
1571
                cbuff = new StringBuffer();
1572
                st.push("SYSTEM");
1573
            }
1574
            // ">" character is found; put it in the stack
1575
            // ">" is found twice: fisrt from <?xml ...?>
1576
            // and second from <!DOCTYPE ... >
1577
            if ((inx = cbuff.toString().indexOf(">")) != -1) {
1578
                cbuff = new StringBuffer();
1579
                st.push(">");
1580
            }
1581
        }
1582

    
1583
        // close the stream
1584
        xmlreader.reset();
1585

    
1586
        // check the stack whether it contains the keywords:
1587
        // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1588
        if (st.size() == 4) {
1589
            if (((String) st.pop()).equals(">")
1590
                    && (((String) st.peek()).equals("PUBLIC") | ((String) st
1591
                            .pop()).equals("SYSTEM"))
1592
                    && ((String) st.pop()).equals("<!DOCTYPE")) {
1593
                validate = true;
1594
            }
1595
        }
1596

    
1597
        MetaCatUtil.debugMessage("Validation for dtd is " + validate, 10);
1598
        return validate;
1599
    }
1600

    
1601
    // END OF INSERT/UPDATE SECTION
1602

    
1603
    /* check if the xml string contains key words to specify schema loocation */
1604
    private boolean needSchemaValidation(StringReader xml) throws IOException
1605
    {
1606
        boolean needSchemaValidate = false;
1607
        if (xml == null) {
1608
            MetaCatUtil.debugMessage("Validation for schema is "
1609
                    + needSchemaValidate, 10);
1610
            return needSchemaValidate;
1611
        }
1612
        System.out.println("before get target line");
1613
        String targetLine = getSchemaLine(xml);
1614
        System.out.println("before get target line");
1615
        // to see if the second line contain some keywords
1616
        if (targetLine != null
1617
                && (targetLine.indexOf(SCHEMALOCATIONKEYWORD) != -1 || targetLine
1618
                        .indexOf(NONAMESPACELOCATION) != -1)) {
1619
            // if contains schema location key word, should be validate
1620
            needSchemaValidate = true;
1621
        }
1622

    
1623
        MetaCatUtil.debugMessage("Validation for schema is "
1624
                + needSchemaValidate, 10);
1625
        return needSchemaValidate;
1626

    
1627
    }
1628

    
1629
    /* check if the xml string contains key words to specify schema loocation */
1630
    private String findNamespace(StringReader xml) throws IOException
1631
    {
1632
        String namespace = null;
1633

    
1634
        String eml2_0_0NameSpace = DocumentImpl.EML2_0_0NAMESPACE;
1635
        String eml2_0_1NameSpace = DocumentImpl.EML2_0_1NAMESPACE;
1636
        String eml2_1_0NameSpace = DocumentImpl.EML2_1_0NAMESPACE;
1637

    
1638
        if (xml == null) {
1639
            MetaCatUtil.debugMessage("Validation for schema is "
1640
                    + namespace, 10);
1641
            return namespace;
1642
        }
1643
        String targetLine = getSchemaLine(xml);
1644

    
1645
        if (targetLine != null) {
1646

    
1647
            int startIndex = targetLine.indexOf(SCHEMALOCATIONKEYWORD);
1648
            int start = 1;
1649
            int end = 1;
1650
            String schemaLocation = null;
1651
            int count = 0;
1652
            if (startIndex != -1) {
1653
                for (int i = startIndex; i < targetLine.length(); i++) {
1654
                    if (targetLine.charAt(i) == '"') {
1655
                        count++;
1656
                    }
1657
                    if (targetLine.charAt(i) == '"' && count == 1) {
1658
                        start = i;
1659
                    }
1660
                    if (targetLine.charAt(i) == '"' && count == 2) {
1661
                        end = i;
1662
                        break;
1663
                    }
1664
                }
1665
            }
1666
            schemaLocation = targetLine.substring(start + 1, end);
1667
            MetaCatUtil.debugMessage("schemaLocation in xml is: "
1668
                    + schemaLocation, 30);
1669
            if (schemaLocation.indexOf(eml2_0_0NameSpace) != -1) {
1670
                namespace = eml2_0_0NameSpace;
1671
            } else if (schemaLocation.indexOf(eml2_0_1NameSpace) != -1) {
1672
                namespace = eml2_0_1NameSpace;
1673
            } else if (schemaLocation.indexOf(eml2_1_0NameSpace) != -1) {
1674
                namespace = eml2_1_0NameSpace;
1675
            }
1676
        }
1677

    
1678
        MetaCatUtil.debugMessage("Validation for eml is " + namespace,
1679
                10);
1680

    
1681
        return namespace;
1682

    
1683
    }
1684

    
1685
    private String getSchemaLine(StringReader xml) throws IOException
1686
    {
1687
        // find the line
1688
        String secondLine = null;
1689
        int count = 0;
1690
        int endIndex = 0;
1691
        int startIndex = 0;
1692
        final int TARGETNUM = 2;
1693
        StringBuffer buffer = new StringBuffer();
1694
        boolean comment = false;
1695
        char thirdPreviousCharacter = '?';
1696
        char secondPreviousCharacter = '?';
1697
        char previousCharacter = '?';
1698
        char currentCharacter = '?';
1699

    
1700
        while ((currentCharacter = (char) xml.read()) != -1) {
1701
            //in a comment
1702
            if (currentCharacter == '-' && previousCharacter == '-'
1703
                    && secondPreviousCharacter == '!'
1704
                    && thirdPreviousCharacter == '<') {
1705
                comment = true;
1706
            }
1707
            //out of comment
1708
            if (comment && currentCharacter == '>' && previousCharacter == '-'
1709
                    && secondPreviousCharacter == '-') {
1710
                comment = false;
1711
            }
1712

    
1713
            //this is not comment
1714
            if (currentCharacter != '!' && previousCharacter == '<' && !comment) {
1715
                count++;
1716
            }
1717
            // get target line
1718
            if (count == TARGETNUM && currentCharacter != '>') {
1719
                buffer.append(currentCharacter);
1720
            }
1721
            if (count == TARGETNUM && currentCharacter == '>') {
1722
                break;
1723
            }
1724
            thirdPreviousCharacter = secondPreviousCharacter;
1725
            secondPreviousCharacter = previousCharacter;
1726
            previousCharacter = currentCharacter;
1727

    
1728
        }
1729
        secondLine = buffer.toString();
1730
        MetaCatUtil
1731
                .debugMessage("the second line string is: " + secondLine, 25);
1732
        xml.reset();
1733
        return secondLine;
1734
    }
1735

    
1736
    /**
1737
     * Handle the database delete request and delete an XML document from the
1738
     * database connection
1739
     */
1740
    private void handleDeleteAction(PrintWriter out, Hashtable params,
1741
            HttpServletRequest request, HttpServletResponse response,
1742
            String user, String[] groups)
1743
    {
1744

    
1745
        String[] docid = (String[]) params.get("docid");
1746

    
1747
        // delete the document from the database
1748
        try {
1749

    
1750
            // NOTE -- NEED TO TEST HERE
1751
            // FOR EXISTENCE OF DOCID PARAM
1752
            // BEFORE ACCESSING ARRAY
1753
            try {
1754
                DocumentImpl.delete(docid[0], user, groups);
1755
                EventLog.getInstance().log(request.getRemoteAddr(),
1756
                    user, docid[0], "delete");
1757
                response.setContentType("text/xml");
1758
                out.println("<?xml version=\"1.0\"?>");
1759
                out.println("<success>");
1760
                out.println("Document deleted.");
1761
                out.println("</success>");
1762
            } catch (AccessionNumberException ane) {
1763
                response.setContentType("text/xml");
1764
                out.println("<?xml version=\"1.0\"?>");
1765
                out.println("<error>");
1766
                out.println("Error deleting document!!!");
1767
                out.println(ane.getMessage());
1768
                out.println("</error>");
1769
            }
1770
        } catch (Exception e) {
1771
            response.setContentType("text/xml");
1772
            out.println("<?xml version=\"1.0\"?>");
1773
            out.println("<error>");
1774
            out.println(e.getMessage());
1775
            out.println("</error>");
1776
        }
1777
    }
1778

    
1779
    /**
1780
     * Handle the validation request and return the results to the requestor
1781
     */
1782
    private void handleValidateAction(PrintWriter out, Hashtable params)
1783
    {
1784

    
1785
        // Get the document indicated
1786
        String valtext = null;
1787
        DBConnection dbConn = null;
1788
        int serialNumber = -1;
1789

    
1790
        try {
1791
            valtext = ((String[]) params.get("valtext"))[0];
1792
        } catch (Exception nullpe) {
1793

    
1794
            String docid = null;
1795
            try {
1796
                // Find the document id number
1797
                docid = ((String[]) params.get("docid"))[0];
1798

    
1799
                // Get the document indicated from the db
1800
                DocumentImpl xmldoc = new DocumentImpl(docid);
1801
                valtext = xmldoc.toString();
1802

    
1803
            } catch (NullPointerException npe) {
1804

    
1805
                out.println("<error>Error getting document ID: " + docid
1806
                        + "</error>");
1807
                //if ( conn != null ) { util.returnConnection(conn); }
1808
                return;
1809
            } catch (Exception e) {
1810

    
1811
                out.println(e.getMessage());
1812
            }
1813
        }
1814

    
1815
        try {
1816
            // get a connection from the pool
1817
            dbConn = DBConnectionPool
1818
                    .getDBConnection("MetaCatServlet.handleValidateAction");
1819
            serialNumber = dbConn.getCheckOutSerialNumber();
1820
            DBValidate valobj = new DBValidate(saxparser, dbConn);
1821
            boolean valid = valobj.validateString(valtext);
1822

    
1823
            // set content type and other response header fields first
1824

    
1825
            out.println(valobj.returnErrors());
1826

    
1827
        } catch (NullPointerException npe2) {
1828
            // set content type and other response header fields first
1829

    
1830
            out.println("<error>Error validating document.</error>");
1831
        } catch (Exception e) {
1832

    
1833
            out.println(e.getMessage());
1834
        } finally {
1835
            // Return db connection
1836
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1837
        }
1838
    }
1839

    
1840
    /**
1841
     * Handle "getrevsionanddoctype" action Given a docid, return it's current
1842
     * revision and doctype from data base The output is String look like
1843
     * "rev;doctype"
1844
     */
1845
    private void handleGetRevisionAndDocTypeAction(PrintWriter out,
1846
            Hashtable params)
1847
    {
1848
        // To store doc parameter
1849
        String[] docs = new String[10];
1850
        // Store a single doc id
1851
        String givenDocId = null;
1852
        // Get docid from parameters
1853
        if (params.containsKey("docid")) {
1854
            docs = (String[]) params.get("docid");
1855
        }
1856
        // Get first docid form string array
1857
        givenDocId = docs[0];
1858

    
1859
        try {
1860
            // Make sure there is a docid
1861
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
1862
                    "User didn't specify docid!"); }//if
1863

    
1864
            // Create a DBUtil object
1865
            DBUtil dbutil = new DBUtil();
1866
            // Get a rev and doctype
1867
            String revAndDocType = dbutil
1868
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1869
            out.println(revAndDocType);
1870

    
1871
        } catch (Exception e) {
1872
            // Handle exception
1873
            out.println("<?xml version=\"1.0\"?>");
1874
            out.println("<error>");
1875
            out.println(e.getMessage());
1876
            out.println("</error>");
1877
        }
1878

    
1879
    }
1880

    
1881
    /**
1882
     * Handle "getaccesscontrol" action. Read Access Control List from db
1883
     * connection in XML format
1884
     */
1885
    private void handleGetAccessControlAction(PrintWriter out,
1886
            Hashtable params, HttpServletResponse response, String username,
1887
            String[] groupnames)
1888
    {
1889
        DBConnection dbConn = null;
1890
        int serialNumber = -1;
1891
        String docid = ((String[]) params.get("docid"))[0];
1892

    
1893
        try {
1894

    
1895
            // get connection from the pool
1896
            dbConn = DBConnectionPool
1897
                    .getDBConnection("MetaCatServlet.handleGetAccessControlAction");
1898
            serialNumber = dbConn.getCheckOutSerialNumber();
1899
            AccessControlList aclobj = new AccessControlList(dbConn);
1900
            String acltext = aclobj.getACL(docid, username, groupnames);
1901
            out.println(acltext);
1902

    
1903
        } catch (Exception e) {
1904
            out.println("<?xml version=\"1.0\"?>");
1905
            out.println("<error>");
1906
            out.println(e.getMessage());
1907
            out.println("</error>");
1908
        } finally {
1909
            // Retrun db connection to pool
1910
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1911
        }
1912
    }
1913

    
1914
    /**
1915
     * Handle the "getprincipals" action. Read all principals from
1916
     * authentication scheme in XML format
1917
     */
1918
    private void handleGetPrincipalsAction(PrintWriter out, String user,
1919
            String password)
1920
    {
1921
        try {
1922
            AuthSession auth = new AuthSession();
1923
            String principals = auth.getPrincipals(user, password);
1924
            out.println(principals);
1925

    
1926
        } catch (Exception e) {
1927
            out.println("<?xml version=\"1.0\"?>");
1928
            out.println("<error>");
1929
            out.println(e.getMessage());
1930
            out.println("</error>");
1931
        }
1932
    }
1933

    
1934
    /**
1935
     * Handle "getdoctypes" action. Read all doctypes from db connection in XML
1936
     * format
1937
     */
1938
    private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
1939
            HttpServletResponse response)
1940
    {
1941
        try {
1942
            DBUtil dbutil = new DBUtil();
1943
            String doctypes = dbutil.readDoctypes();
1944
            out.println(doctypes);
1945
        } catch (Exception e) {
1946
            out.println("<?xml version=\"1.0\"?>");
1947
            out.println("<error>");
1948
            out.println(e.getMessage());
1949
            out.println("</error>");
1950
        }
1951
    }
1952

    
1953
    /**
1954
     * Handle the "getdtdschema" action. Read DTD or Schema file for a given
1955
     * doctype from Metacat catalog system
1956
     */
1957
    private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
1958
            HttpServletResponse response)
1959
    {
1960

    
1961
        String doctype = null;
1962
        String[] doctypeArr = (String[]) params.get("doctype");
1963

    
1964
        // get only the first doctype specified in the list of doctypes
1965
        // it could be done for all doctypes in that list
1966
        if (doctypeArr != null) {
1967
            doctype = ((String[]) params.get("doctype"))[0];
1968
        }
1969

    
1970
        try {
1971
            DBUtil dbutil = new DBUtil();
1972
            String dtdschema = dbutil.readDTDSchema(doctype);
1973
            out.println(dtdschema);
1974

    
1975
        } catch (Exception e) {
1976
            out.println("<?xml version=\"1.0\"?>");
1977
            out.println("<error>");
1978
            out.println(e.getMessage());
1979
            out.println("</error>");
1980
        }
1981

    
1982
    }
1983

    
1984
    /**
1985
     * Handle the "getlastdocid" action. Get the latest docid with rev number
1986
     * from db connection in XML format
1987
     */
1988
    private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
1989
            HttpServletResponse response)
1990
    {
1991

    
1992
        String scope = ((String[]) params.get("scope"))[0];
1993
        if (scope == null) {
1994
            scope = ((String[]) params.get("username"))[0];
1995
        }
1996

    
1997
        try {
1998

    
1999
            DBUtil dbutil = new DBUtil();
2000
            String lastDocid = dbutil.getMaxDocid(scope);
2001
            out.println("<?xml version=\"1.0\"?>");
2002
            out.println("<lastDocid>");
2003
            out.println("  <scope>" + scope + "</scope>");
2004
            out.println("  <docid>" + lastDocid + "</docid>");
2005
            out.println("</lastDocid>");
2006

    
2007
        } catch (Exception e) {
2008
            out.println("<?xml version=\"1.0\"?>");
2009
            out.println("<error>");
2010
            out.println(e.getMessage());
2011
            out.println("</error>");
2012
        }
2013
    }
2014

    
2015
    /**
2016
     * Print a report from the event log based on filter parameters passed in
2017
     * from the web.
2018
     *
2019
     * TODO: make sure urlencoding of timestamp params is working
2020
     *
2021
     * @param params the parameters from the web request
2022
     * @param request the http request object for getting request details
2023
     * @param response the http response object for writing output
2024
     */
2025
    private void handleGetLogAction(Hashtable params, HttpServletRequest request,
2026
            HttpServletResponse response)
2027
    {
2028
        // Get all of the parameters in the correct formats
2029
        String[] ipAddress = (String[])params.get("ipaddress");
2030
        String[] principal = (String[])params.get("principal");
2031
        String[] docid = (String[])params.get("docid");
2032
        String[] event = (String[])params.get("event");
2033
        String[] startArray = (String[]) params.get("start");
2034
        String[] endArray = (String[]) params.get("end");
2035
        String start = null;
2036
        String end = null;
2037
        if (startArray != null) {
2038
            start = startArray[0];
2039
        }
2040
        if (endArray != null) {
2041
            end = endArray[0];
2042
        }
2043
        Timestamp startDate = null;
2044
        Timestamp endDate = null;
2045
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2046
        try {
2047
            if (start != null) {
2048
                startDate = new Timestamp((format.parse(start)).getTime());
2049
            }
2050
            if (end != null) {
2051
                endDate = new Timestamp((format.parse(end)).getTime());
2052
            }
2053
        } catch (ParseException e) {
2054
            System.out.println("Failed to created Timestamp from input.");
2055
        }
2056

    
2057
        // Request the report by passing the filter parameters
2058
        try {
2059
            response.setContentType("text/xml");
2060
            PrintWriter out = response.getWriter();
2061
            out.println(EventLog.getInstance().getReport(ipAddress, principal,
2062
                    docid, event, startDate, endDate));
2063
            out.close();
2064
        } catch (IOException e) {
2065
            MetaCatUtil.debugMessage(
2066
                    "Could not open http response for writing: "
2067
                    + e.getMessage(), 5);
2068
        }
2069
    }
2070

    
2071
    /**
2072
     * Handle documents passed to metacat that are encoded using the
2073
     * "multipart/form-data" mime type. This is typically used for uploading
2074
     * data files which may be binary and large.
2075
     */
2076
    private void handleMultipartForm(HttpServletRequest request,
2077
            HttpServletResponse response)
2078
    {
2079
        PrintWriter out = null;
2080
        String action = null;
2081

    
2082
        // Parse the multipart form, and save the parameters in a Hashtable and
2083
        // save the FileParts in a hashtable
2084

    
2085
        Hashtable params = new Hashtable();
2086
        Hashtable fileList = new Hashtable();
2087
        int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2088
                .intValue();
2089
        MetaCatUtil.debugMessage(
2090
                "The limit size of data file is: " + sizeLimit, 50);
2091

    
2092
        try {
2093
            // MBJ: need to put filesize limit in Metacat config
2094
            // (metacat.properties)
2095
            MultipartParser mp = new MultipartParser(request,
2096
                    sizeLimit * 1024 * 1024);
2097
            Part part;
2098
            while ((part = mp.readNextPart()) != null) {
2099
                String name = part.getName();
2100

    
2101
                if (part.isParam()) {
2102
                    // it's a parameter part
2103
                    ParamPart paramPart = (ParamPart) part;
2104
                    String value = paramPart.getStringValue();
2105
                    params.put(name, value);
2106
                    if (name.equals("action")) {
2107
                        action = value;
2108
                    }
2109
                } else if (part.isFile()) {
2110
                    // it's a file part
2111
                    FilePart filePart = (FilePart) part;
2112
                    fileList.put(name, filePart);
2113

    
2114
                    // Stop once the first file part is found, otherwise going
2115
                    // onto the
2116
                    // next part prevents access to the file contents. So...for
2117
                    // upload
2118
                    // to work, the datafile must be the last part
2119
                    break;
2120
                }
2121
            }
2122
        } catch (IOException ioe) {
2123
            try {
2124
                out = response.getWriter();
2125
            } catch (IOException ioe2) {
2126
                System.err
2127
                        .println("Fatal Error: couldn't get response output stream.");
2128
            }
2129
            out.println("<?xml version=\"1.0\"?>");
2130
            out.println("<error>");
2131
            out.println("Error: problem reading multipart data.");
2132
            out.println("</error>");
2133
        }
2134

    
2135
        // Get the session information
2136
        String username = null;
2137
        String password = null;
2138
        String[] groupnames = null;
2139
        String sess_id = null;
2140

    
2141
        // be aware of session expiration on every request
2142
        HttpSession sess = request.getSession(true);
2143
        if (sess.isNew()) {
2144
            // session expired or has not been stored b/w user requests
2145
            username = "public";
2146
            sess.setAttribute("username", username);
2147
        } else {
2148
            username = (String) sess.getAttribute("username");
2149
            password = (String) sess.getAttribute("password");
2150
            groupnames = (String[]) sess.getAttribute("groupnames");
2151
            try {
2152
                sess_id = (String) sess.getId();
2153
            } catch (IllegalStateException ise) {
2154
                System.out
2155
                        .println("error in  handleMultipartForm: this shouldn't "
2156
                                + "happen: the session should be valid: "
2157
                                + ise.getMessage());
2158
            }
2159
        }
2160

    
2161
        // Get the out stream
2162
        try {
2163
            out = response.getWriter();
2164
        } catch (IOException ioe2) {
2165
            MetaCatUtil.debugMessage("Fatal Error: couldn't get response "
2166
                    + "output stream.", 30);
2167
        }
2168

    
2169
        if (action.equals("upload")) {
2170
            if (username != null && !username.equals("public")) {
2171
                handleUploadAction(request, out, params, fileList, username,
2172
                        groupnames);
2173
            } else {
2174

    
2175
                out.println("<?xml version=\"1.0\"?>");
2176
                out.println("<error>");
2177
                out.println("Permission denied for " + action);
2178
                out.println("</error>");
2179
            }
2180
        } else {
2181
            /*
2182
             * try { out = response.getWriter(); } catch (IOException ioe2) {
2183
             * System.err.println("Fatal Error: couldn't get response output
2184
             * stream.");
2185
             */
2186
            out.println("<?xml version=\"1.0\"?>");
2187
            out.println("<error>");
2188
            out.println(
2189
                    "Error: action not registered.  Please report this error.");
2190
            out.println("</error>");
2191
        }
2192
        out.close();
2193
    }
2194

    
2195
    /**
2196
     * Handle the upload action by saving the attached file to disk and
2197
     * registering it in the Metacat db
2198
     */
2199
    private void handleUploadAction(HttpServletRequest request,
2200
            PrintWriter out, Hashtable params, Hashtable fileList,
2201
            String username, String[] groupnames)
2202
    {
2203
        //PrintWriter out = null;
2204
        //Connection conn = null;
2205
        String action = null;
2206
        String docid = null;
2207

    
2208
        /*
2209
         * response.setContentType("text/xml"); try { out =
2210
         * response.getWriter(); } catch (IOException ioe2) {
2211
         * System.err.println("Fatal Error: couldn't get response output
2212
         * stream.");
2213
         */
2214

    
2215
        if (params.containsKey("docid")) {
2216
            docid = (String) params.get("docid");
2217
        }
2218

    
2219
        // Make sure we have a docid and datafile
2220
        if (docid != null && fileList.containsKey("datafile")) {
2221

    
2222
            // Get a reference to the file part of the form
2223
            FilePart filePart = (FilePart) fileList.get("datafile");
2224
            String fileName = filePart.getFileName();
2225
            MetaCatUtil.debugMessage("Uploading filename: " + fileName, 10);
2226

    
2227
            // Check if the right file existed in the uploaded data
2228
            if (fileName != null) {
2229

    
2230
                try {
2231
                    //MetaCatUtil.debugMessage("Upload datafile " + docid
2232
                    // +"...", 10);
2233
                    //If document get lock data file grant
2234
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2235
                        // register the file in the database (which generates
2236
                        // an exception
2237
                        //if the docid is not acceptable or other untoward
2238
                        // things happen
2239
                        DocumentImpl.registerDocument(fileName, "BIN", docid,
2240
                                username);
2241

    
2242
                        // Save the data file to disk using "docid" as the name
2243
                        dataDirectory.mkdirs();
2244
                        File newFile = new File(dataDirectory, docid);
2245
                        long size = filePart.writeTo(newFile);
2246

    
2247
                        EventLog.getInstance().log(request.getRemoteAddr(),
2248
                                username, docid, "upload");
2249
                        // Force replication this data file
2250
                        // To data file, "insert" and update is same
2251
                        // The fourth parameter is null. Because it is
2252
                        // notification server
2253
                        // and this method is in MetaCatServerlet. It is
2254
                        // original command,
2255
                        // not get force replication info from another metacat
2256
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2257
                                docid, "insert", false, null);
2258

    
2259
                        // set content type and other response header fields
2260
                        // first
2261
                        out.println("<?xml version=\"1.0\"?>");
2262
                        out.println("<success>");
2263
                        out.println("<docid>" + docid + "</docid>");
2264
                        out.println("<size>" + size + "</size>");
2265
                        out.println("</success>");
2266
                    }
2267

    
2268
                } catch (Exception e) {
2269
                    out.println("<?xml version=\"1.0\"?>");
2270
                    out.println("<error>");
2271
                    out.println(e.getMessage());
2272
                    out.println("</error>");
2273
                }
2274
            } else {
2275
                // the field did not contain a file
2276
                out.println("<?xml version=\"1.0\"?>");
2277
                out.println("<error>");
2278
                out.println("The uploaded data did not contain a valid file.");
2279
                out.println("</error>");
2280
            }
2281
        } else {
2282
            // Error bcse docid missing or file missing
2283
            out.println("<?xml version=\"1.0\"?>");
2284
            out.println("<error>");
2285
            out.println("The uploaded data did not contain a valid docid "
2286
                    + "or valid file.");
2287
            out.println("</error>");
2288
        }
2289
    }
2290

    
2291
    /*
2292
     * A method to handle set access action
2293
     */
2294
    private void handleSetAccessAction(PrintWriter out, Hashtable params,
2295
            String username)
2296
    {
2297
        String[] docList = null;
2298
        String[] principalList = null;
2299
        String[] permissionList = null;
2300
        String[] permTypeList = null;
2301
        String[] permOrderList = null;
2302
        String permission = null;
2303
        String permType = null;
2304
        String permOrder = null;
2305
        Vector errorList = new Vector();
2306
        String error = null;
2307
        Vector successList = new Vector();
2308
        String success = null;
2309

    
2310
        // Get parameters
2311
        if (params.containsKey("docid")) {
2312
            docList = (String[]) params.get("docid");
2313
        }
2314
        if (params.containsKey("principal")) {
2315
            principalList = (String[]) params.get("principal");
2316
        }
2317
        if (params.containsKey("permission")) {
2318
            permissionList = (String[]) params.get("permission");
2319

    
2320
        }
2321
        if (params.containsKey("permType")) {
2322
            permTypeList = (String[]) params.get("permType");
2323

    
2324
        }
2325
        if (params.containsKey("permOrder")) {
2326
            permOrderList = (String[]) params.get("permOrder");
2327

    
2328
        }
2329

    
2330
        // Make sure the parameter is not null
2331
        if (docList == null || principalList == null || permTypeList == null
2332
                || permissionList == null) {
2333
            error = "Please check your parameter list, it should look like: "
2334
                    + "?action=setaccess&docid=pipeline.1.1&principal=public"
2335
                    + "&permission=read&permType=allow&permOrder=allowFirst";
2336
            errorList.addElement(error);
2337
            outputResponse(successList, errorList, out);
2338
            return;
2339
        }
2340

    
2341
        // Only select first element for permission, type and order
2342
        permission = permissionList[0];
2343
        permType = permTypeList[0];
2344
        if (permOrderList != null) {
2345
            permOrder = permOrderList[0];
2346
        }
2347

    
2348
        // Get package doctype set
2349
        Vector packageSet = MetaCatUtil.getOptionList(MetaCatUtil
2350
                .getOption("packagedoctypeset"));
2351
        //debug
2352
        if (packageSet != null) {
2353
            for (int i = 0; i < packageSet.size(); i++) {
2354
                MetaCatUtil.debugMessage("doctype in package set: "
2355
                        + (String) packageSet.elementAt(i), 34);
2356
            }
2357
        }
2358

    
2359
        // handle every accessionNumber
2360
        for (int i = 0; i < docList.length; i++) {
2361
            String accessionNumber = docList[i];
2362
            String owner = null;
2363
            String publicId = null;
2364
            // Get document owner and public id
2365
            try {
2366
                owner = getFieldValueForDoc(accessionNumber, "user_owner");
2367
                publicId = getFieldValueForDoc(accessionNumber, "doctype");
2368
            } catch (Exception e) {
2369
                MetaCatUtil.debugMessage("Error in handleSetAccessAction: "
2370
                        + e.getMessage(), 30);
2371
                error = "Error in set access control for document - "
2372
                        + accessionNumber + e.getMessage();
2373
                errorList.addElement(error);
2374
                continue;
2375
            }
2376
            //check if user is the owner. Only owner can do owner
2377
            if (username == null || owner == null || !username.equals(owner)) {
2378
                error = "User - " + username
2379
                        + " does not have permission to set "
2380
                        + "access control for docid - " + accessionNumber;
2381
                errorList.addElement(error);
2382
                continue;
2383
            }
2384

    
2385
            // If docid publicid is BIN data file or other beta4, 6 package
2386
            // document
2387
            // we could not do set access control. Because we don't want
2388
            // inconsistent
2389
            // to its access docuemnt
2390
            if (publicId != null && packageSet != null
2391
                    && packageSet.contains(publicId)) {
2392
                error = "Could not set access control to document "
2393
                        + accessionNumber
2394
                        + "because it is in a pakcage and it has a access file for it";
2395
                errorList.addElement(error);
2396
                continue;
2397
            }
2398

    
2399
            // for every principle
2400
            for (int j = 0; j < principalList.length; j++) {
2401
                String principal = principalList[j];
2402
                try {
2403
                    //insert permission
2404
                    AccessControlForSingleFile accessControl = new AccessControlForSingleFile(
2405
                            accessionNumber, principal, permission, permType,
2406
                            permOrder);
2407
                    accessControl.insertPermissions();
2408
                    success = "Set access control to document "
2409
                            + accessionNumber + " successfully";
2410
                    successList.addElement(success);
2411
                } catch (Exception ee) {
2412
                    MetaCatUtil.debugMessage(
2413
                            "Erorr in handleSetAccessAction2: "
2414
                                    + ee.getMessage(), 30);
2415
                    error = "Faild to set access control for document "
2416
                            + accessionNumber + " because " + ee.getMessage();
2417
                    errorList.addElement(error);
2418
                    continue;
2419
                }
2420
            }
2421
        }
2422
        outputResponse(successList, errorList, out);
2423
    }
2424

    
2425
    /*
2426
     * A method try to determin a docid's public id, if couldn't find null will
2427
     * be returned.
2428
     */
2429
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
2430
            throws Exception
2431
    {
2432
        if (accessionNumber == null || accessionNumber.equals("")
2433
                || fieldName == null || fieldName.equals("")) { throw new Exception(
2434
                "Docid or field name was not specified"); }
2435

    
2436
        PreparedStatement pstmt = null;
2437
        ResultSet rs = null;
2438
        String fieldValue = null;
2439
        String docId = null;
2440
        DBConnection conn = null;
2441
        int serialNumber = -1;
2442

    
2443
        // get rid of revision if access number has
2444
        docId = MetaCatUtil.getDocIdFromString(accessionNumber);
2445
        try {
2446
            //check out DBConnection
2447
            conn = DBConnectionPool
2448
                    .getDBConnection("MetaCatServlet.getPublicIdForDoc");
2449
            serialNumber = conn.getCheckOutSerialNumber();
2450
            pstmt = conn.prepareStatement("SELECT " + fieldName
2451
                    + " FROM xml_documents " + "WHERE docid = ? ");
2452

    
2453
            pstmt.setString(1, docId);
2454
            pstmt.execute();
2455
            rs = pstmt.getResultSet();
2456
            boolean hasRow = rs.next();
2457
            int perm = 0;
2458
            if (hasRow) {
2459
                fieldValue = rs.getString(1);
2460
            } else {
2461
                throw new Exception("Could not find document: "
2462
                        + accessionNumber);
2463
            }
2464
        } catch (Exception e) {
2465
            MetaCatUtil.debugMessage(
2466
                    "Exception in MetacatServlet.getPublicIdForDoc: "
2467
                            + e.getMessage(), 30);
2468
            throw e;
2469
        } finally {
2470
            try {
2471
                rs.close();
2472
                pstmt.close();
2473

    
2474
            } finally {
2475
                DBConnectionPool.returnDBConnection(conn, serialNumber);
2476
            }
2477
        }
2478
        return fieldValue;
2479
    }
2480

    
2481
    /*
2482
     * A method to output setAccess action result
2483
     */
2484
    private void outputResponse(Vector successList, Vector errorList,
2485
            PrintWriter out)
2486
    {
2487
        boolean error = false;
2488
        boolean success = false;
2489
        // Output prolog
2490
        out.println(PROLOG);
2491
        // output success message
2492
        if (successList != null) {
2493
            for (int i = 0; i < successList.size(); i++) {
2494
                out.println(SUCCESS);
2495
                out.println((String) successList.elementAt(i));
2496
                out.println(SUCCESSCLOSE);
2497
                success = true;
2498
            }
2499
        }
2500
        // output error message
2501
        if (errorList != null) {
2502
            for (int i = 0; i < errorList.size(); i++) {
2503
                out.println(ERROR);
2504
                out.println((String) errorList.elementAt(i));
2505
                out.println(ERRORCLOSE);
2506
                error = true;
2507
            }
2508
        }
2509

    
2510
        // if no error and no success info, send a error that nothing happened
2511
        if (!error && !success) {
2512
            out.println(ERROR);
2513
            out.println("Nothing happend for setaccess action");
2514
            out.println(ERRORCLOSE);
2515
        }
2516
    }
2517
}
(42-42/62)