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.ByteArrayOutputStream;
37
import java.io.Writer;
38
import java.net.MalformedURLException;
39
import java.net.URL;
40
import java.sql.PreparedStatement;
41
import java.sql.ResultSet;
42
import java.sql.SQLException;
43
import java.sql.Timestamp;
44
import java.text.ParseException;
45
import java.text.SimpleDateFormat;
46
import java.util.Enumeration;
47
import java.util.HashMap;
48
import java.util.Hashtable;
49
import java.util.Iterator;
50
import java.util.Map;
51
import java.util.Timer;
52
import java.util.Vector;
53
import java.util.zip.ZipEntry;
54
import java.util.zip.ZipOutputStream;
55

    
56
import javax.servlet.ServletContext;
57
import javax.servlet.ServletOutputStream;
58
import javax.servlet.http.HttpServletRequest;
59
import javax.servlet.http.HttpServletResponse;
60
import javax.servlet.http.HttpSession;
61
import javax.activation.MimetypesFileTypeMap;
62

    
63
import org.apache.log4j.Logger;
64
import org.ecoinformatics.eml.EMLParser;
65

    
66
import au.com.bytecode.opencsv.CSVWriter;
67

    
68
import com.oreilly.servlet.multipart.FilePart;
69
import com.oreilly.servlet.multipart.MultipartParser;
70
import com.oreilly.servlet.multipart.ParamPart;
71
import com.oreilly.servlet.multipart.Part;
72

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

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

    
110
    private static boolean _sitemapScheduled = false;
111

    
112
    // Constants -- these should be final in a servlet    
113
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
114
    private static final String SUCCESS = "<success>";
115
    private static final String SUCCESSCLOSE = "</success>";
116
    private static final String ERROR = "<error>";
117
    private static final String ERRORCLOSE = "</error>";
118
    
119
	private Timer timer;
120
	
121
    public MetacatHandler(Timer timer) {
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.getInstance().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.getInstance().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
    /**
910
     * 
911
     * @return
912
     */
913
    public MetacatResultSet query(String metacatUrl, Hashtable<String, String[]>params, 
914
            String username, String[] groups, String sessionid)
915
      throws Exception
916
    {
917
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
918
        PrintWriter out = new PrintWriter(baos);
919
        handleQuery(out, params, null, username, groups, sessionid);
920
        out.flush();
921
        baos.flush();
922
        //baos.close(); 
923
        //System.out.println("result from query: " + baos.toString());
924
        MetacatResultSet rs = new MetacatResultSet(baos.toString());
925
        return rs;
926
    }
927
    
928
    /**
929
     * set the access permissions on the document specified
930
     */
931
    public void setAccess(String metacatUrl, String username, String docid, String principal, 
932
            String permission, String permissionType, String permissionOrder)
933
      throws Exception
934
    {
935
        Hashtable<String,String[]> params = new Hashtable();
936
        params.put("principal", new String[] {principal});
937
        params.put("permission", new String[] {permission});
938
        params.put("permType", new String[] {permissionType});
939
        params.put("permOrder", new String[] {permissionOrder});
940
        params.put("docid", new String[]{docid});
941
        
942
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
943
        PrintWriter out = new PrintWriter(baos);
944
        handleSetAccessAction(out, params, username, null, null);
945
    }
946
    
947
    /** read metadata or data from Metacat
948
     * @throws PropertyNotFoundException 
949
     * @throws ParseLSIDException 
950
     * @throws InsufficientKarmaException 
951
     */
952
    public void readFromMetacat(String ipAddress,
953
            HttpServletResponse response, OutputStream out, String docid, String qformat,
954
            String user, String[] groups, boolean withInlineData, 
955
            Hashtable<String, String[]> params) throws ClassNotFoundException, 
956
            IOException, SQLException, McdbException, PropertyNotFoundException, 
957
            ParseLSIDException, InsufficientKarmaException {
958
        
959
        Logger logMetacat = Logger.getLogger(MetacatHandler.class);
960
        try {
961
            
962
            if (docid.startsWith("urn:")) {
963
                docid = LSIDUtil.getDocId(docid, true);                 
964
            }
965
            
966
            // here is hack for handle docid=john.10(in order to tell mike.jim.10.1
967
            // mike.jim.10, we require to provide entire docid with rev). But
968
            // some old client they only provide docid without rev, so we need
969
            // to handle this suituation. First we will check how many
970
            // seperator here, if only one, we will append the rev in xml_documents
971
            // to the id.
972
            docid = appendRev(docid);
973
            
974
            DocumentImpl doc = new DocumentImpl(docid);
975
            
976
            //check the permission for read
977
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
978
                InsufficientKarmaException e = new InsufficientKarmaException("User " + user
979
                        + " does not have permission"
980
                        + " to read the document with the docid " + docid);
981
                throw e;
982
            }
983
            
984
            if (doc.getRootNodeID() == 0) {
985
                // this is data file, so find the path on disk for the file
986
                String filepath = PropertyService.getProperty("application.datafilepath");
987
                if (!filepath.endsWith("/")) {
988
                    filepath += "/";
989
                }
990
                String filename = filepath + docid;
991
                FileInputStream fin = null;
992
                fin = new FileInputStream(filename);
993
                
994
                if (response != null) {
995
                    // MIME type
996
                    //String contentType = servletContext.getMimeType(filename);
997
                    String contentType = (new MimetypesFileTypeMap()).getContentType(filename);
998
                    if (contentType == null) {
999
                        ContentTypeProvider provider = new ContentTypeProvider(
1000
                                docid);
1001
                        contentType = provider.getContentType();
1002
                        logMetacat.info("MetaCatServlet.readFromMetacat - Final contenttype is: "
1003
                                + contentType);
1004
                    }
1005
                    response.setContentType(contentType);
1006

    
1007
                    // Set the output filename on the response
1008
                    String outputname = generateOutputName(docid, params, doc);                    
1009
                    response.setHeader("Content-Disposition",
1010
                            "attachment; filename=\"" + outputname + "\"");
1011
                }
1012
                
1013
                // Write the data to the output stream
1014
                try {
1015
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
1016
                    int b = fin.read(buf);
1017
                    while (b != -1) {
1018
                        out.write(buf, 0, b);
1019
                        b = fin.read(buf);
1020
                    }
1021
                } finally {
1022
                    if (fin != null) fin.close();
1023
                }
1024
                
1025
            } else {
1026
                // this is metadata doc
1027
                if (qformat.equals("xml") || qformat.equals("")) {
1028
                    // if equals "", that means no qformat is specified. hence
1029
                    // by default the document should be returned in xml format
1030
                    // set content type first
1031
                    
1032
                    if (response != null) {
1033
                        response.setContentType("text/xml"); //MIME type
1034
                        response.setHeader("Content-Disposition",
1035
                                "attachment; filename=" + docid + ".xml");
1036
                    }
1037
                    
1038
                    // Try to get the metadata file from disk. If it isn't
1039
                    // found, create it from the db and write it to disk then.
1040
                    try {
1041
                        PrintWriter pw = new PrintWriter(out);
1042
                        doc.toXml(pw, user, groups, withInlineData);               
1043
                    } catch (McdbException e) {
1044
                        // any exceptions in reading the xml from disc, and we go back to the
1045
                        // old way of creating the xml directly.
1046
                        logMetacat.error("MetaCatServlet.readFromMetacat - could not read from document file " + docid 
1047
                                + ": " + e.getMessage());
1048
                        e.printStackTrace(System.out);
1049
                        PrintWriter pw = new PrintWriter(out);
1050
                        doc.toXmlFromDb(pw, user, groups, withInlineData);
1051
                    }
1052
                } else {
1053
                    // TODO MCD, this should read from disk as well?
1054
                    //*** This is a metadata doc, to be returned in a skin/custom format.
1055
                    //*** Add param to indicate if public has read access or not.
1056
                    logMetacat.debug("User: \n" + user);
1057
                    if (!user.equals("public")) {
1058
                        if (DocumentImpl.hasReadPermission("public", null, docid))
1059
                            params.put("publicRead", new String[] {"true"});
1060
                        else
1061
                            params.put("publicRead", new String[] {"false"});
1062
                    }
1063
                    
1064
                    if (response != null) {
1065
                        response.setContentType("text/html"); //MIME type
1066
                    }
1067
                    
1068
                    PrintWriter pw = new PrintWriter(out);
1069
                    
1070
                    // Look up the document type
1071
                    String doctype = doc.getDoctype();
1072
                    // Transform the document to the new doctype
1073
                    DBTransform dbt = new DBTransform();
1074
                    dbt.transformXMLDocument(doc.toString(user, groups,
1075
                            withInlineData), doctype, "-//W3C//HTML//EN",
1076
                            qformat, pw, params, null);
1077
                }
1078
                
1079
            }
1080
            EventLog.getInstance().log(ipAddress, user, docid, "read");
1081
        } catch (PropertyNotFoundException except) {
1082
            throw except;
1083
        }
1084
    }
1085

    
1086
    /**
1087
     * Create a filename to be used for naming a downloaded document
1088
     * @param docid the identifier of the document to be named
1089
     * @param params the parameters of the request
1090
     * @param doc the DocumentImpl of the document to be named
1091
     * @return String containing a name for the download
1092
     */
1093
    private String generateOutputName(String docid,
1094
            Hashtable<String, String[]> params, DocumentImpl doc) {
1095
        String outputname = null;
1096
        // check for the existence of a metadatadocid parameter,
1097
        // if this is sent, then send a filename which contains both
1098
        // the metadata docid and the data docid, so the link with
1099
        // metadata is explicitly encoded in the filename.
1100
        String metadatadocid = null;
1101
        Vector<String> nameparts = new Vector<String>();
1102

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

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

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

    
2441
        /*
2442
         * response.setContentType("text/xml"); try { out =
2443
         * response.getWriter(); } catch (IOException ioe2) {
2444
         * System.err.println("Fatal Error: couldn't get response output
2445
         * stream.");
2446
         */
2447

    
2448
        if (params.containsKey("docid")) {
2449
            docid = params.get("docid")[0];
2450
        }
2451

    
2452
        if(params.containsKey("qformat")) {
2453
            qformat = params.get("qformat")[0];
2454
        }
2455

    
2456
        // Make sure we have a docid and datafile
2457
        if (docid != null && fileList.containsKey("datafile")) {
2458
            logMetacat.info("MetaCatServlet.handleUploadAction - Uploading data docid: " + docid);
2459
            // Get a reference to the file part of the form
2460
            //FilePart filePart = (FilePart) fileList.get("datafile");
2461
            String fileName = fileList.get("filename");
2462
            logMetacat.info("MetaCatServlet.handleUploadAction - Uploading filename: " + fileName);
2463
            // Check if the right file existed in the uploaded data
2464
            if (fileName != null) {
2465

    
2466
                try {
2467
                    //logMetacat.info("Upload datafile " + docid
2468
                    // +"...", 10);
2469
                    //If document get lock data file grant
2470
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2471
                        // Save the data file to disk using "docid" as the name
2472
                        String datafilepath = PropertyService.getProperty("application.datafilepath");
2473
                        File dataDirectory = new File(datafilepath);
2474
                        dataDirectory.mkdirs();
2475
                        File newFile = null;
2476
                        //                    File tempFile = null;
2477
                        String tempFileName = fileList.get("name");
2478
                        String newFileName = dataDirectory + File.separator + docid;
2479
                        long size = 0;
2480
                        boolean fileExists = false;
2481

    
2482
                        try {
2483
                            newFile = new File(newFileName);
2484
                            fileExists = newFile.exists();
2485
                            logMetacat.info("MetaCatServlet.handleUploadAction - new file status is: " + fileExists);
2486
                            if ( fileExists == false ) {
2487
                                // copy file to desired output location
2488
                                try {
2489
                                    MetacatUtil.copyFile(tempFileName, newFileName);
2490
                                } catch (IOException ioe) {
2491
                                    logMetacat.error("IO Exception copying file: " +
2492
                                            ioe.getMessage());
2493
                                    ioe.printStackTrace(System.out);
2494
                                }
2495
                                size = newFile.length();
2496
                                if (size == 0) {
2497
                                    throw new IOException("Uploaded file is 0 bytes!");
2498
                                }
2499
                            } // Latent bug here if the file already exists, then the
2500
                              // conditional fails but the document is still registered.
2501
                              // maybe this never happens because we already requested a lock?
2502
                            logMetacat.info("MetaCatServlet.handleUploadAction - Uploading the following to Metacat:" +
2503
                                    fileName + ", " + docid + ", " +
2504
                                    username + ", " + groupnames);
2505
                            //register the file in the database (which generates
2506
                            // an exception
2507
                            //if the docid is not acceptable or other untoward
2508
                            // things happen
2509
                            DocumentImpl.registerDocument(fileName, "BIN", docid,
2510
                                    username, groupnames);
2511
                        } catch (Exception ee) {
2512
                            // If the file did not exist before this method was 
2513
                            // called and an exception is generated while 
2514
                            // creating or registering it, then we want to delete
2515
                            // the file from disk because the operation failed.
2516
                            // However, if the file already existed before the 
2517
                            // method was called, then the exception probably
2518
                            // occurs when registering the document, and so we
2519
                            // want to leave the old file in place.
2520
                            if ( fileExists == false ) {
2521
                                newFile.delete();
2522
                            }
2523
                            
2524
                            logMetacat.info("MetaCatServlet.handleUploadAction - in Exception: fileExists is " + fileExists);
2525
                            logMetacat.error("MetaCatServlet.handleUploadAction - Upload Error: " + ee.getMessage());
2526
                            throw ee;
2527
                        }
2528

    
2529
                        EventLog.getInstance().log(request.getRemoteAddr(),
2530
                                username, docid, "upload");
2531
                        // Force replication this data file
2532
                        // To data file, "insert" and update is same
2533
                        // The fourth parameter is null. Because it is
2534
                        // notification server
2535
                        // and this method is in MetaCatServerlet. It is
2536
                        // original command,
2537
                        // not get force replication info from another metacat
2538
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2539
                                docid, "insert", false, null);
2540
                        logMetacat.debug("MetaCatServlet.handleUploadAction - ForceReplicationHandler created: " + frh.toString());
2541

    
2542
                        // set content type and other response header fields
2543
                        // first
2544
                        output += "<?xml version=\"1.0\"?>";
2545
                        output += "<success>";
2546
                        output += "<docid>" + docid + "</docid>";
2547
                        output += "<size>" + size + "</size>";
2548
                        output += "</success>";
2549
                    }
2550

    
2551
                } catch (Exception e) {
2552

    
2553
                    output += "<?xml version=\"1.0\"?>";
2554
                    output += "<error>";
2555
                    output += e.getMessage();
2556
                    output += "</error>";
2557
                }
2558
            } else {
2559
                // the field did not contain a file
2560
                output += "<?xml version=\"1.0\"?>";
2561
                output += "<error>";
2562
                output += "The uploaded data did not contain a valid file.";
2563
                output += "</error>";
2564
            }
2565
        } else {
2566
            // Error bcse docid missing or file missing
2567
            output += "<?xml version=\"1.0\"?>";
2568
            output += "<error>";
2569
            output += "The uploaded data did not contain a valid docid "
2570
                + "or valid file.";
2571
            output += "</error>";
2572
        }
2573

    
2574
        if (qformat == null || qformat.equals("xml")) {
2575
            response.setContentType("text/xml");
2576
            out.println(output);
2577
        } else {
2578
            try {
2579
                DBTransform trans = new DBTransform();
2580
                response.setContentType("text/html");
2581
                trans.transformXMLDocument(output,
2582
                        "message", "-//W3C//HTML//EN", qformat,
2583
                        out, null, null);
2584
            } catch (Exception e) {
2585

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

    
2970
    /**
2971
     * @param sitemapScheduled toggle the _sitemapScheduled flag
2972
     */
2973
    public void set_sitemapScheduled(boolean sitemapScheduled) {
2974
        _sitemapScheduled = sitemapScheduled;
2975
    }
2976

    
2977
}
(43-43/63)