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
        }
1325
        
1326
        try {
1327
            // Get the document indicated
1328
            logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - params: " + params.toString());
1329
            
1330
            String[] doctext = params.get("doctext");
1331
            String pub = null;
1332
            if (params.containsKey("public")) {
1333
                pub = params.get("public")[0];
1334
            }
1335
            
1336
            StringReader dtd = null;
1337
            if (params.containsKey("dtdtext")) {
1338
                String[] dtdtext = params.get("dtdtext");
1339
                try {
1340
                    if (!dtdtext[0].equals("")) {
1341
                        dtd = new StringReader(dtdtext[0]);
1342
                    }
1343
                } catch (NullPointerException npe) {
1344
                }
1345
            }
1346
            
1347
            if(doctext == null){
1348
                out.println("<?xml version=\"1.0\"?>");
1349
                out.println("<error>");
1350
                out.println("Document text not submitted");
1351
                out.println("</error>");
1352
                return;
1353
            }
1354
            
1355
            logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - the xml document in metacat servlet (before parsing):\n" + doctext[0]);
1356
            StringReader xmlReader = new StringReader(doctext[0]);
1357
            boolean validate = false;
1358
            DocumentImplWrapper documentWrapper = null;
1359
            try {
1360
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1361
                // >
1362
                // in order to decide whether to use validation parser
1363
                validate = needDTDValidation(xmlReader);
1364
                if (validate) {
1365
                    // set a dtd base validation parser
1366
                    String rule = DocumentImpl.DTD;
1367
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1368
                } else {
1369
                    
1370
                    String namespace = XMLSchemaService.findDocumentNamespace(xmlReader);
1371
                    
1372
                    if (namespace != null) {
1373
                        if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1374
                                || namespace.compareTo(
1375
                                DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1376
                            // set eml2 base     validation parser
1377
                            String rule = DocumentImpl.EML200;
1378
                            // using emlparser to check id validation
1379
                            @SuppressWarnings("unused")
1380
                            EMLParser parser = new EMLParser(doctext[0]);
1381
                            documentWrapper = new DocumentImplWrapper(rule, true);
1382
                        } else if (namespace.compareTo(
1383
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1384
                            // set eml2 base validation parser
1385
                            String rule = DocumentImpl.EML210;
1386
                            // using emlparser to check id validation
1387
                            @SuppressWarnings("unused")
1388
                            EMLParser parser = new EMLParser(doctext[0]);
1389
                            documentWrapper = new DocumentImplWrapper(rule, true);
1390
                        } else {
1391
                            // set schema base validation parser
1392
                            String rule = DocumentImpl.SCHEMA;
1393
                            documentWrapper = new DocumentImplWrapper(rule, true);
1394
                        }
1395
                    } else {
1396
                        documentWrapper = new DocumentImplWrapper("", false);
1397
                    }
1398
                }
1399
                
1400
                String[] action = params.get("action");
1401
                String[] docid = params.get("docid");
1402
                String newdocid = null;
1403
                
1404
                String doAction = null;
1405
                if (action[0].equals("insert") || action[0].equals("insertmultipart")) {
1406
                    doAction = "INSERT";
1407
                } else if (action[0].equals("update")) {
1408
                    doAction = "UPDATE";
1409
                }
1410
                
1411
                try {
1412
                    // get a connection from the pool
1413
                    dbConn = DBConnectionPool
1414
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1415
                    serialNumber = dbConn.getCheckOutSerialNumber();
1416
                    
1417
                    // write the document to the database and disk
1418
                    String accNumber = docid[0];
1419
                    logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - " + doAction + " "
1420
                            + accNumber + "...");
1421
                    if (accNumber == null || accNumber.equals("")) {
1422
                        logMetacat.warn("MetaCatServlet.handleInsertOrUpdateAction - writing with null acnumber");
1423
                        newdocid = documentWrapper.write(dbConn, doctext[0], pub, dtd,
1424
                                doAction, null, user, groups);
1425
                        EventLog.getInstance().log(ipAddress, user, "", action[0]);
1426
                    } else {
1427
                        newdocid = documentWrapper.write(dbConn, doctext[0], pub, dtd,
1428
                                doAction, accNumber, user, groups);
1429

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

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

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

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

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

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

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

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

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

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

    
2490
                } catch (Exception e) {
2491

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

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

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

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

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

    
2918
}
(43-43/62)