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
                    if (!user.equals("public")) {
1018
                        if (DocumentImpl.hasReadPermission("public", null, docid))
1019
                            params.put("publicRead", new String[] {"true"});
1020
                        else
1021
                            params.put("publicRead", new String[] {"false"});
1022
                    }
1023
                    
1024
                    if (response != null) {
1025
                        response.setContentType("text/html"); //MIME type
1026
                    }
1027
                    
1028
                    PrintWriter pw = new PrintWriter(out);
1029
                    
1030
                    // Look up the document type
1031
                    String doctype = doc.getDoctype();
1032
                    // Transform the document to the new doctype
1033
                    DBTransform dbt = new DBTransform();
1034
                    dbt.transformXMLDocument(doc.toString(user, groups,
1035
                            withInlineData), doctype, "-//W3C//HTML//EN",
1036
                            qformat, pw, params, null);
1037
                }
1038
                
1039
            }
1040
            EventLog.getInstance().log(ipAddress, user, docid, "read");
1041
        } catch (PropertyNotFoundException except) {
1042
            throw except;
1043
        }
1044
    }
1045

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

    
1063
        if(params.containsKey("metadatadocid")) {
1064
            metadatadocid = params.get("metadatadocid")[0];
1065
        }
1066
        if (metadatadocid != null && !metadatadocid.equals("")) {
1067
            nameparts.add(metadatadocid);
1068
        }
1069
        // we'll always have the docid, include it in the name
1070
        String doctype = doc.getDoctype();
1071
        // TODO: fix this to lookup the associated FGDC metadata document,
1072
        // and grab the doctype tag for it.  These should be set to something 
1073
        // consistent, not 'metadata' as it stands...
1074
        //if (!doctype.equals("metadata")) {
1075
        //    nameparts.add(docid);
1076
        //} 
1077
        nameparts.add(docid);
1078
        // Set the name of the data file to the entity name plus docid,
1079
        // or if that is unavailable, use the docid alone
1080
        String docname = doc.getDocname();
1081
        if (docname != null && !docname.equals("")) {
1082
            nameparts.add(docname); 
1083
        }
1084
        // combine the name elements with a dash, using a 'join' equivalent
1085
        String delimiter = "-";
1086
        Iterator<String> iter = nameparts.iterator();
1087
        StringBuffer buffer = new StringBuffer(iter.next());
1088
        while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
1089
        outputname = buffer.toString();
1090
        return outputname;
1091
    }
1092
    
1093
    /**
1094
     * read data from URLConnection
1095
     */
1096
    private void readFromURLConnection(HttpServletResponse response,
1097
            String docid) throws IOException, MalformedURLException {
1098
        ServletOutputStream out = response.getOutputStream();
1099
        String contentType = servletContext.getMimeType(docid); //MIME type
1100
        if (contentType == null) {
1101
            if (docid.endsWith(".xml")) {
1102
                contentType = "text/xml";
1103
            } else if (docid.endsWith(".css")) {
1104
                contentType = "text/css";
1105
            } else if (docid.endsWith(".dtd")) {
1106
                contentType = "text/plain";
1107
            } else if (docid.endsWith(".xsd")) {
1108
                contentType = "text/xml";
1109
            } else if (docid.endsWith("/")) {
1110
                contentType = "text/html";
1111
            } else {
1112
                File f = new File(docid);
1113
                if (f.isDirectory()) {
1114
                    contentType = "text/html";
1115
                } else {
1116
                    contentType = "application/octet-stream";
1117
                }
1118
            }
1119
        }
1120
        response.setContentType(contentType);
1121
        // if we decide to use "application/octet-stream" for all data returns
1122
        // response.setContentType("application/octet-stream");
1123
        
1124
        // this is http url
1125
        URL url = new URL(docid);
1126
        BufferedInputStream bis = null;
1127
        try {
1128
            bis = new BufferedInputStream(url.openStream());
1129
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1130
            int b = bis.read(buf);
1131
            while (b != -1) {
1132
                out.write(buf, 0, b);
1133
                b = bis.read(buf);
1134
            }
1135
        } finally {
1136
            if (bis != null) bis.close();
1137
        }
1138
        
1139
    }
1140
    
1141
    /**
1142
     * read file/doc and write to ZipOutputStream
1143
     *
1144
     * @param docid
1145
     * @param zout
1146
     * @param user
1147
     * @param groups
1148
     * @throws ClassNotFoundException
1149
     * @throws IOException
1150
     * @throws SQLException
1151
     * @throws McdbException
1152
     * @throws Exception
1153
     */
1154
    private void addDocToZip(HttpServletRequest request, String docid, String providedFileName,
1155
            ZipOutputStream zout, String user, String[] groups) throws
1156
            ClassNotFoundException, IOException, SQLException, McdbException,
1157
            Exception {
1158
        byte[] bytestring = null;
1159
        ZipEntry zentry = null;
1160
        
1161
        try {
1162
            URL url = new URL(docid);
1163
            
1164
            // this http url; read from URLConnection; add to zip
1165
            //use provided file name if we have one
1166
            if (providedFileName != null && providedFileName.length() > 1) {
1167
                zentry = new ZipEntry(providedFileName);
1168
            }
1169
            else {
1170
                zentry = new ZipEntry(docid);
1171
            }
1172
            zout.putNextEntry(zentry);
1173
            BufferedInputStream bis = null;
1174
            try {
1175
                bis = new BufferedInputStream(url.openStream());
1176
                byte[] buf = new byte[4 * 1024]; // 4K buffer
1177
                int b = bis.read(buf);
1178
                while (b != -1) {
1179
                    zout.write(buf, 0, b);
1180
                    b = bis.read(buf);
1181
                }
1182
            } finally {
1183
                if (bis != null) bis.close();
1184
            }
1185
            zout.closeEntry();
1186
            
1187
        } catch (MalformedURLException mue) {
1188
            
1189
            // this is metacat doc (data file or metadata doc)
1190
            try {
1191
                DocumentImpl doc = new DocumentImpl(docid);
1192
                
1193
                //check the permission for read
1194
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1195
                    Exception e = new Exception("User " + user
1196
                            + " does not have "
1197
                            + "permission to read the document with the docid "
1198
                            + docid);
1199
                    throw e;
1200
                }
1201
                
1202
                if (doc.getRootNodeID() == 0) {
1203
                    // this is data file; add file to zip
1204
                    String filepath = PropertyService.getProperty("application.datafilepath");
1205
                    if (!filepath.endsWith("/")) {
1206
                        filepath += "/";
1207
                    }
1208
                    String filename = filepath + docid;
1209
                    FileInputStream fin = null;
1210
                    fin = new FileInputStream(filename);
1211
                    try {
1212
                        //use provided file name if we have one
1213
                        if (providedFileName != null && providedFileName.length() > 1) {
1214
                            zentry = new ZipEntry(providedFileName);
1215
                        }
1216
                        else {
1217
                            zentry = new ZipEntry(docid);
1218
                        }
1219
                        zout.putNextEntry(zentry);
1220
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
1221
                        int b = fin.read(buf);
1222
                        while (b != -1) {
1223
                            zout.write(buf, 0, b);
1224
                            b = fin.read(buf);
1225
                        }
1226
                    } finally {
1227
                        if (fin != null) fin.close();
1228
                    }
1229
                    zout.closeEntry();
1230
                    
1231
                } else {
1232
                    // this is metadata doc; add doc to zip
1233
                    bytestring = doc.toString().getBytes();
1234
                    //use provided file name if given
1235
                    if (providedFileName != null && providedFileName.length() > 1) {
1236
                        zentry = new ZipEntry(providedFileName);
1237
                    }
1238
                    else {
1239
                        zentry = new ZipEntry(docid + ".xml");
1240
                    }
1241
                    zentry.setSize(bytestring.length);
1242
                    zout.putNextEntry(zentry);
1243
                    zout.write(bytestring, 0, bytestring.length);
1244
                    zout.closeEntry();
1245
                }
1246
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1247
                        docid, "read");
1248
            } catch (Exception except) {
1249
                throw except;
1250
            }
1251
        }
1252
    }
1253
    
1254
    /**
1255
     * If metacat couldn't find a data file or document locally, it will read
1256
     * this docid from its home server. This is for the replication feature
1257
     */
1258
    private void readFromRemoteMetaCat(HttpServletResponse response,
1259
            String docid, String rev, String user, String password,
1260
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
1261
            throws Exception {
1262
        // Create a object of RemoteDocument, "" is for zipEntryPath
1263
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
1264
                password, "");
1265
        String docType = remoteDoc.getDocType();
1266
        // Only read data file
1267
        if (docType.equals("BIN")) {
1268
            // If it is zip format
1269
            if (zip) {
1270
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
1271
            } else {
1272
                if (out == null) {
1273
                    out = response.getOutputStream();
1274
                }
1275
                response.setContentType("application/octet-stream");
1276
                remoteDoc.readDocumentFromRemoteServer(out);
1277
            }
1278
        } else {
1279
            throw new Exception("Docid: " + docid + "." + rev
1280
                    + " couldn't find");
1281
        }
1282
    }
1283
    
1284
    /**
1285
     * Handle the database putdocument request and write an XML document to the
1286
     * database connection
1287
     */
1288
    public void handleInsertOrUpdateAction(HttpServletRequest request,
1289
            HttpServletResponse response, PrintWriter out, Hashtable<String, String[]> params,
1290
            String user, String[] groups) {
1291
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1292
        DBConnection dbConn = null;
1293
        int serialNumber = -1;
1294
        String output = "";
1295
        String qformat = null;
1296
        if(params.containsKey("qformat"))
1297
        {
1298
          qformat = params.get("qformat")[0];
1299
        }
1300
        
1301
        if(params.get("docid") == null){
1302
            out.println("<?xml version=\"1.0\"?>");
1303
            out.println("<error>");
1304
            out.println("Docid not specified");
1305
            out.println("</error>");
1306
            logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - Docid not specified");
1307
            return;
1308
        }
1309
        
1310
        try {
1311
            if (!AuthUtil.canInsertOrUpdate(user, groups)) {
1312
                out.println("<?xml version=\"1.0\"?>");
1313
                out.println("<error>");
1314
                out.println("User '" + user + "' not allowed to insert and update");
1315
                out.println("</error>");
1316
                logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - User '" + user + "' not allowed to insert and update");
1317
                return;
1318
            }
1319
        } catch (MetacatUtilException ue) {
1320
            logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - Could not determine if user could insert or update: "
1321
                    + ue.getMessage());
1322
            ue.printStackTrace(System.out);
1323
        }
1324
        
1325
        try {
1326
            // Get the document indicated
1327
            logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - params: " + params.toString());
1328
            
1329
            String[] doctext = params.get("doctext");
1330
            String pub = null;
1331
            if (params.containsKey("public")) {
1332
                pub = params.get("public")[0];
1333
            }
1334
            
1335
            StringReader dtd = null;
1336
            if (params.containsKey("dtdtext")) {
1337
                String[] dtdtext = params.get("dtdtext");
1338
                try {
1339
                    if (!dtdtext[0].equals("")) {
1340
                        dtd = new StringReader(dtdtext[0]);
1341
                    }
1342
                } catch (NullPointerException npe) {
1343
                }
1344
            }
1345
            
1346
            if(doctext == null){
1347
                out.println("<?xml version=\"1.0\"?>");
1348
                out.println("<error>");
1349
                out.println("Document text not submitted");
1350
                out.println("</error>");
1351
                return;
1352
            }
1353
            
1354
            logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - the xml document in metacat servlet (before parsing):\n" + doctext[0]);
1355
            StringReader xmlReader = new StringReader(doctext[0]);
1356
            boolean validate = false;
1357
            DocumentImplWrapper documentWrapper = null;
1358
            try {
1359
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1360
                // >
1361
                // in order to decide whether to use validation parser
1362
                validate = needDTDValidation(xmlReader);
1363
                if (validate) {
1364
                    // set a dtd base validation parser
1365
                    String rule = DocumentImpl.DTD;
1366
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1367
                } else {
1368
                    
1369
                    String namespace = XMLSchemaService.findDocumentNamespace(xmlReader);
1370
                    
1371
                    if (namespace != null) {
1372
                        if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1373
                                || namespace.compareTo(
1374
                                DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1375
                            // set eml2 base     validation parser
1376
                            String rule = DocumentImpl.EML200;
1377
                            // using emlparser to check id validation
1378
                            @SuppressWarnings("unused")
1379
                            EMLParser parser = new EMLParser(doctext[0]);
1380
                            documentWrapper = new DocumentImplWrapper(rule, true);
1381
                        } else if (namespace.compareTo(
1382
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1383
                            // set eml2 base validation parser
1384
                            String rule = DocumentImpl.EML210;
1385
                            // using emlparser to check id validation
1386
                            @SuppressWarnings("unused")
1387
                            EMLParser parser = new EMLParser(doctext[0]);
1388
                            documentWrapper = new DocumentImplWrapper(rule, true);
1389
                        } else {
1390
                            // set schema base validation parser
1391
                            String rule = DocumentImpl.SCHEMA;
1392
                            documentWrapper = new DocumentImplWrapper(rule, true);
1393
                        }
1394
                    } else {
1395
                        documentWrapper = new DocumentImplWrapper("", false);
1396
                    }
1397
                }
1398
                
1399
                String[] action = params.get("action");
1400
                String[] docid = params.get("docid");
1401
                String newdocid = null;
1402
                
1403
                String doAction = null;
1404
                if (action[0].equals("insert") || action[0].equals("insertmultipart")) {
1405
                    doAction = "INSERT";
1406
                } else if (action[0].equals("update")) {
1407
                    doAction = "UPDATE";
1408
                }
1409
                
1410
                try {
1411
                    // get a connection from the pool
1412
                    dbConn = DBConnectionPool
1413
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1414
                    serialNumber = dbConn.getCheckOutSerialNumber();
1415
                    
1416
                    // write the document to the database and disk
1417
                    String accNumber = docid[0];
1418
                    logMetacat.debug("MetaCatServlet.handleInsertOrUpdateAction - " + doAction + " "
1419
                            + accNumber + "...");
1420
                    if (accNumber == null || accNumber.equals("")) {
1421
                        logMetacat.warn("MetaCatServlet.handleInsertOrUpdateAction - writing with null acnumber");
1422
                        newdocid = documentWrapper.write(dbConn, doctext[0], pub, dtd,
1423
                                doAction, null, user, groups);
1424
                        EventLog.getInstance().log(request.getRemoteAddr(),
1425
                                user, "", action[0]);
1426
                        } else {
1427
                            newdocid = documentWrapper.write(dbConn, doctext[0], pub, dtd,
1428
                                    doAction, accNumber, user, groups);
1429
                            
1430
                            EventLog.getInstance().log(request.getRemoteAddr(),
1431
                                    user, accNumber, action[0]);
1432
                        }
1433
                } finally {
1434
                    // Return db connection
1435
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1436
                }
1437
                
1438
                // set content type and other response header fields first
1439
                //response.setContentType("text/xml");
1440
                output += "<?xml version=\"1.0\"?>";
1441
                output += "<success>";
1442
                output += "<docid>" + newdocid + "</docid>";
1443
                output += "</success>";
1444
                
1445
            } catch (NullPointerException npe) {
1446
                //response.setContentType("text/xml");
1447
                output += "<?xml version=\"1.0\"?>";
1448
                output += "<error>";
1449
                output += npe.getMessage();
1450
                output += "</error>";
1451
                logMetacat.warn("MetaCatServlet.handleInsertOrUpdateAction - Null pointer error when writing eml document to the database: " + npe.getMessage());
1452
                npe.printStackTrace();
1453
            }
1454
        } catch (Exception e) {
1455
            //response.setContentType("text/xml");
1456
            output += "<?xml version=\"1.0\"?>";
1457
            output += "<error>";
1458
            output += e.getMessage();
1459
            output += "</error>";
1460
            logMetacat.warn("MetaCatServlet.handleInsertOrUpdateAction - General error when writing eml document to the database: " + e.getMessage());
1461
            e.printStackTrace();
1462
        }
1463
        
1464
        if (qformat == null || qformat.equals("xml")) {
1465
            response.setContentType("text/xml");
1466
            out.println(output);
1467
        } else {
1468
            try {
1469
                DBTransform trans = new DBTransform();
1470
                response.setContentType("text/html");
1471
                trans.transformXMLDocument(output,
1472
                        "message", "-//W3C//HTML//EN", qformat,
1473
                        out, null, null);
1474
            } catch (Exception e) {
1475
                
1476
                logMetacat.error("MetaCatServlet.handleInsertOrUpdateAction - General error: "
1477
                        + e.getMessage());
1478
                e.printStackTrace(System.out);
1479
            }
1480
        }
1481
    }
1482
    
1483
    /**
1484
     * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > in
1485
     * order to decide whether to use validation parser
1486
     */
1487
    private static boolean needDTDValidation(StringReader xmlreader)
1488
    throws IOException {
1489
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1490
        StringBuffer cbuff = new StringBuffer();
1491
        java.util.Stack<String> st = new java.util.Stack<String>();
1492
        boolean validate = false;
1493
        boolean commented = false;
1494
        int c;
1495
        int inx;
1496
        
1497
        // read from the stream until find the keywords
1498
        while ((st.empty() || st.size() < 4) && ((c = xmlreader.read()) != -1)) {
1499
            cbuff.append((char) c);
1500
            
1501
            if ((inx = cbuff.toString().indexOf("<!--")) != -1) {
1502
                commented = true;
1503
            }
1504
            
1505
            // "<!DOCTYPE" keyword is found; put it in the stack
1506
            if ((inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1) {
1507
                cbuff = new StringBuffer();
1508
                st.push("<!DOCTYPE");
1509
            }
1510
            // "PUBLIC" keyword is found; put it in the stack
1511
            if ((inx = cbuff.toString().indexOf("PUBLIC")) != -1) {
1512
                cbuff = new StringBuffer();
1513
                st.push("PUBLIC");
1514
            }
1515
            // "SYSTEM" keyword is found; put it in the stack
1516
            if ((inx = cbuff.toString().indexOf("SYSTEM")) != -1) {
1517
                cbuff = new StringBuffer();
1518
                st.push("SYSTEM");
1519
            }
1520
            // ">" character is found; put it in the stack
1521
            // ">" is found twice: fisrt from <?xml ...?>
1522
            // and second from <!DOCTYPE ... >
1523
            if ((inx = cbuff.toString().indexOf(">")) != -1) {
1524
                cbuff = new StringBuffer();
1525
                st.push(">");
1526
            }
1527
        }
1528
        
1529
        // close the stream
1530
        xmlreader.reset();
1531
        
1532
        // check the stack whether it contains the keywords:
1533
        // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
1534
        if (st.size() == 4) {
1535
            if ((st.pop()).equals(">")
1536
            && ((st.peek()).equals("PUBLIC") | (st.pop()).equals("SYSTEM"))
1537
                    && (st.pop()).equals("<!DOCTYPE")) {
1538
                validate = true && !commented;
1539
            }
1540
        }
1541
        
1542
        logMetacat.info("MetaCatServlet.needDTDValidation - Validation for dtd is " + validate);
1543
        return validate;
1544
    }
1545
    
1546
    // END OF INSERT/UPDATE SECTION
1547
    
1548
    /**
1549
     * Handle the database delete request and delete an XML document from the
1550
     * database connection
1551
     */
1552
    public void handleDeleteAction(PrintWriter out, Hashtable<String, String[]> params,
1553
            HttpServletRequest request, HttpServletResponse response,
1554
            String user, String[] groups) {
1555
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1556
        String[] docid = params.get("docid");
1557
        
1558
        if(docid == null){
1559
            response.setContentType("text/xml");
1560
            out.println("<?xml version=\"1.0\"?>");
1561
            out.println("<error>");
1562
            out.println("Docid not specified.");
1563
            out.println("</error>");
1564
            logMetacat.error("MetaCatServlet.handleDeleteAction - Docid not specified for the document to be deleted.");
1565
        } else {
1566
            
1567
            // delete the document from the database
1568
            try {
1569
                
1570
                try {
1571
                    // null means notify server is null
1572
                    DocumentImpl.delete(docid[0], user, groups, null);
1573
                    EventLog.getInstance().log(request.getRemoteAddr(),
1574
                            user, docid[0], "delete");
1575
                    response.setContentType("text/xml");
1576
                    out.println("<?xml version=\"1.0\"?>");
1577
                    out.println("<success>");
1578
                    out.println("Document deleted.");
1579
                    out.println("</success>");
1580
                    logMetacat.info("MetaCatServlet.handleDeleteAction - Document deleted.");
1581
                    
1582
                    // Delete from spatial cache if runningSpatialOption
1583
                    if ( PropertyService.getProperty("spatial.runSpatialOption").equals("true") ) {
1584
                        SpatialHarvester sh = new SpatialHarvester();
1585
                        sh.addToDeleteQue( DocumentUtil.getSmartDocId( docid[0] ) );
1586
                        sh.destroy();
1587
                    }
1588
                    
1589
                } catch (AccessionNumberException ane) {
1590
                    response.setContentType("text/xml");
1591
                    out.println("<?xml version=\"1.0\"?>");
1592
                    out.println("<error>");
1593
                    //out.println("Error deleting document!!!");
1594
                    out.println(ane.getMessage());
1595
                    out.println("</error>");
1596
                    logMetacat.error("MetaCatServlet.handleDeleteAction - Document could not be deleted: "
1597
                            + ane.getMessage());
1598
                    ane.printStackTrace(System.out);
1599
                }
1600
            } catch (Exception e) {
1601
                response.setContentType("text/xml");
1602
                out.println("<?xml version=\"1.0\"?>");
1603
                out.println("<error>");
1604
                out.println(e.getMessage());
1605
                out.println("</error>");
1606
                logMetacat.error("MetaCatServlet.handleDeleteAction - Document could not be deleted: "
1607
                        + e.getMessage());
1608
                e.printStackTrace(System.out);
1609
            }
1610
        }
1611
    }
1612
    
1613
    /**
1614
     * Handle the validation request and return the results to the requestor
1615
     */
1616
    protected void handleValidateAction(PrintWriter out, Hashtable<String, String[]> params) {
1617
        
1618
        // Get the document indicated
1619
        String valtext = null;
1620
        DBConnection dbConn = null;
1621
        int serialNumber = -1;
1622
        
1623
        try {
1624
            valtext = params.get("valtext")[0];
1625
        } catch (Exception nullpe) {
1626
            
1627
            String docid = null;
1628
            try {
1629
                // Find the document id number
1630
                docid = params.get("docid")[0];
1631
                
1632
                // Get the document indicated from the db
1633
                DocumentImpl xmldoc = new DocumentImpl(docid);
1634
                valtext = xmldoc.toString();
1635
                
1636
            } catch (NullPointerException npe) {
1637
                
1638
                out.println("<error>Error getting document ID: " + docid
1639
                        + "</error>");
1640
                //if ( conn != null ) { util.returnConnection(conn); }
1641
                return;
1642
            } catch (Exception e) {
1643
                
1644
                out.println(e.getMessage());
1645
            }
1646
        }
1647
        
1648
        try {
1649
            // get a connection from the pool
1650
            dbConn = DBConnectionPool
1651
                    .getDBConnection("MetaCatServlet.handleValidateAction");
1652
            serialNumber = dbConn.getCheckOutSerialNumber();
1653
            DBValidate valobj = new DBValidate(dbConn);
1654
//            boolean valid = valobj.validateString(valtext);
1655
            
1656
            // set content type and other response header fields first
1657
            
1658
            out.println(valobj.returnErrors());
1659
            
1660
        } catch (NullPointerException npe2) {
1661
            // set content type and other response header fields first
1662
            
1663
            out.println("<error>Error validating document.</error>");
1664
        } catch (Exception e) {
1665
            
1666
            out.println(e.getMessage());
1667
        } finally {
1668
            // Return db connection
1669
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1670
        }
1671
    }
1672
    
1673
    /**
1674
     * Handle "getrevsionanddoctype" action Given a docid, return it's current
1675
     * revision and doctype from data base The output is String look like
1676
     * "rev;doctype"
1677
     */
1678
    protected void handleGetRevisionAndDocTypeAction(PrintWriter out,
1679
            Hashtable<String, String[]> params) {
1680
        // To store doc parameter
1681
        String[] docs = new String[10];
1682
        // Store a single doc id
1683
        String givenDocId = null;
1684
        // Get docid from parameters
1685
        if (params.containsKey("docid")) {
1686
            docs = params.get("docid");
1687
        }
1688
        // Get first docid form string array
1689
        givenDocId = docs[0];
1690
        
1691
        try {
1692
            // Make sure there is a docid
1693
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
1694
                    "User didn't specify docid!"); }//if
1695
            
1696
            // Create a DBUtil object
1697
            DBUtil dbutil = new DBUtil();
1698
            // Get a rev and doctype
1699
            String revAndDocType = dbutil
1700
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
1701
            out.println(revAndDocType);
1702
            
1703
        } catch (Exception e) {
1704
            // Handle exception
1705
            out.println("<?xml version=\"1.0\"?>");
1706
            out.println("<error>");
1707
            out.println(e.getMessage());
1708
            out.println("</error>");
1709
        }
1710
        
1711
    }
1712
    
1713
    /**
1714
     * Handle "getaccesscontrol" action. Read Access Control List from db
1715
     * connection in XML format
1716
     */
1717
    protected void handleGetAccessControlAction(PrintWriter out,
1718
            Hashtable<String,String[]> params, HttpServletResponse response, String username,
1719
            String[] groupnames) {
1720
        
1721
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1722

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

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

    
2904
    /**
2905
     * @param sitemapScheduled toggle the _sitemapScheduled flag
2906
     */
2907
    public void set_sitemapScheduled(boolean sitemapScheduled) {
2908
        _sitemapScheduled = sitemapScheduled;
2909
    }
2910

    
2911
}
(43-43/62)