Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2010 Regents of the University of California and the
4
 *             National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: jones $'
7
 *     '$Date: 2010-02-03 17:58:12 -0900 (Wed, 03 Feb 2010) $'
8
 * '$Revision: 5211 $'
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 2 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
 */
24

    
25
package edu.ucsb.nceas.metacat;
26

    
27
import java.io.BufferedInputStream;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileReader;
31
import java.io.IOException;
32
import java.io.OutputStream;
33
import java.io.OutputStreamWriter;
34
import java.io.PrintWriter;
35
import java.io.StringReader;
36
import java.io.Writer;
37
import java.net.MalformedURLException;
38
import java.net.URL;
39
import java.sql.PreparedStatement;
40
import java.sql.ResultSet;
41
import java.sql.SQLException;
42
import java.sql.Timestamp;
43
import java.text.ParseException;
44
import java.text.SimpleDateFormat;
45
import java.util.Enumeration;
46
import java.util.HashMap;
47
import java.util.Hashtable;
48
import java.util.Iterator;
49
import java.util.Map;
50
import java.util.Timer;
51
import java.util.Vector;
52
import java.util.zip.ZipEntry;
53
import java.util.zip.ZipOutputStream;
54

    
55
import javax.servlet.ServletContext;
56
import javax.servlet.ServletOutputStream;
57
import javax.servlet.http.HttpServletRequest;
58
import javax.servlet.http.HttpServletResponse;
59
import javax.servlet.http.HttpSession;
60

    
61
import org.apache.log4j.Logger;
62
import org.ecoinformatics.eml.EMLParser;
63

    
64
import au.com.bytecode.opencsv.CSVWriter;
65

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

    
71
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlException;
72
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
73
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
74
import edu.ucsb.nceas.metacat.cart.CartManager;
75
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
76
import edu.ucsb.nceas.metacat.database.DBConnection;
77
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
78
import edu.ucsb.nceas.metacat.dataquery.DataQuery;
79
import edu.ucsb.nceas.metacat.properties.PropertyService;
80
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
81
import edu.ucsb.nceas.metacat.service.SessionService;
82
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
83
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
84
import edu.ucsb.nceas.metacat.shared.ServiceException;
85
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
86
import edu.ucsb.nceas.metacat.spatial.SpatialQuery;
87
import edu.ucsb.nceas.metacat.util.AuthUtil;
88
import edu.ucsb.nceas.metacat.util.DocumentUtil;
89
import edu.ucsb.nceas.metacat.util.MetacatUtil;
90
import edu.ucsb.nceas.metacat.util.RequestUtil;
91
import edu.ucsb.nceas.metacat.util.SystemUtil;
92
import edu.ucsb.nceas.utilities.FileUtil;
93
import edu.ucsb.nceas.utilities.LSIDUtil;
94
import edu.ucsb.nceas.utilities.ParseLSIDException;
95
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
96

    
97
/**
98
 * General entry point for the Metacat server which is called from various 
99
 * mechanisms such as the standard MetacatServlet class and the various web
100
 * service servlets such as RestServlet class.  All application logic should be
101
 * encapsulated in this class, and the calling classes should only contain
102
 * parameter marshaling and demarshaling code, delegating all else to this
103
 * MetacatHandler instance.
104
 * @author Matthew Jones
105
 */
106
public class MetacatHandler {
107

    
108
    private static boolean _sitemapScheduled = false;
109

    
110
    // Constants -- these should be final in a servlet    
111
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
112
    private static final String SUCCESS = "<success>";
113
    private static final String SUCCESSCLOSE = "</success>";
114
    private static final String ERROR = "<error>";
115
    private static final String ERRORCLOSE = "</error>";
116
    
117
    private ServletContext servletContext;
118
	private Timer timer;
119
	
120
    public MetacatHandler(ServletContext servletContext, Timer timer) {
121
    	this.servletContext = servletContext;
122
    	this.timer = timer;
123
    }
124
    
125
    
126
    protected void handleDataquery(
127
            Hashtable<String, String[]> params,
128
            HttpServletResponse response,
129
            String sessionId) throws PropertyNotFoundException, IOException {
130
        
131
        DataQuery dq = null;
132
        if (sessionId != null) {
133
            dq = new DataQuery(sessionId);
134
        }
135
        else {
136
            dq = new DataQuery();
137
        }
138
        
139
        String dataqueryXML = (params.get("dataquery"))[0];
140

    
141
        ResultSet rs = null;
142
        try {
143
            rs = dq.executeQuery(dataqueryXML);
144
        } catch (Exception e) {
145
            //probably need to do something here
146
            e.printStackTrace();
147
            return;
148
        }
149
        
150
        //process the result set
151
        String qformat = "csv";
152
        String[] temp = params.get("qformat");
153
        if (temp != null && temp.length > 0) {
154
            qformat = temp[0];
155
        }
156
        String fileName = "query-results." + qformat;
157
        
158
        //get the results as csv file
159
        if (qformat != null && qformat.equalsIgnoreCase("csv")) {
160
            response.setContentType("text/csv");
161
            //response.setContentType("application/csv");
162
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
163
            
164
            Writer writer = new OutputStreamWriter(response.getOutputStream());
165
            CSVWriter csv = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
166
            try {
167
                
168
                csv.writeAll(rs, true);
169
                
170
                csv.flush();
171
                response.flushBuffer();
172
                
173
                rs.close();
174
                
175
            } catch (SQLException e) {
176
                e.printStackTrace();
177
            }
178
            
179
            return;
180
        }
181
        
182
    }
183
    
184
    protected void handleEditCart(
185
            Hashtable<String, String[]> params,
186
            HttpServletResponse response,
187
            String sessionId) throws PropertyNotFoundException, IOException {
188
        
189
        CartManager cm = null;
190
        if (sessionId != null) {
191
            cm = new CartManager(sessionId);
192
        }
193
        else {
194
            cm = new CartManager();
195
        }
196
        
197
        String editOperation = (params.get("operation"))[0];
198
        
199
        String[] docids = params.get("docid");
200
        String[] field = params.get("field");
201
        String[] path = params.get("path");
202
        
203
        Map<String,String> fields = null;
204
        if (field != null && path != null) {
205
            fields = new HashMap<String,String>();
206
            fields.put(field[0], path[0]);
207
        }
208
        
209
        //TODO handle attribute map (metadata fields)
210
        cm.editCart(editOperation, docids, fields);
211
        
212
    }
213
    
214
    // ///////////////////////////// METACAT SPATIAL ///////////////////////////
215
    
216
    /**
217
     * handles all spatial queries -- these queries may include any of the
218
     * queries supported by the WFS / WMS standards
219
     * 
220
     * handleSQuery(out, params, response, username, groupnames, sess_id);
221
     */
222
    protected void handleSpatialQuery(PrintWriter out, Hashtable<String, String[]> params,
223
            HttpServletResponse response,
224
            String username, String[] groupnames,
225
            String sess_id) throws PropertyNotFoundException {
226
        
227
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
228
        
229
        if ( !PropertyService.getProperty("spatial.runSpatialOption").equals("true") ) {
230
            response.setContentType("text/html");
231
            out.println("<html> Metacat Spatial Option is turned off </html>");
232
            out.close();
233
            return ;
234
        }
235
        
236
        /*
237
         * Perform spatial query against spatial cache
238
         */
239
        float _xmax = Float.valueOf( (params.get("xmax"))[0] ).floatValue();
240
        float _ymax = Float.valueOf( (params.get("ymax"))[0] ).floatValue();
241
        float _xmin = Float.valueOf( (params.get("xmin"))[0] ).floatValue();
242
        float _ymin = Float.valueOf( (params.get("ymin"))[0] ).floatValue();
243
        SpatialQuery sq = new SpatialQuery();
244
        Vector<String> docids = sq.filterByBbox( _xmin, _ymin, _xmax, _ymax );
245
        // logMetacat.info(" --- Spatial Query completed. Passing on the SQuery
246
        // handler");
247
        // logMetacat.warn("\n\n ******* after spatial query, we've got " +
248
        // docids.size() + " docids \n\n");
249
        
250
        /*
251
         * Create an array matching docids
252
         */
253
        String [] docidArray = new String[docids.size()];
254
        docids.toArray(docidArray);
255
        
256
        /*
257
         * Create squery string
258
         */
259
        String squery = DocumentIdQuery.createDocidQuery( docidArray );
260
        // logMetacat.info("-----------\n" + squery + "\n------------------");
261
        String[] queryArray = new String[1];
262
        queryArray[0] = squery;
263
        params.put("query", queryArray);
264
        
265
        /*
266
         * Determine qformat
267
         */
268
        String[] qformatArray = new String[1];
269
        try {
270
            String _skin = (params.get("skin"))[0];
271
            qformatArray[0] = _skin;
272
        } catch (java.lang.NullPointerException e) {
273
            // should be "default" but keep this for backwards compatibility
274
            // with knp site
275
            logMetacat.warn("MetaCatServlet.handleSpatialQuery - No SKIN specified for metacat actions=spatial_query... defaulting to 'knp' skin !\n");
276
            qformatArray[0] = "knp";
277
        }
278
        params.put("qformat", qformatArray);
279
        
280
        // change the action
281
        String[] actionArray = new String[1];
282
        actionArray[0] = "squery";
283
        params.put("action", actionArray);
284
        
285
        /*
286
         * Pass the docids to the DBQuery contructor
287
         */
288
        // This is a hack to get the empty result set to show...
289
        // Otherwise dbquery sees no docidOverrides and does a full % percent
290
        // query
291
        if (docids.size() == 0)
292
            docids.add("");
293
        
294
        DBQuery queryobj = new DBQuery(docids);
295
        queryobj.findDocuments(response, out, params, username, groupnames, sess_id);
296
        
297
    }
298
    
299
    // LOGIN & LOGOUT SECTION
300
    /**
301
     * Handle the login request. Create a new session object. Do user
302
     * authentication through the session.
303
     */
304
    public void handleLoginAction(PrintWriter out, Hashtable<String, String[]> params,
305
            HttpServletRequest request, HttpServletResponse response) {
306
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
307
        AuthSession sess = null;
308
        
309
        if(params.get("username") == null){
310
            response.setContentType("text/xml");
311
            out.println("<?xml version=\"1.0\"?>");
312
            out.println("<error>");
313
            out.println("Username not specified");
314
            out.println("</error>");
315
            return;
316
        }
317
        
318
        // }
319
        
320
        if(params.get("password") == null){
321
            response.setContentType("text/xml");
322
            out.println("<?xml version=\"1.0\"?>");
323
            out.println("<error>");
324
            out.println("Password not specified");
325
            out.println("</error>");
326
            return;
327
        }
328
        
329
        String un = (params.get("username"))[0];
330
        logMetacat.info("MetaCatServlet.handleLoginAction - user " + un + " is trying to login");
331
        String pw = (params.get("password"))[0];
332
        
333
        String qformat = "xml";
334
        if (params.get("qformat") != null) {
335
            qformat = (params.get("qformat"))[0];
336
        }
337
        
338
        try {
339
            sess = new AuthSession();
340
        } catch (Exception e) {
341
            String errorMsg = "MetacatServlet.handleLoginAction - Problem in MetacatServlet.handleLoginAction() authenicating session: "
342
                + e.getMessage();
343
            logMetacat.error(errorMsg);
344
            out.println(errorMsg);
345
            e.printStackTrace(System.out);
346
            return;
347
        }
348
        boolean isValid = sess.authenticate(request, un, pw);
349
        
350
        //if it is authernticate is true, store the session
351
        if (isValid) {
352
            HttpSession session = sess.getSessions();
353
            String id = session.getId();
354
            
355
            logMetacat.debug("MetaCatServlet.handleLoginAction - Store session id " + id
356
                    + " which has username" + session.getAttribute("username")
357
                    + " into hash in login method");
358
            try {
359
                SessionService.registerSession(id, 
360
                        (String) session.getAttribute("username"), 
361
                        (String[]) session.getAttribute("groupnames"), 
362
                        (String) session.getAttribute("password"), 
363
                        (String) session.getAttribute("name"));
364
            } catch (ServiceException se) {
365
                String errorMsg = "MetacatServlet.handleLoginAction - service problem registering session: "
366
                        + se.getMessage();
367
                logMetacat.error("MetaCatServlet.handleLoginAction - " + errorMsg);
368
                out.println(errorMsg);
369
                se.printStackTrace(System.out);
370
                return;
371
            }           
372
        }
373
                
374
        // format and transform the output
375
        if (qformat.equals("xml")) {
376
            response.setContentType("text/xml");
377
            out.println(sess.getMessage());
378
        } else {
379
            try {
380
                DBTransform trans = new DBTransform();
381
                response.setContentType("text/html");
382
                trans.transformXMLDocument(sess.getMessage(),
383
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
384
                        out, null, null);
385
            } catch (Exception e) {               
386
                logMetacat.error("MetaCatServlet.handleLoginAction - General error"
387
                        + e.getMessage());
388
                e.printStackTrace(System.out);
389
            }
390
        }
391
    }
392
    
393
    /**
394
     * Handle the logout request. Close the connection.
395
     */
396
    public void handleLogoutAction(PrintWriter out, Hashtable<String, String[]> params,
397
            HttpServletRequest request, HttpServletResponse response) {
398
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
399
        String qformat = "xml";
400
        if(params.get("qformat") != null){
401
            qformat = params.get("qformat")[0];
402
        }
403
        
404
        // close the connection
405
        HttpSession sess = request.getSession(false);
406
        logMetacat.info("MetaCatServlet.handleLogoutAction - After get session in logout request");
407
        if (sess != null) {
408
            logMetacat.info("MetaCatServlet.handleLogoutAction - The session id " + sess.getId()
409
            + " will be invalidate in logout action");
410
            logMetacat.info("MetaCatServlet.handleLogoutAction - The session contains user "
411
                    + sess.getAttribute("username")
412
                    + " will be invalidate in logout action");
413
            sess.invalidate();
414
            SessionService.unRegisterSession(sess.getId());
415
        }
416
        
417
        // produce output
418
        StringBuffer output = new StringBuffer();
419
        output.append("<?xml version=\"1.0\"?>");
420
        output.append("<logout>");
421
        output.append("User logged out");
422
        output.append("</logout>");
423
        
424
        //format and transform the output
425
        if (qformat.equals("xml")) {
426
            response.setContentType("text/xml");
427
            out.println(output.toString());
428
        } else {
429
            try {
430
                DBTransform trans = new DBTransform();
431
                response.setContentType("text/html");
432
                trans.transformXMLDocument(output.toString(),
433
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
434
                        out, null, null);
435
            } catch (Exception e) {
436
                logMetacat.error(
437
                        "MetaCatServlet.handleLogoutAction - General error: "
438
                        + e.getMessage());
439
                e.printStackTrace(System.out);
440
            }
441
        }
442
    }
443
    
444
    // END OF LOGIN & LOGOUT SECTION
445
    
446
    // SQUERY & QUERY SECTION
447
    /**
448
     * Retreive the squery xml, execute it and display it
449
     *
450
     * @param out the output stream to the client
451
     * @param params the Hashtable of parameters that should be included in the
452
     *            squery.
453
     * @param response the response object linked to the client
454
     * @param conn the database connection
455
     */
456
    protected void handleSQuery(PrintWriter out, Hashtable<String, String[]> params,
457
            HttpServletResponse response, String user, String[] groups,
458
            String sessionid) throws PropertyNotFoundException {
459
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
460
        long squeryWarnLimit = Long.parseLong(PropertyService.getProperty("database.squeryTimeWarnLimit"));
461
        
462
        long startTime = System.currentTimeMillis();
463
        DBQuery queryobj = new DBQuery();
464
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
465
        long outPutTime = System.currentTimeMillis();
466
        long runTime = outPutTime - startTime;
467

    
468
        if (runTime > squeryWarnLimit) {
469
            logMetacat.warn("MetaCatServlet.handleSQuery - Long running squery.  Total time: " + runTime + 
470
                    " ms, squery: " + ((String[])params.get("query"))[0]);
471
        }
472
        logMetacat.debug("MetaCatServlet.handleSQuery - squery: " + ((String[])params.get("query"))[0] + 
473
                " ran in " + runTime + " ms");
474
    }
475
    
476
    /**
477
     * Create the xml query, execute it and display the results.
478
     *
479
     * @param out the output stream to the client
480
     * @param params the Hashtable of parameters that should be included in the
481
     *            squery.
482
     * @param response the response object linked to the client
483
     */
484
    protected void handleQuery(PrintWriter out, Hashtable<String, String[]> params,
485
            HttpServletResponse response, String user, String[] groups,
486
            String sessionid) throws PropertyNotFoundException {
487
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
488
        long queryWarnLimit = Long.parseLong(PropertyService.getProperty("database.queryTimeWarnLimit"));
489
        
490
        //create the query and run it
491
        String xmlquery = DBQuery.createSQuery(params);
492
        String[] queryArray = new String[1];
493
        queryArray[0] = xmlquery;
494
        params.put("query", queryArray);
495
        long startTime = System.currentTimeMillis();
496
        DBQuery queryobj = new DBQuery();
497
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
498
        long outPutTime = System.currentTimeMillis();
499
        long runTime = outPutTime -startTime;
500

    
501
        if (runTime > queryWarnLimit) {
502
            logMetacat.warn("MetaCatServlet.handleQuery - Long running squery.  Total time: " + runTime + 
503
                    " ms, squery: " + ((String[])params.get("query"))[0]);
504
        }
505
        logMetacat.debug("MetaCatServlet.handleQuery - query: " + ((String[])params.get("query"))[0] + 
506
                " ran in " + runTime + " ms");
507
    }
508
    
509
    // END OF SQUERY & QUERY SECTION
510
    
511
    //Export section
512
    /**
513
     * Handle the "export" request of data package from Metacat in zip format
514
     *
515
     * @param params the Hashtable of HTTP request parameters
516
     * @param response the HTTP response object linked to the client
517
     * @param user the username sent the request
518
     * @param groups the user's groupnames
519
     */
520
    protected void handleExportAction(Hashtable<String, String[]> params,
521
            HttpServletResponse response,
522
            String user, String[] groups, String passWord) {
523
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
524
        // Output stream
525
        ServletOutputStream out = null;
526
        // Zip output stream
527
        ZipOutputStream zOut = null;
528
        DBQuery queryObj = null;
529
        
530
        String[] docs = new String[10];
531
        String docId = "";
532
        
533
        try {
534
            // read the params
535
            if (params.containsKey("docid")) {
536
                docs = params.get("docid");
537
            }
538
            // Create a DBuery to handle export
539
            queryObj = new DBQuery();
540
            // Get the docid
541
            docId = docs[0];
542
            // Make sure the client specify docid
543
            if (docId == null || docId.equals("")) {
544
                response.setContentType("text/xml"); //MIME type
545
                // Get a printwriter
546
                PrintWriter pw = response.getWriter();
547
                // Send back message
548
                pw.println("<?xml version=\"1.0\"?>");
549
                pw.println("<error>");
550
                pw.println("You didn't specify requested docid");
551
                pw.println("</error>");
552
                // Close printwriter
553
                pw.close();
554
                return;
555
            }
556
            // Get output stream
557
            out = response.getOutputStream();
558
            response.setContentType("application/zip"); //MIME type
559
            response.setHeader("Content-Disposition",
560
                    "attachment; filename="
561
                    + docId + ".zip"); // Set the name of the zip file
562
            
563
            zOut = new ZipOutputStream(out);
564
            zOut = queryObj
565
                    .getZippedPackage(docId, out, user, groups, passWord);
566
            zOut.finish(); //terminate the zip file
567
            zOut.close(); //close the zip stream
568
            
569
        } catch (Exception e) {
570
            try {
571
                response.setContentType("text/xml"); //MIME type
572
                // Send error message back
573
                if (out != null) {
574
                    PrintWriter pw = new PrintWriter(out);
575
                    pw.println("<?xml version=\"1.0\"?>");
576
                    pw.println("<error>");
577
                    pw.println(e.getMessage());
578
                    pw.println("</error>");
579
                    // Close printwriter
580
                    pw.close();
581
                    // Close output stream
582
                    out.close();
583
                }
584
                // Close zip output stream
585
                if (zOut != null) {
586
                    zOut.close();
587
                }
588
            } catch (IOException ioe) {
589
                logMetacat.error("MetaCatServlet.handleExportAction - Problem with the servlet output: "
590
                        + ioe.getMessage());
591
                e.printStackTrace(System.out);
592
            }
593
            
594
            logMetacat.error("MetaCatServlet.handleExportAction - General error: "
595
                    + e.getMessage());
596
            e.printStackTrace(System.out);
597
            
598
        }
599
        
600
    }
601
    
602
    /**
603
     * In eml2 document, the xml can have inline data and data was stripped off
604
     * and store in file system. This action can be used to read inline data
605
     * only
606
     *
607
     * @param params the Hashtable of HTTP request parameters
608
     * @param response the HTTP response object linked to the client
609
     * @param user the username sent the request
610
     * @param groups the user's groupnames
611
     */
612
    protected void handleReadInlineDataAction(Hashtable<String, String[]> params,
613
            HttpServletRequest request, HttpServletResponse response,
614
            String user, String passWord, String[] groups) {
615
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
616
        String[] docs = new String[10];
617
        String inlineDataId = null;
618
        String docId = "";
619
        ServletOutputStream out = null;
620
        
621
        try {
622
            // read the params
623
            if (params.containsKey("inlinedataid")) {
624
                docs = params.get("inlinedataid");
625
            }
626
            // Get the docid
627
            inlineDataId = docs[0];
628
            // Make sure the client specify docid
629
            if (inlineDataId == null || inlineDataId.equals("")) {
630
                throw new Exception("You didn't specify requested inlinedataid"); }
631
            
632
            // check for permission
633
            docId = 
634
                DocumentUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
635
            PermissionController controller = new PermissionController(docId);
636
            // check top level read permission
637
            if (!controller.hasPermission(user, groups,
638
                    AccessControlInterface.READSTRING)) {
639
                throw new Exception("User " + user
640
                        + " doesn't have permission " + " to read document "
641
                        + docId);
642
            } else {
643
                //check data access level
644
                try {
645
                    Hashtable<String,String> unReadableInlineDataList =
646
                            PermissionController.getUnReadableInlineDataIdList(docId,
647
                            user, groups, false);
648
                    String inlineDataIdWithoutRev = DocumentUtil.getInlineDataIdWithoutRev(inlineDataId);
649
                    if (unReadableInlineDataList.containsValue(inlineDataIdWithoutRev)) {
650
                        throw new Exception("User " + user
651
                                + " doesn't have permission " + " to read inlinedata "
652
                                + inlineDataId);
653
                        
654
                    }//if
655
                }//try
656
                catch (Exception e) {
657
                    throw e;
658
                }//catch
659
            }//else
660
            
661
            // Get output stream
662
            out = response.getOutputStream();
663
            // read the inline data from the file
664
            String inlinePath = PropertyService.getProperty("application.inlinedatafilepath");
665
            File lineData = new File(inlinePath, inlineDataId);
666
            FileInputStream input = new FileInputStream(lineData);
667
            byte[] buffer = new byte[4 * 1024];
668
            int bytes = input.read(buffer);
669
            while (bytes != -1) {
670
                out.write(buffer, 0, bytes);
671
                bytes = input.read(buffer);
672
            }
673
            out.close();
674
            
675
            EventLog.getInstance().log(request.getRemoteAddr(), user,
676
                    inlineDataId, "readinlinedata");
677
        } catch (Exception e) {
678
            try {
679
                PrintWriter pw = null;
680
                // Send error message back
681
                if (out != null) {
682
                    pw = new PrintWriter(out);
683
                } else {
684
                    pw = response.getWriter();
685
                }
686
                pw.println("<?xml version=\"1.0\"?>");
687
                pw.println("<error>");
688
                pw.println(e.getMessage());
689
                pw.println("</error>");
690
                // Close printwriter
691
                pw.close();
692
                // Close output stream if out is not null
693
                if (out != null) {
694
                    out.close();
695
                }
696
            } catch (IOException ioe) {
697
                logMetacat.error("MetaCatServlet.handleReadInlineDataAction - Problem with the servlet output: "
698
                        + ioe.getMessage());
699
                e.printStackTrace(System.out);
700
            }
701
            logMetacat.error("MetaCatServlet.handleReadInlineDataAction - General error: "
702
                    + e.getMessage());
703
            e.printStackTrace(System.out);
704
        }
705
    }
706
    
707
    /**
708
     * Handle the "read" request of metadata/data files from Metacat or any
709
     * files from Internet; transformed metadata XML document into HTML
710
     * presentation if requested; zip files when more than one were requested.
711
     *
712
     * @param params the Hashtable of HTTP request parameters
713
     * @param request the HTTP request object linked to the client
714
     * @param response the HTTP response object linked to the client
715
     * @param user the username sent the request
716
     * @param groups the user's groupnames
717
     */
718
    public void handleReadAction(Hashtable<String, String[]> params, HttpServletRequest request,
719
            HttpServletResponse response, String user, String passWord,
720
            String[] groups) {
721
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
722
        ServletOutputStream out = null;
723
        ZipOutputStream zout = null;
724
        PrintWriter pw = null;
725
        boolean zip = false;
726
        boolean withInlineData = true;
727
        
728
        try {
729
            String[] docs = new String[0];
730
            String docid = "";
731
            String qformat = "";
732
            
733
            // read the params
734
            if (params.containsKey("docid")) {
735
                docs = params.get("docid");
736
            }
737
            if (params.containsKey("qformat")) {
738
                qformat = params.get("qformat")[0];
739
            }
740
            // the param for only metadata (eml)
741
            // we don't support read a eml document without inline data now.
742
            /*if (params.containsKey("inlinedata")) {
743
             
744
                String inlineData = ((String[]) params.get("inlinedata"))[0];
745
                if (inlineData.equalsIgnoreCase("false")) {
746
                    withInlineData = false;
747
                }
748
            }*/
749
            if ((docs.length > 1) || qformat.equals("zip")) {
750
                zip = true;
751
                out = response.getOutputStream();
752
                response.setContentType("application/zip"); //MIME type
753
                zout = new ZipOutputStream(out);
754
            }
755
            // go through the list of docs to read
756
            for (int i = 0; i < docs.length; i++) {
757
                String providedFileName = null;
758
                if (params.containsKey(docs[i])) {
759
                    providedFileName = params.get(docs[i])[0];
760
                }
761
                try {
762
                    
763
                    URL murl = new URL(docs[i]);
764
                    Hashtable<String,String> murlQueryStr = MetacatUtil.parseQuery(
765
                            murl.getQuery());
766
                    // case docid="http://.../?docid=aaa"
767
                    // or docid="metacat://.../?docid=bbb"
768
                    if (murlQueryStr.containsKey("docid")) {
769
                        // get only docid, eliminate the rest
770
                        docid = murlQueryStr.get("docid");
771
                        if (zip) {
772
                            addDocToZip(request, docid, providedFileName, zout, user, groups);
773
                        } else {
774
                            readFromMetacat(request.getRemoteAddr(), response, response.getOutputStream(), docid, qformat,
775
                                    user, groups, withInlineData, params);
776
                        }
777
                        
778
                        // case docid="http://.../filename"
779
                    } else {
780
                        docid = docs[i];
781
                        if (zip) {
782
                            addDocToZip(request, docid, providedFileName, zout, user, groups);
783
                        } else {
784
                            readFromURLConnection(response, docid);
785
                        }
786
                    }
787
                    
788
                } catch (MalformedURLException mue) {
789
                    docid = docs[i];
790
                    if (zip) {
791
                        addDocToZip(request, docid, providedFileName, zout, user, groups);
792
                    } else {
793
                    	if (out == null) {
794
                    		out = response.getOutputStream();
795
                    	}
796
                        readFromMetacat(request.getRemoteAddr(), response, out, docid, qformat,
797
                                user, groups, withInlineData, params);
798
                    }
799
                }
800
            }
801
            
802
            if (zip) {
803
                zout.finish(); //terminate the zip file
804
                zout.close(); //close the zip stream
805
            }
806
            
807
        } catch (McdbDocNotFoundException notFoundE) {
808
            // To handle doc not found exception
809
            // the docid which didn't be found
810
            String notFoundDocId = notFoundE.getUnfoundDocId();
811
            String notFoundRevision = notFoundE.getUnfoundRevision();
812
            logMetacat.warn("MetaCatServlet.handleReadAction - Missed id: " + notFoundDocId);
813
            logMetacat.warn("MetaCatServlet.handleReadAction - Missed rev: " + notFoundRevision);
814
            try {
815
                // read docid from remote server
816
                readFromRemoteMetaCat(response, notFoundDocId,
817
                        notFoundRevision, user, passWord, out, zip, zout);
818
                // Close zout outputstream
819
                if (zout != null) {
820
                    zout.close();
821
                }
822
                // close output stream
823
                if (out != null) {
824
                    out.close();
825
                }
826
                
827
            } catch (Exception exc) {
828
                logMetacat.error("MetaCatServlet.handleReadAction - General error: "
829
                        + exc.getMessage());
830
                exc.printStackTrace(System.out);
831
                try {
832
                    if (out != null) {
833
                        response.setContentType("text/xml");
834
                        // Send back error message by printWriter
835
                        pw = new PrintWriter(out);
836
                        pw.println("<?xml version=\"1.0\"?>");
837
                        pw.println("<error>");
838
                        pw.println(notFoundE.getMessage());
839
                        pw.println("</error>");
840
                        pw.close();
841
                        out.close();
842
                        
843
                    } else {
844
                        response.setContentType("text/xml"); //MIME type
845
                        // Send back error message if out = null
846
                        if (pw == null) {
847
                            // If pw is null, open the respnose
848
                            pw = response.getWriter();
849
                        }
850
                        pw.println("<?xml version=\"1.0\"?>");
851
                        pw.println("<error>");
852
                        pw.println(notFoundE.getMessage());
853
                        pw.println("</error>");
854
                        pw.close();
855
                    }
856
                    // close zout
857
                    if (zout != null) {
858
                        zout.close();
859
                    }
860
                } catch (IOException ie) {
861
                    logMetacat.error("MetaCatServlet.handleReadAction - Problem with the servlet output: "
862
                            + ie.getMessage());
863
                    ie.printStackTrace(System.out);
864
                }
865
            }
866
        } catch (Exception e) {
867
            try {
868
                
869
                if (out != null) {
870
                    response.setContentType("text/xml"); //MIME type
871
                    pw = new PrintWriter(out);
872
                    pw.println("<?xml version=\"1.0\"?>");
873
                    pw.println("<error>");
874
                    pw.println(e.getMessage());
875
                    pw.println("</error>");
876
                    pw.close();
877
                    out.close();
878
                } else {
879
                    response.setContentType("text/xml"); //MIME type
880
                    // Send back error message if out = null
881
                    if (pw == null) {
882
                        pw = response.getWriter();
883
                    }
884
                    pw.println("<?xml version=\"1.0\"?>");
885
                    pw.println("<error>");
886
                    pw.println(e.getMessage());
887
                    pw.println("</error>");
888
                    pw.close();
889
                    
890
                }
891
                // Close zip output stream
892
                if (zout != null) {
893
                    zout.close();
894
                }
895
                
896
            } catch (Exception e2) {
897
                logMetacat.error("MetaCatServlet.handleReadAction - Problem with the servlet output: "
898
                        + e2.getMessage());
899
                e2.printStackTrace(System.out);
900
                
901
            }
902
            
903
            logMetacat.error("MetaCatServlet.handleReadAction - General error: "
904
                    + e.getMessage());
905
            e.printStackTrace(System.out);
906
        }
907
    }
908
    
909
    /** read metadata or data from Metacat
910
     * @throws PropertyNotFoundException 
911
     * @throws ParseLSIDException 
912
     * @throws InsufficientKarmaException 
913
     */
914
    public void readFromMetacat(String ipAddress,
915
            HttpServletResponse response, OutputStream out, String docid, String qformat,
916
            String user, String[] groups, boolean withInlineData, 
917
            Hashtable<String, String[]> params) throws ClassNotFoundException, 
918
            IOException, SQLException, McdbException, PropertyNotFoundException, 
919
            ParseLSIDException, InsufficientKarmaException {
920
        
921
        Logger logMetacat = Logger.getLogger(MetacatHandler.class);
922
        try {
923
            
924
            if (docid.startsWith("urn:")) {
925
                docid = LSIDUtil.getDocId(docid, true);                 
926
            }
927
            
928
            // here is hack for handle docid=john.10(in order to tell mike.jim.10.1
929
            // mike.jim.10, we require to provide entire docid with rev). But
930
            // some old client they only provide docid without rev, so we need
931
            // to handle this suituation. First we will check how many
932
            // seperator here, if only one, we will append the rev in xml_documents
933
            // to the id.
934
            docid = appendRev(docid);
935
            
936
            DocumentImpl doc = new DocumentImpl(docid);
937
            
938
            //check the permission for read
939
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
940
                InsufficientKarmaException e = new InsufficientKarmaException("User " + user
941
                        + " does not have permission"
942
                        + " to read the document with the docid " + docid);
943
                throw e;
944
            }
945
            
946
            if (doc.getRootNodeID() == 0) {
947
                // this is data file, so find the path on disk for the file
948
                String filepath = PropertyService.getProperty("application.datafilepath");
949
                if (!filepath.endsWith("/")) {
950
                    filepath += "/";
951
                }
952
                String filename = filepath + docid;
953
                FileInputStream fin = null;
954
                fin = new FileInputStream(filename);
955
                
956
                if (response != null) {
957
                    // MIME type
958
                    String contentType = servletContext.getMimeType(filename);
959
                    if (contentType == null) {
960
                        ContentTypeProvider provider = new ContentTypeProvider(
961
                                docid);
962
                        contentType = provider.getContentType();
963
                        logMetacat.info("MetaCatServlet.readFromMetacat - Final contenttype is: "
964
                                + contentType);
965
                    }
966
                    response.setContentType(contentType);
967

    
968
                    // Set the output filename on the response
969
                    String outputname = generateOutputName(docid, params, doc);                    
970
                    response.setHeader("Content-Disposition",
971
                            "attachment; filename=\"" + outputname + "\"");
972
                }
973
                
974
                // Write the data to the output stream
975
                try {
976
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
977
                    int b = fin.read(buf);
978
                    while (b != -1) {
979
                        out.write(buf, 0, b);
980
                        b = fin.read(buf);
981
                    }
982
                } finally {
983
                    if (fin != null) fin.close();
984
                }
985
                
986
            } else {
987
                // this is metadata doc
988
                if (qformat.equals("xml") || qformat.equals("")) {
989
                    // if equals "", that means no qformat is specified. hence
990
                    // by default the document should be returned in xml format
991
                    // set content type first
992
                    
993
                    if (response != null) {
994
                        response.setContentType("text/xml"); //MIME type
995
                        response.setHeader("Content-Disposition",
996
                                "attachment; filename=" + docid + ".xml");
997
                    }
998
                    
999
                    // Try to get the metadata file from disk. If it isn't
1000
                    // found, create it from the db and write it to disk then.
1001
                    try {
1002
                        PrintWriter pw = new PrintWriter(out);
1003
                        doc.toXml(pw, user, groups, withInlineData);               
1004
                    } catch (McdbException e) {
1005
                        // any exceptions in reading the xml from disc, and we go back to the
1006
                        // old way of creating the xml directly.
1007
                        logMetacat.error("MetaCatServlet.readFromMetacat - could not read from document file " + docid 
1008
                                + ": " + e.getMessage());
1009
                        e.printStackTrace(System.out);
1010
                        PrintWriter pw = new PrintWriter(out);
1011
                        doc.toXmlFromDb(pw, user, groups, withInlineData);
1012
                    }
1013
                } else {
1014
                    // TODO MCD, this should read from disk as well?
1015
                    //*** This is a metadata doc, to be returned in a skin/custom format.
1016
                    //*** Add param to indicate if public has read access or not.
1017
                    logMetacat.debug("User: \n" + user);
1018
                    if (!user.equals("public")) {
1019
                        if (DocumentImpl.hasReadPermission("public", null, docid))
1020
                            params.put("publicRead", new String[] {"true"});
1021
                        else
1022
                            params.put("publicRead", new String[] {"false"});
1023
                    }
1024
                    
1025
                    if (response != null) {
1026
                        response.setContentType("text/html"); //MIME type
1027
                    }
1028
                    
1029
                    PrintWriter pw = new PrintWriter(out);
1030
                    
1031
                    // Look up the document type
1032
                    String doctype = doc.getDoctype();
1033
                    // Transform the document to the new doctype
1034
                    DBTransform dbt = new DBTransform();
1035
                    dbt.transformXMLDocument(doc.toString(user, groups,
1036
                            withInlineData), doctype, "-//W3C//HTML//EN",
1037
                            qformat, pw, params, null);
1038
                }
1039
                
1040
            }
1041
            EventLog.getInstance().log(ipAddress, user, docid, "read");
1042
        } catch (PropertyNotFoundException except) {
1043
            throw except;
1044
        }
1045
    }
1046

    
1047
    /**
1048
     * Create a filename to be used for naming a downloaded document
1049
     * @param docid the identifier of the document to be named
1050
     * @param params the parameters of the request
1051
     * @param doc the DocumentImpl of the document to be named
1052
     * @return String containing a name for the download
1053
     */
1054
    private String generateOutputName(String docid,
1055
            Hashtable<String, String[]> params, DocumentImpl doc) {
1056
        String outputname = null;
1057
        // check for the existence of a metadatadocid parameter,
1058
        // if this is sent, then send a filename which contains both
1059
        // the metadata docid and the data docid, so the link with
1060
        // metadata is explicitly encoded in the filename.
1061
        String metadatadocid = null;
1062
        Vector<String> nameparts = new Vector<String>();
1063

    
1064
        if(params.containsKey("metadatadocid")) {
1065
            metadatadocid = params.get("metadatadocid")[0];
1066
        }
1067
        if (metadatadocid != null && !metadatadocid.equals("")) {
1068
            nameparts.add(metadatadocid);
1069
        }
1070
        // we'll always have the docid, include it in the name
1071
        String doctype = doc.getDoctype();
1072
        // TODO: fix this to lookup the associated FGDC metadata document,
1073
        // and grab the doctype tag for it.  These should be set to something 
1074
        // consistent, not 'metadata' as it stands...
1075
        //if (!doctype.equals("metadata")) {
1076
        //    nameparts.add(docid);
1077
        //} 
1078
        nameparts.add(docid);
1079
        // Set the name of the data file to the entity name plus docid,
1080
        // or if that is unavailable, use the docid alone
1081
        String docname = doc.getDocname();
1082
        if (docname != null && !docname.equals("")) {
1083
            nameparts.add(docname); 
1084
        }
1085
        // combine the name elements with a dash, using a 'join' equivalent
1086
        String delimiter = "-";
1087
        Iterator<String> iter = nameparts.iterator();
1088
        StringBuffer buffer = new StringBuffer(iter.next());
1089
        while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
1090
        outputname = buffer.toString();
1091
        return outputname;
1092
    }
1093
    
1094
    /**
1095
     * read data from URLConnection
1096
     */
1097
    private void readFromURLConnection(HttpServletResponse response,
1098
            String docid) throws IOException, MalformedURLException {
1099
        ServletOutputStream out = response.getOutputStream();
1100
        String contentType = servletContext.getMimeType(docid); //MIME type
1101
        if (contentType == null) {
1102
            if (docid.endsWith(".xml")) {
1103
                contentType = "text/xml";
1104
            } else if (docid.endsWith(".css")) {
1105
                contentType = "text/css";
1106
            } else if (docid.endsWith(".dtd")) {
1107
                contentType = "text/plain";
1108
            } else if (docid.endsWith(".xsd")) {
1109
                contentType = "text/xml";
1110
            } else if (docid.endsWith("/")) {
1111
                contentType = "text/html";
1112
            } else {
1113
                File f = new File(docid);
1114
                if (f.isDirectory()) {
1115
                    contentType = "text/html";
1116
                } else {
1117
                    contentType = "application/octet-stream";
1118
                }
1119
            }
1120
        }
1121
        response.setContentType(contentType);
1122
        // if we decide to use "application/octet-stream" for all data returns
1123
        // response.setContentType("application/octet-stream");
1124
        
1125
        // this is http url
1126
        URL url = new URL(docid);
1127
        BufferedInputStream bis = null;
1128
        try {
1129
            bis = new BufferedInputStream(url.openStream());
1130
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1131
            int b = bis.read(buf);
1132
            while (b != -1) {
1133
                out.write(buf, 0, b);
1134
                b = bis.read(buf);
1135
            }
1136
        } finally {
1137
            if (bis != null) bis.close();
1138
        }
1139
        
1140
    }
1141
    
1142
    /**
1143
     * read file/doc and write to ZipOutputStream
1144
     *
1145
     * @param docid
1146
     * @param zout
1147
     * @param user
1148
     * @param groups
1149
     * @throws ClassNotFoundException
1150
     * @throws IOException
1151
     * @throws SQLException
1152
     * @throws McdbException
1153
     * @throws Exception
1154
     */
1155
    private void addDocToZip(HttpServletRequest request, String docid, String providedFileName,
1156
            ZipOutputStream zout, String user, String[] groups) throws
1157
            ClassNotFoundException, IOException, SQLException, McdbException,
1158
            Exception {
1159
        byte[] bytestring = null;
1160
        ZipEntry zentry = null;
1161
        
1162
        try {
1163
            URL url = new URL(docid);
1164
            
1165
            // this http url; read from URLConnection; add to zip
1166
            //use provided file name if we have one
1167
            if (providedFileName != null && providedFileName.length() > 1) {
1168
                zentry = new ZipEntry(providedFileName);
1169
            }
1170
            else {
1171
                zentry = new ZipEntry(docid);
1172
            }
1173
            zout.putNextEntry(zentry);
1174
            BufferedInputStream bis = null;
1175
            try {
1176
                bis = new BufferedInputStream(url.openStream());
1177
                byte[] buf = new byte[4 * 1024]; // 4K buffer
1178
                int b = bis.read(buf);
1179
                while (b != -1) {
1180
                    zout.write(buf, 0, b);
1181
                    b = bis.read(buf);
1182
                }
1183
            } finally {
1184
                if (bis != null) bis.close();
1185
            }
1186
            zout.closeEntry();
1187
            
1188
        } catch (MalformedURLException mue) {
1189
            
1190
            // this is metacat doc (data file or metadata doc)
1191
            try {
1192
                DocumentImpl doc = new DocumentImpl(docid);
1193
                
1194
                //check the permission for read
1195
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1196
                    Exception e = new Exception("User " + user
1197
                            + " does not have "
1198
                            + "permission to read the document with the docid "
1199
                            + docid);
1200
                    throw e;
1201
                }
1202
                
1203
                if (doc.getRootNodeID() == 0) {
1204
                    // this is data file; add file to zip
1205
                    String filepath = PropertyService.getProperty("application.datafilepath");
1206
                    if (!filepath.endsWith("/")) {
1207
                        filepath += "/";
1208
                    }
1209
                    String filename = filepath + docid;
1210
                    FileInputStream fin = null;
1211
                    fin = new FileInputStream(filename);
1212
                    try {
1213
                        //use provided file name if we have one
1214
                        if (providedFileName != null && providedFileName.length() > 1) {
1215
                            zentry = new ZipEntry(providedFileName);
1216
                        }
1217
                        else {
1218
                            zentry = new ZipEntry(docid);
1219
                        }
1220
                        zout.putNextEntry(zentry);
1221
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
1222
                        int b = fin.read(buf);
1223
                        while (b != -1) {
1224
                            zout.write(buf, 0, b);
1225
                            b = fin.read(buf);
1226
                        }
1227
                    } finally {
1228
                        if (fin != null) fin.close();
1229
                    }
1230
                    zout.closeEntry();
1231
                    
1232
                } else {
1233
                    // this is metadata doc; add doc to zip
1234
                    bytestring = doc.toString().getBytes();
1235
                    //use provided file name if given
1236
                    if (providedFileName != null && providedFileName.length() > 1) {
1237
                        zentry = new ZipEntry(providedFileName);
1238
                    }
1239
                    else {
1240
                        zentry = new ZipEntry(docid + ".xml");
1241
                    }
1242
                    zentry.setSize(bytestring.length);
1243
                    zout.putNextEntry(zentry);
1244
                    zout.write(bytestring, 0, bytestring.length);
1245
                    zout.closeEntry();
1246
                }
1247
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1248
                        docid, "read");
1249
            } catch (Exception except) {
1250
                throw except;
1251
            }
1252
        }
1253
    }
1254
    
1255
    /**
1256
     * If metacat couldn't find a data file or document locally, it will read
1257
     * this docid from its home server. This is for the replication feature
1258
     */
1259
    private void readFromRemoteMetaCat(HttpServletResponse response,
1260
            String docid, String rev, String user, String password,
1261
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
1262
            throws Exception {
1263
        // Create a object of RemoteDocument, "" is for zipEntryPath
1264
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
1265
                password, "");
1266
        String docType = remoteDoc.getDocType();
1267
        // Only read data file
1268
        if (docType.equals("BIN")) {
1269
            // If it is zip format
1270
            if (zip) {
1271
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
1272
            } else {
1273
                if (out == null) {
1274
                    out = response.getOutputStream();
1275
                }
1276
                response.setContentType("application/octet-stream");
1277
                remoteDoc.readDocumentFromRemoteServer(out);
1278
            }
1279
        } else {
1280
            throw new Exception("Docid: " + docid + "." + rev
1281
                    + " couldn't find");
1282
        }
1283
    }
1284
    
1285
    /**
1286
     * Handle the database putdocument request and write an XML document to the
1287
     * database connection
1288
     */
1289
    public void handleInsertOrUpdateAction(String ipAddress,
1290
            HttpServletResponse response, PrintWriter out, Hashtable<String, String[]> params,
1291
            String user, String[] groups) {
1292
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1293
        DBConnection dbConn = null;
1294
        int serialNumber = -1;
1295
        String output = "";
1296
        String qformat = null;
1297
        if(params.containsKey("qformat"))
1298
        {
1299
          qformat = params.get("qformat")[0];
1300
        }
1301
        
1302
        if(params.get("docid") == null){
1303
            out.println("<?xml version=\"1.0\"?>");
1304
            out.println("<error>");
1305
            out.println("Docid not specified");
1306
            out.println("</error>");
1307
            logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - Docid not specified");
1308
            return;
1309
        }
1310
        
1311
        try {
1312
            if (!AuthUtil.canInsertOrUpdate(user, groups)) {
1313
                out.println("<?xml version=\"1.0\"?>");
1314
                out.println("<error>");
1315
                out.println("User '" + user + "' not allowed to insert and update");
1316
                out.println("</error>");
1317
                logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - User '" + user + "' not allowed to insert and update");
1318
                return;
1319
            }
1320
        } catch (MetacatUtilException ue) {
1321
            logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - Could not determine if user could insert or update: "
1322
                    + ue.getMessage());
1323
            ue.printStackTrace(System.out);
1324
            // TODO: This is a bug, as it allows one to bypass the access check -- need to throw an exception
1325
        }
1326
        
1327
        try {
1328
            // Get the document indicated
1329
            logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - params: " + params.toString());
1330
            
1331
            String[] doctext = params.get("doctext");
1332
            String pub = null;
1333
            if (params.containsKey("public")) {
1334
                pub = params.get("public")[0];
1335
            }
1336
            
1337
            StringReader dtd = null;
1338
            if (params.containsKey("dtdtext")) {
1339
                String[] dtdtext = params.get("dtdtext");
1340
                try {
1341
                    if (!dtdtext[0].equals("")) {
1342
                        dtd = new StringReader(dtdtext[0]);
1343
                    }
1344
                } catch (NullPointerException npe) {
1345
                }
1346
            }
1347
            
1348
            if(doctext == null){
1349
                out.println("<?xml version=\"1.0\"?>");
1350
                out.println("<error>");
1351
                out.println("Document text not submitted");
1352
                out.println("</error>");
1353
                // TODO: this should really throw an exception
1354
                return;
1355
            }
1356
            
1357
            logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - the xml document in metacat servlet (before parsing):\n" + doctext[0]);
1358
            StringReader xmlReader = new StringReader(doctext[0]);
1359
            boolean validate = false;
1360
            DocumentImplWrapper documentWrapper = null;
1361
            try {
1362
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1363
                // >
1364
                // in order to decide whether to use validation parser
1365
                validate = needDTDValidation(xmlReader);
1366
                if (validate) {
1367
                    // set a dtd base validation parser
1368
                    String rule = DocumentImpl.DTD;
1369
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1370
                } else {
1371
                    
1372
                    String namespace = XMLSchemaService.findDocumentNamespace(xmlReader);
1373
                    
1374
                    if (namespace != null) {
1375
                        if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1376
                                || namespace.compareTo(
1377
                                DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1378
                            // set eml2 base     validation parser
1379
                            String rule = DocumentImpl.EML200;
1380
                            // using emlparser to check id validation
1381
                            @SuppressWarnings("unused")
1382
                            EMLParser parser = new EMLParser(doctext[0]);
1383
                            documentWrapper = new DocumentImplWrapper(rule, true);
1384
                        } else if (namespace.compareTo(
1385
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1386
                            // set eml2 base validation parser
1387
                            String rule = DocumentImpl.EML210;
1388
                            // using emlparser to check id validation
1389
                            @SuppressWarnings("unused")
1390
                            EMLParser parser = new EMLParser(doctext[0]);
1391
                            documentWrapper = new DocumentImplWrapper(rule, true);
1392
                        } else {
1393
                            // set schema base validation parser
1394
                            String rule = DocumentImpl.SCHEMA;
1395
                            documentWrapper = new DocumentImplWrapper(rule, true);
1396
                        }
1397
                    } else {
1398
                        documentWrapper = new DocumentImplWrapper("", false);
1399
                    }
1400
                }
1401
                
1402
                String[] action = params.get("action");
1403
                String[] docid = params.get("docid");
1404
                String newdocid = null;
1405
                
1406
                String doAction = null;
1407
                if (action[0].equals("insert") || action[0].equals("insertmultipart")) {
1408
                    doAction = "INSERT";
1409
                } else if (action[0].equals("update")) {
1410
                    doAction = "UPDATE";
1411
                }
1412
                
1413
                try {
1414
                    // get a connection from the pool
1415
                    dbConn = DBConnectionPool
1416
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1417
                    serialNumber = dbConn.getCheckOutSerialNumber();
1418
                    
1419
                    // write the document to the database and disk
1420
                    String accNumber = docid[0];
1421
                    logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - " + doAction + " "
1422
                            + accNumber + "...");
1423
                    if (accNumber == null || accNumber.equals("")) {
1424
                        logMetacat.warn("MetaCatServlet.handleInsertOrUpdateAction - writing with null acnumber");
1425
                        newdocid = documentWrapper.write(dbConn, doctext[0], pub, dtd,
1426
                                doAction, null, user, groups);
1427
                        EventLog.getInstance().log(ipAddress, user, "", action[0]);
1428
                    } else {
1429
                        newdocid = documentWrapper.write(dbConn, doctext[0], pub, dtd,
1430
                                doAction, accNumber, user, groups);
1431

    
1432
                        EventLog.getInstance().log(ipAddress, user, accNumber, action[0]);
1433
                    }
1434
                } finally {
1435
                    // Return db connection
1436
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1437
                }
1438
                
1439
                // set content type and other response header fields first
1440
                //response.setContentType("text/xml");
1441
                output += "<?xml version=\"1.0\"?>";
1442
                output += "<success>";
1443
                output += "<docid>" + newdocid + "</docid>";
1444
                output += "</success>";
1445
                
1446
            } catch (NullPointerException npe) {
1447
                //response.setContentType("text/xml");
1448
                output += "<?xml version=\"1.0\"?>";
1449
                output += "<error>";
1450
                output += npe.getMessage();
1451
                output += "</error>";
1452
                logMetacat.warn("MetaCatServlet.handleInsertOrUpdateAction - Null pointer error when writing eml document to the database: " + npe.getMessage());
1453
                npe.printStackTrace();
1454
            }
1455
        } catch (Exception e) {
1456
            //response.setContentType("text/xml");
1457
            output += "<?xml version=\"1.0\"?>";
1458
            output += "<error>";
1459
            output += e.getMessage();
1460
            output += "</error>";
1461
            logMetacat.warn("MetaCatServlet.handleInsertOrUpdateAction - General error when writing eml document to the database: " + e.getMessage());
1462
            e.printStackTrace();
1463
        }
1464
        
1465
        if (qformat == null || qformat.equals("xml")) {
1466
            response.setContentType("text/xml");
1467
            out.println(output);
1468
        } else {
1469
            try {
1470
                DBTransform trans = new DBTransform();
1471
                response.setContentType("text/html");
1472
                trans.transformXMLDocument(output,
1473
                        "message", "-//W3C//HTML//EN", qformat,
1474
                        out, null, null);
1475
            } catch (Exception e) {
1476
                
1477
                logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - General error: "
1478
                        + e.getMessage());
1479
                e.printStackTrace(System.out);
1480
            }
1481
        }
1482
    }
1483
    
1484
    /**
1485
     * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > in
1486
     * order to decide whether to use validation parser
1487
     */
1488
    private static boolean needDTDValidation(StringReader xmlreader)
1489
    throws IOException {
1490
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1491
        StringBuffer cbuff = new StringBuffer();
1492
        java.util.Stack<String> st = new java.util.Stack<String>();
1493
        boolean validate = false;
1494
        boolean commented = false;
1495
        int c;
1496
        int inx;
1497
        
1498
        // read from the stream until find the keywords
1499
        while ((st.empty() || st.size() < 4) && ((c = xmlreader.read()) != -1)) {
1500
            cbuff.append((char) c);
1501
            
1502
            if ((inx = cbuff.toString().indexOf("<!--")) != -1) {
1503
                commented = true;
1504
            }
1505
            
1506
            // "<!DOCTYPE" keyword is found; put it in the stack
1507
            if ((inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1) {
1508
                cbuff = new StringBuffer();
1509
                st.push("<!DOCTYPE");
1510
            }
1511
            // "PUBLIC" keyword is found; put it in the stack
1512
            if ((inx = cbuff.toString().indexOf("PUBLIC")) != -1) {
1513
                cbuff = new StringBuffer();
1514
                st.push("PUBLIC");
1515
            }
1516
            // "SYSTEM" keyword is found; put it in the stack
1517
            if ((inx = cbuff.toString().indexOf("SYSTEM")) != -1) {
1518
                cbuff = new StringBuffer();
1519
                st.push("SYSTEM");
1520
            }
1521
            // ">" character is found; put it in the stack
1522
            // ">" is found twice: fisrt from <?xml ...?>
1523
            // and second from <!DOCTYPE ... >
1524
            if ((inx = cbuff.toString().indexOf(">")) != -1) {
1525
                cbuff = new StringBuffer();
1526
                st.push(">");
1527
            }
1528
        }
1529
        
1530
        // close the stream
1531
        xmlreader.reset();
1532
        
1533
        // check the stack whether it contains the keywords:
1534
        // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1535
        if (st.size() == 4) {
1536
            if ((st.pop()).equals(">")
1537
            && ((st.peek()).equals("PUBLIC") | (st.pop()).equals("SYSTEM"))
1538
                    && (st.pop()).equals("<!DOCTYPE")) {
1539
                validate = true && !commented;
1540
            }
1541
        }
1542
        
1543
        logMetacat.info("MetaCatServlet.needDTDValidation - Validation for dtd is " + validate);
1544
        return validate;
1545
    }
1546
    
1547
    // END OF INSERT/UPDATE SECTION
1548
    
1549
    /**
1550
     * Handle the database delete request and delete an XML document from the
1551
     * database connection
1552
     */
1553
    public void handleDeleteAction(PrintWriter out, Hashtable<String, String[]> params,
1554
            HttpServletRequest request, HttpServletResponse response,
1555
            String user, String[] groups) {
1556
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1557
        String[] docid = params.get("docid");
1558
        
1559
        if(docid == null){
1560
            response.setContentType("text/xml");
1561
            out.println("<?xml version=\"1.0\"?>");
1562
            out.println("<error>");
1563
            out.println("Docid not specified.");
1564
            out.println("</error>");
1565
            logMetacat.error("MetaCatServlet.handleDeleteAction - Docid not specified for the document to be deleted.");
1566
        } else {
1567
            
1568
            // delete the document from the database
1569
            try {
1570
                
1571
                try {
1572
                    // null means notify server is null
1573
                    DocumentImpl.delete(docid[0], user, groups, null);
1574
                    EventLog.getInstance().log(request.getRemoteAddr(),
1575
                            user, docid[0], "delete");
1576
                    response.setContentType("text/xml");
1577
                    out.println("<?xml version=\"1.0\"?>");
1578
                    out.println("<success>");
1579
                    out.println("Document deleted.");
1580
                    out.println("</success>");
1581
                    logMetacat.info("MetaCatServlet.handleDeleteAction - Document deleted.");
1582
                    
1583
                    // Delete from spatial cache if runningSpatialOption
1584
                    if ( PropertyService.getProperty("spatial.runSpatialOption").equals("true") ) {
1585
                        SpatialHarvester sh = new SpatialHarvester();
1586
                        sh.addToDeleteQue( DocumentUtil.getSmartDocId( docid[0] ) );
1587
                        sh.destroy();
1588
                    }
1589
                    
1590
                } catch (AccessionNumberException ane) {
1591
                    response.setContentType("text/xml");
1592
                    out.println("<?xml version=\"1.0\"?>");
1593
                    out.println("<error>");
1594
                    //out.println("Error deleting document!!!");
1595
                    out.println(ane.getMessage());
1596
                    out.println("</error>");
1597
                    logMetacat.error("MetaCatServlet.handleDeleteAction - Document could not be deleted: "
1598
                            + ane.getMessage());
1599
                    ane.printStackTrace(System.out);
1600
                }
1601
            } catch (Exception e) {
1602
                response.setContentType("text/xml");
1603
                out.println("<?xml version=\"1.0\"?>");
1604
                out.println("<error>");
1605
                out.println(e.getMessage());
1606
                out.println("</error>");
1607
                logMetacat.error("MetaCatServlet.handleDeleteAction - Document could not be deleted: "
1608
                        + e.getMessage());
1609
                e.printStackTrace(System.out);
1610
            }
1611
        }
1612
    }
1613
    
1614
    /**
1615
     * Handle the validation request and return the results to the requestor
1616
     */
1617
    protected void handleValidateAction(PrintWriter out, Hashtable<String, String[]> params) {
1618
        
1619
        // Get the document indicated
1620
        String valtext = null;
1621
        DBConnection dbConn = null;
1622
        int serialNumber = -1;
1623
        
1624
        try {
1625
            valtext = params.get("valtext")[0];
1626
        } catch (Exception nullpe) {
1627
            
1628
            String docid = null;
1629
            try {
1630
                // Find the document id number
1631
                docid = params.get("docid")[0];
1632
                
1633
                // Get the document indicated from the db
1634
                DocumentImpl xmldoc = new DocumentImpl(docid);
1635
                valtext = xmldoc.toString();
1636
                
1637
            } catch (NullPointerException npe) {
1638
                
1639
                out.println("<error>Error getting document ID: " + docid
1640
                        + "</error>");
1641
                //if ( conn != null ) { util.returnConnection(conn); }
1642
                return;
1643
            } catch (Exception e) {
1644
                
1645
                out.println(e.getMessage());
1646
            }
1647
        }
1648
        
1649
        try {
1650
            // get a connection from the pool
1651
            dbConn = DBConnectionPool
1652
                    .getDBConnection("MetaCatServlet.handleValidateAction");
1653
            serialNumber = dbConn.getCheckOutSerialNumber();
1654
            DBValidate valobj = new DBValidate(dbConn);
1655
//            boolean valid = valobj.validateString(valtext);
1656
            
1657
            // set content type and other response header fields first
1658
            
1659
            out.println(valobj.returnErrors());
1660
            
1661
        } catch (NullPointerException npe2) {
1662
            // set content type and other response header fields first
1663
            
1664
            out.println("<error>Error validating document.</error>");
1665
        } catch (Exception e) {
1666
            
1667
            out.println(e.getMessage());
1668
        } finally {
1669
            // Return db connection
1670
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1671
        }
1672
    }
1673
    
1674
    /**
1675
     * Handle "getrevsionanddoctype" action Given a docid, return it's current
1676
     * revision and doctype from data base The output is String look like
1677
     * "rev;doctype"
1678
     */
1679
    protected void handleGetRevisionAndDocTypeAction(PrintWriter out,
1680
            Hashtable<String, String[]> params) {
1681
        // To store doc parameter
1682
        String[] docs = new String[10];
1683
        // Store a single doc id
1684
        String givenDocId = null;
1685
        // Get docid from parameters
1686
        if (params.containsKey("docid")) {
1687
            docs = params.get("docid");
1688
        }
1689
        // Get first docid form string array
1690
        givenDocId = docs[0];
1691
        
1692
        try {
1693
            // Make sure there is a docid
1694
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
1695
                    "User didn't specify docid!"); }//if
1696
            
1697
            // Create a DBUtil object
1698
            DBUtil dbutil = new DBUtil();
1699
            // Get a rev and doctype
1700
            String revAndDocType = dbutil
1701
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1702
            out.println(revAndDocType);
1703
            
1704
        } catch (Exception e) {
1705
            // Handle exception
1706
            out.println("<?xml version=\"1.0\"?>");
1707
            out.println("<error>");
1708
            out.println(e.getMessage());
1709
            out.println("</error>");
1710
        }
1711
        
1712
    }
1713
    
1714
    /**
1715
     * Handle "getaccesscontrol" action. Read Access Control List from db
1716
     * connection in XML format
1717
     */
1718
    protected void handleGetAccessControlAction(PrintWriter out,
1719
            Hashtable<String,String[]> params, HttpServletResponse response, String username,
1720
            String[] groupnames) {
1721
        
1722
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1723

    
1724
        String docid = params.get("docid")[0];
1725
        if (docid.startsWith("urn:")) {
1726
            try {
1727
                String actualDocId = LSIDUtil.getDocId(docid, false);
1728
                docid = actualDocId;
1729
            } catch (ParseLSIDException ple) {
1730
                logMetacat.error("MetaCatServlet.handleGetAccessControlAction - MetaCatServlet.handleGetAccessControlAction - " +
1731
                        "could not parse lsid: " + docid + " : " + ple.getMessage());  
1732
                ple.printStackTrace(System.out);
1733
            }
1734
        }
1735
        
1736
        String qformat = "xml";
1737
        if (params.get("qformat") != null) {
1738
            qformat = (params.get("qformat"))[0];
1739
        }
1740
        
1741
        try {
1742
            AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
1743
            String acltext = acfsf.getACL(username, groupnames);
1744
            if (qformat.equals("xml")) {
1745
                response.setContentType("text/xml");
1746
                out.println(acltext);
1747
            } else {
1748
                DBTransform trans = new DBTransform();
1749
                response.setContentType("text/html");
1750
                trans.transformXMLDocument(acltext,"-//NCEAS//getaccesscontrol//EN", 
1751
                    "-//W3C//HTML//EN", qformat, out, params, null);              
1752
            }            
1753
        } catch (Exception e) {
1754
            out.println("<?xml version=\"1.0\"?>");
1755
            out.println("<error>");
1756
            out.println(e.getMessage());
1757
            out.println("</error>");
1758
        } 
1759
//        finally {
1760
//            // Retrun db connection to pool
1761
//            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1762
//        }
1763
    }
1764
    
1765
    /**
1766
     * Handle the "getprincipals" action. Read all principals from
1767
     * authentication scheme in XML format
1768
     */
1769
    protected void handleGetPrincipalsAction(PrintWriter out, String user,
1770
            String password) {
1771
        try {
1772
            AuthSession auth = new AuthSession();
1773
            String principals = auth.getPrincipals(user, password);
1774
            out.println(principals);
1775
            
1776
        } catch (Exception e) {
1777
            out.println("<?xml version=\"1.0\"?>");
1778
            out.println("<error>");
1779
            out.println(e.getMessage());
1780
            out.println("</error>");
1781
        }
1782
    }
1783
    
1784
    /**
1785
     * Handle "getdoctypes" action. Read all doctypes from db connection in XML
1786
     * format
1787
     */
1788
    protected void handleGetDoctypesAction(PrintWriter out, Hashtable<String, String[]> params,
1789
            HttpServletResponse response) {
1790
        try {
1791
            DBUtil dbutil = new DBUtil();
1792
            String doctypes = dbutil.readDoctypes();
1793
            out.println(doctypes);
1794
        } catch (Exception e) {
1795
            out.println("<?xml version=\"1.0\"?>");
1796
            out.println("<error>");
1797
            out.println(e.getMessage());
1798
            out.println("</error>");
1799
        }
1800
    }
1801
    
1802
    /**
1803
     * Handle the "getdtdschema" action. Read DTD or Schema file for a given
1804
     * doctype from Metacat catalog system
1805
     */
1806
    protected void handleGetDTDSchemaAction(PrintWriter out, Hashtable<String, String[]> params,
1807
            HttpServletResponse response) {
1808
        
1809
        String doctype = null;
1810
        String[] doctypeArr = params.get("doctype");
1811
        
1812
        // get only the first doctype specified in the list of doctypes
1813
        // it could be done for all doctypes in that list
1814
        if (doctypeArr != null) {
1815
            doctype = params.get("doctype")[0];
1816
        }
1817
        
1818
        try {
1819
            DBUtil dbutil = new DBUtil();
1820
            String dtdschema = dbutil.readDTDSchema(doctype);
1821
            out.println(dtdschema);
1822
            
1823
        } catch (Exception e) {
1824
            out.println("<?xml version=\"1.0\"?>");
1825
            out.println("<error>");
1826
            out.println(e.getMessage());
1827
            out.println("</error>");
1828
        }
1829
        
1830
    }
1831
    
1832
    /**
1833
     * Check if the document is registered in either the xml_documents or xml_revisions table
1834
     * @param out the writer to write the xml results to
1835
     * @param params request parameters
1836
     * @param response the http servlet response
1837
     */
1838
    public void handleIdIsRegisteredAction(PrintWriter out, Hashtable<String, String[]> params,
1839
            HttpServletResponse response) {
1840
        String id = null;
1841
        boolean exists = false;
1842
        if(params.get("docid") != null) {
1843
            id = params.get("docid")[0];
1844
        }
1845
        
1846
        try {
1847
            DBUtil dbutil = new DBUtil();
1848
            exists = dbutil.idExists(id);
1849
        } catch (Exception e) {
1850
            out.println("<?xml version=\"1.0\"?>");
1851
            out.println("<error>");
1852
            out.println(e.getMessage());
1853
            out.println("</error>");
1854
        }
1855
        
1856
        out.println("<?xml version=\"1.0\"?>");
1857
        out.println("<isRegistered>");
1858
        out.println("<docid>" + id + "</docid>");
1859
        out.println("<exists>" + exists + "</exists>");
1860
        out.println("</isRegistered>");
1861
    }
1862
    
1863
    /**
1864
     * Handle the "getalldocids" action. return a list of all docids registered
1865
     * in the system
1866
     */
1867
    public void handleGetAllDocidsAction(PrintWriter out, Hashtable<String, String[]> params,
1868
            HttpServletResponse response) {
1869
        String scope = null;
1870
        if(params.get("scope") != null) {
1871
            scope = params.get("scope")[0];
1872
        }
1873
        
1874
        try {
1875
            DBUtil dbutil = new DBUtil();
1876
            Vector<String> docids = dbutil.getAllDocids(scope);
1877
            out.println("<?xml version=\"1.0\"?>");
1878
            out.println("<idList>");
1879
            out.println("  <scope>" + scope + "</scope>");
1880
            for(int i=0; i<docids.size(); i++) {
1881
                String docid = docids.elementAt(i);
1882
                out.println("  <docid>" + docid + "</docid>");
1883
            }
1884
            out.println("</idList>");
1885
            
1886
        } catch (Exception e) {
1887
            out.println("<?xml version=\"1.0\"?>");
1888
            out.println("<error>");
1889
            out.println(e.getMessage());
1890
            out.println("</error>");
1891
        }
1892
    }
1893
    
1894
    /**
1895
     * Handle the "getlastdocid" action. Get the latest docid with rev number
1896
     * from db connection in XML format
1897
     */
1898
    public void handleGetMaxDocidAction(PrintWriter out, Hashtable<String, String[]> params,
1899
            HttpServletResponse response) {
1900
        
1901
        String scope = params.get("scope")[0];
1902
        if (scope == null) {
1903
            scope = params.get("username")[0];
1904
        }
1905
        
1906
        try {
1907
            
1908
            DBUtil dbutil = new DBUtil();
1909
            String lastDocid = dbutil.getMaxDocid(scope);
1910
            out.println("<?xml version=\"1.0\"?>");
1911
            out.println("<lastDocid>");
1912
            out.println("  <scope>" + scope + "</scope>");
1913
            out.println("  <docid>" + lastDocid + "</docid>");
1914
            out.println("</lastDocid>");
1915
            
1916
        } catch (Exception e) {
1917
            out.println("<?xml version=\"1.0\"?>");
1918
            out.println("<error>");
1919
            out.println(e.getMessage());
1920
            out.println("</error>");
1921
        }
1922
    }
1923
    
1924
    /**
1925
     * Print a report from the event log based on filter parameters passed in
1926
     * from the web.
1927
     *
1928
     * @param params the parameters from the web request
1929
     * @param request the http request object for getting request details
1930
     * @param response the http response object for writing output
1931
     */
1932
    protected void handleGetLogAction(Hashtable<String, String[]> params, HttpServletRequest request,
1933
            HttpServletResponse response, String username, String[] groups) {
1934
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1935
        try {
1936
            response.setContentType("text/xml");
1937
            PrintWriter out = response.getWriter();
1938
            
1939
            // Check that the user is authenticated as an administrator account
1940
            if (!AuthUtil.isAdministrator(username, groups)) {
1941
                out.print("<error>");
1942
                out.print("The user \"" + username +
1943
                        "\" is not authorized for this action.");
1944
                out.print("</error>");
1945
                return;
1946
            }
1947
            
1948
            // Get all of the parameters in the correct formats
1949
            String[] ipAddress = params.get("ipaddress");
1950
            String[] principal = params.get("principal");
1951
            String[] docid = params.get("docid");
1952
            String[] event = params.get("event");
1953
            String[] startArray = params.get("start");
1954
            String[] endArray = params.get("end");
1955
            String start = null;
1956
            String end = null;
1957
            if (startArray != null) {
1958
                start = startArray[0];
1959
            }
1960
            if (endArray != null) {
1961
                end = endArray[0];
1962
            }
1963
            Timestamp startDate = null;
1964
            Timestamp endDate = null;
1965
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1966
            try {
1967
                if (start != null) {
1968
                    startDate = new Timestamp((format.parse(start)).getTime());
1969
                }
1970
                if (end != null) {
1971
                    endDate = new Timestamp((format.parse(end)).getTime());
1972
                }
1973
            } catch (ParseException e) {
1974
                logMetacat.error("MetaCatServlet.handleGetLogAction - Failed to created Timestamp from input.");
1975
                e.printStackTrace(System.out);
1976
            }
1977
            
1978
            // Request the report by passing the filter parameters
1979
            out.println(EventLog.getInstance().getReport(ipAddress, principal,
1980
                    docid, event, startDate, endDate));
1981
            out.close();
1982
        } catch (IOException e) {
1983
            logMetacat.error("MetaCatServlet.handleGetLogAction - Could not open http response for writing: "
1984
                    + e.getMessage());
1985
            e.printStackTrace(System.out);
1986
        } catch (MetacatUtilException ue) {
1987
            logMetacat.error("MetaCatServlet.handleGetLogAction - Could not determine if user is administrator: "
1988
                    + ue.getMessage());
1989
            ue.printStackTrace(System.out);
1990
        }
1991
    }
1992
    
1993
    /**
1994
     * Rebuild the index for one or more documents. If the docid parameter is
1995
     * provided, rebuild for just that one document or list of documents. If
1996
     * not, then rebuild the index for all documents in the xml_documents table.
1997
     * 
1998
     * @param params
1999
     *            the parameters from the web request
2000
     * @param request
2001
     *            the http request object for getting request details
2002
     * @param response
2003
     *            the http response object for writing output
2004
     * @param username
2005
     *            the username of the authenticated user
2006
     */
2007
    protected void handleBuildIndexAction(Hashtable<String, String[]> params,
2008
            HttpServletRequest request, HttpServletResponse response,
2009
            String username, String[] groups) {
2010
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2011
        
2012
        // Get all of the parameters in the correct formats
2013
        String[] docid = params.get("docid");
2014
        
2015
        // Rebuild the indices for appropriate documents
2016
        try {
2017
            response.setContentType("text/xml");
2018
            PrintWriter out = response.getWriter();
2019
            
2020
            // Check that the user is authenticated as an administrator account
2021
            if (!AuthUtil.isAdministrator(username, groups)) {
2022
                out.print("<error>");
2023
                out.print("The user \"" + username +
2024
                        "\" is not authorized for this action.");
2025
                out.print("</error>");
2026
                return;
2027
            }
2028
            
2029
            // Process the documents
2030
            out.println("<success>");
2031
            if (docid == null || docid.length == 0) {
2032
                // Process all of the documents
2033
                try {
2034
                    Vector<String> documents = getDocumentList();
2035
                    Iterator<String> it = documents.iterator();
2036
                    while (it.hasNext()) {
2037
                        String id = it.next();
2038
                        buildDocumentIndex(id, out);
2039
                    }
2040
                } catch (SQLException se) {
2041
                    out.print("<error>");
2042
                    out.print(se.getMessage());
2043
                    out.println("</error>");
2044
                }
2045
            } else {
2046
                // Only process the requested documents
2047
                for (int i = 0; i < docid.length; i++) {
2048
                    buildDocumentIndex(docid[i], out);
2049
                }
2050
            }
2051
            out.println("</success>");
2052
            out.close();
2053
        } catch (IOException e) {
2054
            logMetacat.error("MetaCatServlet.handleBuildIndexAction - Could not open http response for writing: "
2055
                    + e.getMessage());
2056
            e.printStackTrace(System.out);
2057
        } catch (MetacatUtilException ue) {
2058
            logMetacat.error("MetaCatServlet.handleBuildIndexAction - Could not determine if user is administrator: "
2059
                    + ue.getMessage());
2060
            ue.printStackTrace(System.out);
2061
        }
2062
    }
2063
    
2064
    /**
2065
     * Build the index for one document by reading the document and
2066
     * calling its buildIndex() method.
2067
     *
2068
     * @param docid the document (with revision) to rebuild
2069
     * @param out the PrintWriter to which output is printed
2070
     */
2071
    private void buildDocumentIndex(String docid, PrintWriter out) {
2072
        try {
2073
            DocumentImpl doc = new DocumentImpl(docid, false);
2074
            doc.buildIndex();
2075
            out.print("<docid>" + docid);
2076
            out.println("</docid>");
2077
        } catch (McdbException me) {
2078
            out.print("<error>");
2079
            out.print(me.getMessage());
2080
            out.println("</error>");
2081
        }
2082
    }
2083
    
2084
    /**
2085
     * Handle documents passed to metacat that are encoded using the
2086
     * "multipart/form-data" mime type. This is typically used for uploading
2087
     * data files which may be binary and large.
2088
     */
2089
    protected void handleMultipartForm(HttpServletRequest request,
2090
            HttpServletResponse response) {
2091
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2092
        PrintWriter out = null;
2093
        String action = null;
2094
        
2095
        // Parse the multipart form, and save the parameters in a Hashtable and
2096
        // save the FileParts in a hashtable
2097
        
2098
        Hashtable<String,String[]> params = new Hashtable<String,String[]>();
2099
        Hashtable<String,String> fileList = new Hashtable<String,String>();
2100
        int sizeLimit = 1000;
2101
        try {
2102
            sizeLimit = 
2103
                (new Integer(PropertyService.getProperty("replication.datafilesizelimit"))).intValue();
2104
        } catch (PropertyNotFoundException pnfe) {
2105
            logMetacat.error("MetaCatServlet.handleMultipartForm - Could not determine data file size limit.  Using 1000. " 
2106
                    + pnfe.getMessage());
2107
            pnfe.printStackTrace(System.out);
2108
        }
2109
        logMetacat.debug("MetaCatServlet.handleMultipartForm - The size limit of uploaded data files is: " + sizeLimit);
2110
        
2111
        try {
2112
            MultipartParser mp = new MultipartParser(request,
2113
                    sizeLimit * 1024 * 1024);
2114
            Part part;
2115
            
2116
            while ((part = mp.readNextPart()) != null) {
2117
                String name = part.getName();
2118
                
2119
                if (part.isParam()) {
2120
                    // it's a parameter part
2121
                    ParamPart paramPart = (ParamPart) part;
2122
                    String[] values = new String[1];
2123
                    values[0] = paramPart.getStringValue();
2124
                    params.put(name, values);
2125
                    if (name.equals("action")) {
2126
                        action = values[0];
2127
                    }
2128
                } else if (part.isFile()) {
2129
                    // it's a file part
2130
                    FilePart filePart = (FilePart) part;
2131
                    String fileName = filePart.getFileName();
2132
                    String fileTempLocation;
2133
                    
2134
                    // the filePart will be clobbered on the next loop, save to disk
2135
                    fileTempLocation = MetacatUtil.writeTempUploadFile(filePart, fileName);
2136
                    fileList.put(name, fileTempLocation);
2137
                    fileList.put("filename", fileName);
2138
                    fileList.put("name", fileTempLocation);
2139
                } else {
2140
                    logMetacat.info("MetaCatServlet.handleMultipartForm - Upload name '" + name + "' was empty.");
2141
                }
2142
            }
2143
        } catch (IOException ioe) {
2144
            try {
2145
                out = response.getWriter();
2146
            } catch (IOException ioe2) {
2147
                logMetacat.fatal("MetaCatServlet.handleMultipartForm - Fatal Error: couldn't get response output stream.");
2148
            }
2149
            out.println("<?xml version=\"1.0\"?>");
2150
            out.println("<error>");
2151
            out.println("Error: problem reading multipart data: " + ioe.getMessage());
2152
            out.println("</error>");
2153
            out.close();
2154
            return;
2155
        }
2156
        
2157
        // Get the session information
2158
        String username = null;
2159
        String password = null;
2160
        String[] groupnames = null;
2161
        String sess_id = null;
2162
        
2163
        // be aware of session expiration on every request
2164
        HttpSession sess = request.getSession(true);
2165
        if (sess.isNew()) {
2166
            // session expired or has not been stored b/w user requests
2167
            username = "public";
2168
            sess.setAttribute("username", username);
2169
        } else {
2170
            username = (String) sess.getAttribute("username");
2171
            password = (String) sess.getAttribute("password");
2172
            groupnames = (String[]) sess.getAttribute("groupnames");
2173
            try {
2174
                sess_id = (String) sess.getId();
2175
            } catch (IllegalStateException ise) {
2176
                System.out
2177
                        .println("error in  handleMultipartForm: this shouldn't "
2178
                        + "happen: the session should be valid: "
2179
                        + ise.getMessage());
2180
            }
2181
        }
2182
        
2183
        // Get the out stream
2184
        try {
2185
            out = response.getWriter();
2186
        } catch (IOException ioe2) {
2187
            logMetacat.error("MetaCatServlet.handleMultipartForm - Fatal Error: couldn't get response "
2188
                    + "output stream.");
2189
            ioe2.printStackTrace(System.out);
2190
        }
2191
        
2192
        if (action.equals("upload")) {
2193
            if (username != null && !username.equals("public")) {
2194
                handleUploadAction(request, out, params, fileList, username,
2195
                        groupnames, response);
2196
            } else {                
2197
                out.println("<?xml version=\"1.0\"?>");
2198
                out.println("<error>");
2199
                out.println("Permission denied for " + action);
2200
                out.println("</error>");
2201
            }
2202
        } else if(action.equals("insertmultipart")) {
2203
          if (username != null && !username.equals("public")) {
2204
            logMetacat.debug("MetaCatServlet.handleMultipartForm - handling multipart insert");
2205
              handleInsertMultipartAction(request, response,
2206
                            out, params, fileList, username, groupnames);
2207
          } else {
2208
              out.println("<?xml version=\"1.0\"?>");
2209
              out.println("<error>");
2210
              out.println("Permission denied for " + action);
2211
              out.println("</error>");
2212
          }
2213
        } else {
2214
            /*
2215
             * try { out = response.getWriter(); } catch (IOException ioe2) {
2216
             * System.err.println("Fatal Error: couldn't get response output
2217
             * stream.");
2218
             */
2219
            out.println("<?xml version=\"1.0\"?>");
2220
            out.println("<error>");
2221
            out.println("Error: action not registered.  Please report this error.");
2222
            out.println("</error>");
2223
        }
2224
        out.close();
2225
    }
2226
    
2227
    /**
2228
     * Handle the upload action by saving the attached file to disk and
2229
     * registering it in the Metacat db
2230
     */
2231
    private void handleInsertMultipartAction(HttpServletRequest request, 
2232
            HttpServletResponse response,
2233
            PrintWriter out, Hashtable<String,String[]> params, Hashtable<String,String> fileList,
2234
            String username, String[] groupnames)
2235
    {
2236
      Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2237
      String action = null;
2238
      String docid = null;
2239
      String qformat = null;
2240
      String output = "";
2241
      
2242
      /*
2243
       * response.setContentType("text/xml"); try { out =
2244
       * response.getWriter(); } catch (IOException ioe2) {
2245
       * System.err.println("Fatal Error: couldn't get response output
2246
       * stream.");
2247
       */
2248
      
2249
      if (params.containsKey("docid")) 
2250
      {
2251
          docid = params.get("docid")[0];
2252
      }
2253
      
2254
      if(params.containsKey("qformat")) 
2255
      {
2256
          qformat = params.get("qformat")[0];
2257
      }
2258
      
2259
      // Make sure we have a docid and datafile
2260
      if (docid != null && fileList.containsKey("datafile")) 
2261
      {
2262
        logMetacat.info("MetaCatServlet.handleInsertMultipartAction - Uploading data docid: " + docid);
2263
        // Get a reference to the file part of the form
2264
        //FilePart filePart = (FilePart) fileList.get("datafile");
2265
        String fileName = fileList.get("filename");
2266
        logMetacat.debug("MetaCatServlet.handleInsertMultipartAction - Uploading filename: " + fileName);
2267
        // Check if the right file existed in the uploaded data
2268
        if (fileName != null) 
2269
        {
2270
              
2271
          try 
2272
          {
2273
              //logMetacat.info("Upload datafile " + docid
2274
              // +"...", 10);
2275
              //If document get lock data file grant
2276
            if (DocumentImpl.getDataFileLockGrant(docid)) 
2277
            {
2278
              // Save the data file to disk using "docid" as the name
2279
              String datafilepath = PropertyService.getProperty("application.datafilepath");
2280
              File dataDirectory = new File(datafilepath);
2281
              dataDirectory.mkdirs();
2282
              File newFile = null;
2283
    //          File tempFile = null;
2284
              String tempFileName = fileList.get("name");
2285
              String newFileName = dataDirectory + File.separator + docid;
2286
              long size = 0;
2287
              boolean fileExists = false;
2288
                      
2289
              try 
2290
              {
2291
                newFile = new File(newFileName);
2292
                fileExists = newFile.exists();
2293
                logMetacat.info("MetaCatServlet.handleInsertMultipartAction - new file status is: " + fileExists);
2294
                if(fileExists)
2295
                {
2296
                  newFile.delete();
2297
                  newFile.createNewFile();
2298
                  fileExists = false;
2299
                }
2300
                
2301
                if ( fileExists == false ) 
2302
                {
2303
                    // copy file to desired output location
2304
                    try 
2305
                    {
2306
                        MetacatUtil.copyFile(tempFileName, newFileName);
2307
                    } 
2308
                    catch (IOException ioe) 
2309
                    {
2310
                        logMetacat.error("MetaCatServlet.handleInsertMultipartAction - IO Exception copying file: " +
2311
                                ioe.getMessage());
2312
                        ioe.printStackTrace(System.out);
2313
                    }
2314
                    size = newFile.length();
2315
                    if (size == 0) 
2316
                    {
2317
                        throw new IOException("MetaCatServlet.handleInsertMultipartAction - Uploaded file is 0 bytes!");
2318
                    }
2319
                }
2320
                logMetacat.info("MetaCatServlet.handleInsertMultipartAction - Uploading the following to Metacat:" +
2321
                        fileName + ", " + docid + ", " +
2322
                        username + ", " + groupnames);
2323
                FileReader fr = new FileReader(newFile);
2324
                
2325
                char[] c = new char[1024];
2326
                int numread = fr.read(c, 0, 1024);
2327
                StringBuffer sb = new StringBuffer();
2328
                while(numread != -1)
2329
                {
2330
                  sb.append(c, 0, numread);
2331
                  numread = fr.read(c, 0, 1024);
2332
                }
2333
                
2334
                Enumeration<String> keys = params.keys();
2335
                while(keys.hasMoreElements())
2336
                { //convert the params to arrays
2337
                  String key = keys.nextElement();
2338
                  String[] paramValue = params.get(key);
2339
                  String[] s = new String[1];
2340
                  s[0] = paramValue[0];
2341
                  params.put(key, s);
2342
                }
2343
                //add the doctext to the params
2344
                String doctext = sb.toString();
2345
                String[] doctextArr = new String[1];
2346
                doctextArr[0] = doctext;
2347
                params.put("doctext", doctextArr);
2348
                //call the insert routine
2349
                handleInsertOrUpdateAction(request.getRemoteAddr(), response, out, 
2350
                          params, username, groupnames);
2351
              }
2352
              catch(Exception e)
2353
              {
2354
                throw e;
2355
              }
2356
            }
2357
          }
2358
          catch(Exception e)
2359
          {
2360
              logMetacat.error("MetaCatServlet.handleInsertMultipartAction - error uploading text file via multipart: " + e.getMessage());
2361
              e.printStackTrace(System.out);;
2362
          }
2363
        }
2364
      }
2365
    }
2366
    
2367
    /**
2368
     * Handle the upload action by saving the attached file to disk and
2369
     * registering it in the Metacat db
2370
     */
2371
    private void handleUploadAction(HttpServletRequest request,
2372
            PrintWriter out, Hashtable<String, String[]> params, Hashtable<String,String> fileList,
2373
            String username, String[] groupnames, HttpServletResponse response) {
2374
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2375
        //PrintWriter out = null;
2376
        //Connection conn = null;
2377
        //        String action = null;
2378
        String docid = null;
2379
        String qformat = null;
2380
        String output = "";
2381

    
2382
        /*
2383
         * response.setContentType("text/xml"); try { out =
2384
         * response.getWriter(); } catch (IOException ioe2) {
2385
         * System.err.println("Fatal Error: couldn't get response output
2386
         * stream.");
2387
         */
2388

    
2389
        if (params.containsKey("docid")) {
2390
            docid = params.get("docid")[0];
2391
        }
2392

    
2393
        if(params.containsKey("qformat")) {
2394
            qformat = params.get("qformat")[0];
2395
        }
2396

    
2397
        // Make sure we have a docid and datafile
2398
        if (docid != null && fileList.containsKey("datafile")) {
2399
            logMetacat.info("MetaCatServlet.handleUploadAction - Uploading data docid: " + docid);
2400
            // Get a reference to the file part of the form
2401
            //FilePart filePart = (FilePart) fileList.get("datafile");
2402
            String fileName = fileList.get("filename");
2403
            logMetacat.info("MetaCatServlet.handleUploadAction - Uploading filename: " + fileName);
2404
            // Check if the right file existed in the uploaded data
2405
            if (fileName != null) {
2406

    
2407
                try {
2408
                    //logMetacat.info("Upload datafile " + docid
2409
                    // +"...", 10);
2410
                    //If document get lock data file grant
2411
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2412
                        // Save the data file to disk using "docid" as the name
2413
                        String datafilepath = PropertyService.getProperty("application.datafilepath");
2414
                        File dataDirectory = new File(datafilepath);
2415
                        dataDirectory.mkdirs();
2416
                        File newFile = null;
2417
                        //                    File tempFile = null;
2418
                        String tempFileName = fileList.get("name");
2419
                        String newFileName = dataDirectory + File.separator + docid;
2420
                        long size = 0;
2421
                        boolean fileExists = false;
2422

    
2423
                        try {
2424
                            newFile = new File(newFileName);
2425
                            fileExists = newFile.exists();
2426
                            logMetacat.info("MetaCatServlet.handleUploadAction - new file status is: " + fileExists);
2427
                            if ( fileExists == false ) {
2428
                                // copy file to desired output location
2429
                                try {
2430
                                    MetacatUtil.copyFile(tempFileName, newFileName);
2431
                                } catch (IOException ioe) {
2432
                                    logMetacat.error("IO Exception copying file: " +
2433
                                            ioe.getMessage());
2434
                                    ioe.printStackTrace(System.out);
2435
                                }
2436
                                size = newFile.length();
2437
                                if (size == 0) {
2438
                                    throw new IOException("Uploaded file is 0 bytes!");
2439
                                }
2440
                            } // Latent bug here if the file already exists, then the
2441
                              // conditional fails but the document is still registered.
2442
                              // maybe this never happens because we already requested a lock?
2443
                            logMetacat.info("MetaCatServlet.handleUploadAction - Uploading the following to Metacat:" +
2444
                                    fileName + ", " + docid + ", " +
2445
                                    username + ", " + groupnames);
2446
                            //register the file in the database (which generates
2447
                            // an exception
2448
                            //if the docid is not acceptable or other untoward
2449
                            // things happen
2450
                            DocumentImpl.registerDocument(fileName, "BIN", docid,
2451
                                    username, groupnames);
2452
                        } catch (Exception ee) {
2453
                            // If the file did not exist before this method was 
2454
                            // called and an exception is generated while 
2455
                            // creating or registering it, then we want to delete
2456
                            // the file from disk because the operation failed.
2457
                            // However, if the file already existed before the 
2458
                            // method was called, then the exception probably
2459
                            // occurs when registering the document, and so we
2460
                            // want to leave the old file in place.
2461
                            if ( fileExists == false ) {
2462
                                newFile.delete();
2463
                            }
2464
                            
2465
                            logMetacat.info("MetaCatServlet.handleUploadAction - in Exception: fileExists is " + fileExists);
2466
                            logMetacat.error("MetaCatServlet.handleUploadAction - Upload Error: " + ee.getMessage());
2467
                            throw ee;
2468
                        }
2469

    
2470
                        EventLog.getInstance().log(request.getRemoteAddr(),
2471
                                username, docid, "upload");
2472
                        // Force replication this data file
2473
                        // To data file, "insert" and update is same
2474
                        // The fourth parameter is null. Because it is
2475
                        // notification server
2476
                        // and this method is in MetaCatServerlet. It is
2477
                        // original command,
2478
                        // not get force replication info from another metacat
2479
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2480
                                docid, "insert", false, null);
2481
                        logMetacat.debug("MetaCatServlet.handleUploadAction - ForceReplicationHandler created: " + frh.toString());
2482

    
2483
                        // set content type and other response header fields
2484
                        // first
2485
                        output += "<?xml version=\"1.0\"?>";
2486
                        output += "<success>";
2487
                        output += "<docid>" + docid + "</docid>";
2488
                        output += "<size>" + size + "</size>";
2489
                        output += "</success>";
2490
                    }
2491

    
2492
                } catch (Exception e) {
2493

    
2494
                    output += "<?xml version=\"1.0\"?>";
2495
                    output += "<error>";
2496
                    output += e.getMessage();
2497
                    output += "</error>";
2498
                }
2499
            } else {
2500
                // the field did not contain a file
2501
                output += "<?xml version=\"1.0\"?>";
2502
                output += "<error>";
2503
                output += "The uploaded data did not contain a valid file.";
2504
                output += "</error>";
2505
            }
2506
        } else {
2507
            // Error bcse docid missing or file missing
2508
            output += "<?xml version=\"1.0\"?>";
2509
            output += "<error>";
2510
            output += "The uploaded data did not contain a valid docid "
2511
                + "or valid file.";
2512
            output += "</error>";
2513
        }
2514

    
2515
        if (qformat == null || qformat.equals("xml")) {
2516
            response.setContentType("text/xml");
2517
            out.println(output);
2518
        } else {
2519
            try {
2520
                DBTransform trans = new DBTransform();
2521
                response.setContentType("text/html");
2522
                trans.transformXMLDocument(output,
2523
                        "message", "-//W3C//HTML//EN", qformat,
2524
                        out, null, null);
2525
            } catch (Exception e) {
2526

    
2527
                logMetacat.error("MetaCatServlet.handleUploadAction - General error: "
2528
                        + e.getMessage());
2529
                e.printStackTrace(System.out);
2530
            }
2531
        }
2532
    }
2533
    
2534
    /*
2535
     * A method to handle set access action
2536
     */
2537
    protected void handleSetAccessAction(PrintWriter out, Hashtable<String, String[]> params,
2538
            String username, HttpServletRequest request, HttpServletResponse response) {
2539
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2540

    
2541
        String permission = null;
2542
        String permType = null;
2543
        String permOrder = null;
2544
        Vector<String> errorList = new Vector<String>();
2545
        String error = null;
2546
        Vector<String> successList = new Vector<String>();
2547
        String success = null;
2548
        boolean isEmlPkgMember = false;
2549
        
2550
        String[] docList = params.get("docid");
2551
        String[] principalList = params.get("principal");
2552
        String[] permissionList = params.get("permission");
2553
        String[] permTypeList = params.get("permType");
2554
        String[] permOrderList = params.get("permOrder");
2555
        String[] qformatList = params.get("qformat");
2556
        String[] accessBlock = params.get("accessBlock");
2557
        
2558
        if(accessBlock != null) {
2559
            if (docList == null) {
2560
                errorList.addElement("MetaCatServlet.handleSetAccessAction - Doc id missing.  Please check your parameter list, it should look like: "
2561
                    + "?action=setaccess&docid=<doc_id>&accessBlock=<access_section>");
2562
                outputResponse(successList, errorList, out);
2563
                return;
2564
            }
2565
            
2566
            try {
2567
                AccessControlForSingleFile accessControl = 
2568
                    new AccessControlForSingleFile(docList[0]);
2569
                accessControl.insertPermissions(accessBlock[0]);
2570
                successList.addElement("MetaCatServlet.handleSetAccessAction - successfully replaced access block for doc id: " + docList[0]);
2571
            } catch(AccessControlException ace) {
2572
                errorList.addElement("MetaCatServlet.handleSetAccessAction - access control error when setting " + 
2573
                    "access block: " + ace.getMessage());
2574
            } 
2575
            outputResponse(successList, errorList, out);
2576
            return;
2577
        }
2578
        
2579
        // Make sure the parameter is not null
2580
        if (docList == null || principalList == null || permTypeList == null
2581
                || permissionList == null) {
2582
            error = "MetaCatServlet.handleSetAccessAction - Please check your parameter list, it should look like: "
2583
                    + "?action=setaccess&docid=pipeline.1.1&principal=public"
2584
                    + "&permission=read&permType=allow&permOrder=allowFirst";
2585
            errorList.addElement(error);
2586
            outputResponse(successList, errorList, out);
2587
            return;
2588
        }
2589
        
2590
        // Only select first element for permission, type and order
2591
        permission = permissionList[0];
2592
        permType = permTypeList[0];
2593
        if (permOrderList != null) {
2594
            permOrder = permOrderList[0];
2595
        }
2596
        
2597
        // Get package doctype set
2598
        Vector<String> packageSet = null;
2599
        try {
2600
            packageSet = 
2601
                MetacatUtil.getOptionList(PropertyService.getProperty("xml.packagedoctypeset"));
2602
        } catch (PropertyNotFoundException pnfe) {
2603
            logMetacat.error("MetaCatServlet.handleSetAccessAction - Could not find package doctype set.  Setting to null: " 
2604
                    + pnfe.getMessage());
2605
        }
2606
        //debug
2607
        if (packageSet != null) {
2608
            for (int i = 0; i < packageSet.size(); i++) {
2609
                logMetacat.debug("MetaCatServlet.handleSetAccessAction - doctype in package set: "
2610
                        + packageSet.elementAt(i));
2611
            }
2612
        }
2613
        
2614
        // handle every accessionNumber
2615
        for (int i = 0; i < docList.length; i++) {
2616
            String docid = docList[i];
2617
            if (docid.startsWith("urn:")) {
2618
                try {
2619
                    String actualDocId = LSIDUtil.getDocId(docid, false);
2620
                    docid = actualDocId;
2621
                } catch (ParseLSIDException ple) {
2622
                    logMetacat.error("MetaCatServlet.handleSetAccessAction - " +
2623
                            "could not parse lsid: " + docid + " : " + ple.getMessage()); 
2624
                    ple.printStackTrace(System.out);
2625
                }
2626
            }
2627
            
2628
            String accessionNumber = docid;
2629
            String owner = null;
2630
            String publicId = null;
2631
            // Get document owner and public id
2632
            try {
2633
                owner = getFieldValueForDoc(accessionNumber, "user_owner");
2634
                publicId = getFieldValueForDoc(accessionNumber, "doctype");
2635
            } catch (Exception e) {
2636
                logMetacat.error("MetaCatServlet.handleSetAccessAction - Error in handleSetAccessAction: "
2637
                        + e.getMessage());
2638
                e.printStackTrace(System.out);
2639
                error = "Error in set access control for document - " + accessionNumber + e.getMessage();
2640
                errorList.addElement(error);
2641
                continue;
2642
            }
2643
            //check if user is the owner. Only owner can do owner
2644
            if (username == null || owner == null || !username.equals(owner)) {
2645
                error = "User - " + username + " does not have permission to set "
2646
                        + "access control for docid - " + accessionNumber;
2647
                errorList.addElement(error);
2648
                continue;
2649
            }
2650
            
2651
            //*** Find out if the document is a Member of an EML package.
2652
            //*** (for efficiency, only check if it isn't already true
2653
            //*** for the case of multiple files).
2654
            if (isEmlPkgMember == false)
2655
                isEmlPkgMember = (DBUtil.findDataSetDocIdForGivenDocument(accessionNumber) != null);
2656
            
2657
            // If docid publicid is BIN data file or other beta4, 6 package document
2658
            // we could not do set access control. Because we don't want inconsistent
2659
            // to its access docuemnt
2660
            if (publicId != null && packageSet != null
2661
                    && packageSet.contains(publicId) && isEmlPkgMember) {
2662
                error = "Could not set access control to document " + accessionNumber
2663
                        + "because it is in a pakcage and it has a access file for it";
2664
                errorList.addElement(error);
2665
                continue;
2666
            }
2667
            
2668
            // for every principle
2669
            for (int j = 0; j < principalList.length; j++) {
2670
                String principal = principalList[j];
2671
                try {
2672
                    //insert permission
2673
                    AccessControlForSingleFile accessControl = 
2674
                        new AccessControlForSingleFile(accessionNumber);
2675
                    accessControl.insertPermissions(principal, Long.valueOf(permission), permType, permOrder);
2676
                } catch (Exception ee) {
2677
                    logMetacat.error("MetaCatServlet.handleSetAccessAction - Error inserting permission: "
2678
                            + ee.getMessage());
2679
                    ee.printStackTrace(System.out);
2680
                    error = "Failed to set access control for document "
2681
                            + accessionNumber + " because " + ee.getMessage();
2682
                    errorList.addElement(error);
2683
                    continue;
2684
                }
2685
            }
2686
            
2687
            //force replication when this action is called
2688
            boolean isXml = true;
2689
            if (publicId.equalsIgnoreCase("BIN")) {
2690
                isXml = false;
2691
            }
2692
            ForceReplicationHandler frh = 
2693
                new ForceReplicationHandler(accessionNumber, isXml, null);
2694
            logMetacat.debug("MetaCatServlet.handleSetAccessAction - ForceReplicationHandler created: " + frh.toString());
2695
            
2696
        }
2697
        successList.addElement("MetaCatServlet.handleSetAccessAction - successfully added individual access for doc id: " + docList[0]);
2698
        
2699
        if (params.get("forwardto")  != null) {
2700
            try {
2701
                RequestUtil.forwardRequest(request, response, params);
2702
            } catch (MetacatUtilException mue) {
2703
                logMetacat.error("metaCatServlet.handleSetAccessAction - could not forward " +
2704
                        "request. Sending output to response writer");
2705
                mue.printStackTrace(System.out);
2706
                outputResponse(successList, errorList, out);
2707
            }               
2708
        } else {
2709
            outputResponse(successList, errorList, out);
2710
        }
2711
    }
2712
    
2713
    /*
2714
     * A method try to determin a docid's public id, if couldn't find null will
2715
     * be returned.
2716
     */
2717
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
2718
    throws Exception {
2719
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2720
        if (accessionNumber == null || accessionNumber.equals("")
2721
        || fieldName == null || fieldName.equals("")) { throw new Exception(
2722
                "Docid or field name was not specified"); }
2723
        
2724
        PreparedStatement pstmt = null;
2725
        ResultSet rs = null;
2726
        String fieldValue = null;
2727
        String docId = null;
2728
        DBConnection conn = null;
2729
        int serialNumber = -1;
2730
        
2731
        // get rid of revision if access number has
2732
        docId = DocumentUtil.getDocIdFromString(accessionNumber);
2733
        try {
2734
            //check out DBConnection
2735
            conn = DBConnectionPool
2736
                    .getDBConnection("MetaCatServlet.getPublicIdForDoc");
2737
            serialNumber = conn.getCheckOutSerialNumber();
2738
            pstmt = conn.prepareStatement("SELECT " + fieldName
2739
                    + " FROM xml_documents " + "WHERE docid = ? ");
2740
            
2741
            pstmt.setString(1, docId);
2742
            pstmt.execute();
2743
            rs = pstmt.getResultSet();
2744
            boolean hasRow = rs.next();
2745
        //    int perm = 0;
2746
            if (hasRow) {
2747
                fieldValue = rs.getString(1);
2748
            } else {
2749
                throw new Exception("Could not find document: "
2750
                        + accessionNumber);
2751
            }
2752
        } catch (Exception e) {
2753
            logMetacat.error("MetaCatServlet.getFieldValueForDoc - General error: "
2754
                    + e.getMessage());
2755
            throw e;
2756
        } finally {
2757
            try {
2758
                rs.close();
2759
                pstmt.close();
2760
                
2761
            } finally {
2762
                DBConnectionPool.returnDBConnection(conn, serialNumber);
2763
            }
2764
        }
2765
        return fieldValue;
2766
    }
2767
    
2768
    /*
2769
     * Get the list of documents from the database and return the list in an
2770
     * Vector of identifiers.
2771
     *
2772
     * @ returns the array of identifiers
2773
     */
2774
    private Vector<String> getDocumentList() throws SQLException {
2775
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2776
        Vector<String> docList = new Vector<String>();
2777
        PreparedStatement pstmt = null;
2778
        ResultSet rs = null;
2779
        DBConnection conn = null;
2780
        int serialNumber = -1;
2781
        
2782
        try {
2783
            //check out DBConnection
2784
            conn = DBConnectionPool
2785
                    .getDBConnection("MetaCatServlet.getDocumentList");
2786
            serialNumber = conn.getCheckOutSerialNumber();
2787
            pstmt = conn.prepareStatement("SELECT docid, rev"
2788
                    + " FROM xml_documents ");
2789
            pstmt.execute();
2790
            rs = pstmt.getResultSet();
2791
            while (rs.next()) {
2792
                String docid = rs.getString(1);
2793
                String rev = rs.getString(2);
2794
                docList.add(docid + "." + rev);
2795
            }
2796
        } catch (SQLException e) {
2797
            logMetacat.error("MetaCatServlet.getDocumentList - General exception: "
2798
                    + e.getMessage());
2799
            throw e;
2800
        } finally {
2801
            try {
2802
                rs.close();
2803
                pstmt.close();
2804
                
2805
            } catch (SQLException se) {
2806
                logMetacat.error("MetaCatServlet.getDocumentList - General exception: "
2807
                        + se.getMessage());
2808
                throw se;
2809
            } finally {
2810
                DBConnectionPool.returnDBConnection(conn, serialNumber);
2811
            }
2812
        }
2813
        return docList;
2814
    }
2815
    
2816
    /*
2817
     * A method to output setAccess action result
2818
     */
2819
    private void outputResponse(Vector<String> successList, Vector<String> errorList,
2820
            PrintWriter out) {
2821
        boolean error = false;
2822
        boolean success = false;
2823
        // Output prolog
2824
        out.println(PROLOG);
2825
        // output success message
2826
        if (successList != null) {
2827
            for (int i = 0; i < successList.size(); i++) {
2828
                out.println(SUCCESS);
2829
                out.println(successList.elementAt(i));
2830
                out.println(SUCCESSCLOSE);
2831
                success = true;
2832
            }
2833
        }
2834
        // output error message
2835
        if (errorList != null) {
2836
            for (int i = 0; i < errorList.size(); i++) {
2837
                out.println(ERROR);
2838
                out.println(errorList.elementAt(i));
2839
                out.println(ERRORCLOSE);
2840
                error = true;
2841
            }
2842
        }
2843
        
2844
        // if no error and no success info, send a error that nothing happened
2845
        if (!error && !success) {
2846
            out.println(ERROR);
2847
            out.println("Nothing happend for setaccess action");
2848
            out.println(ERRORCLOSE);
2849
        }
2850
    }
2851
    
2852
    /*
2853
     * If the given docid only have one seperter, we need
2854
     * append rev for it. The rev come from xml_documents
2855
     */
2856
    private static String appendRev(String docid) throws PropertyNotFoundException, SQLException, McdbDocNotFoundException {
2857
//        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2858
        String newAccNum = null;
2859
        String separator = PropertyService.getProperty("document.accNumSeparator");
2860
        int firstIndex = docid.indexOf(separator);
2861
        int lastIndex = docid.lastIndexOf(separator);
2862
        if (firstIndex == lastIndex) {
2863
            
2864
            //only one seperater
2865
            int rev = DBUtil.getLatestRevisionInDocumentTable(docid);
2866
            if (rev == -1) {
2867
                throw new McdbDocNotFoundException("the requested docid '"
2868
                        + docid+ "' does not exist");
2869
            } else {
2870
                newAccNum = docid+ separator+ rev;
2871
            }
2872
        } else {
2873
            // in other suituation we don't change the docid
2874
            newAccNum = docid;
2875
        }
2876
        //logMetacat.debug("The docid will be read is "+newAccNum);
2877
        return newAccNum;
2878
    }
2879
    
2880
    /**
2881
     * Schedule the sitemap generator to run periodically and update all
2882
     * of the sitemap files for search indexing engines.
2883
     *
2884
     * @param request a servlet request, from which we determine the context
2885
     */
2886
    protected void scheduleSitemapGeneration(HttpServletRequest request) {
2887
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2888
        if (!_sitemapScheduled) {
2889
            String directoryName = null;
2890
            String skin = null;
2891
            long sitemapInterval = 0;
2892
            
2893
            try {
2894
                directoryName = SystemUtil.getContextDir() + FileUtil.getFS() + "sitemaps";
2895
                skin = PropertyService.getProperty("application.default-style");
2896
                sitemapInterval = 
2897
                    Integer.parseInt(PropertyService.getProperty("sitemap.interval"));
2898
            } catch (PropertyNotFoundException pnfe) {
2899
                logMetacat.error("MetaCatServlet.scheduleSitemapGeneration - Could not run site map generation because property " 
2900
                        + "could not be found: " + pnfe.getMessage());
2901
            }
2902
            
2903
            File directory = new File(directoryName);
2904
            directory.mkdirs();
2905
            String urlRoot = request.getRequestURL().toString();
2906
            Sitemap smap = new Sitemap(directory, urlRoot, skin);
2907
            long firstDelay = 60*1000;   // 60 seconds delay
2908
            timer.schedule(smap, firstDelay, sitemapInterval);
2909
            _sitemapScheduled = true;
2910
        }
2911
    }
2912

    
2913
    /**
2914
     * @param sitemapScheduled toggle the _sitemapScheduled flag
2915
     */
2916
    public void set_sitemapScheduled(boolean sitemapScheduled) {
2917
        _sitemapScheduled = sitemapScheduled;
2918
    }
2919

    
2920
}
(43-43/62)