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.registerSession(id, 
360
                        (String) session.getAttribute("username"), 
361
                        (String[]) session.getAttribute("groupnames"), 
362
                        (String) session.getAttribute("password"), 
363
                        (String) session.getAttribute("name"));
364
            } catch (ServiceException se) {
365
                String errorMsg = "MetacatServlet.handleLoginAction - service problem registering session: "
366
                        + se.getMessage();
367
                logMetacat.error("MetaCatServlet.handleLoginAction - " + errorMsg);
368
                out.println(errorMsg);
369
                se.printStackTrace(System.out);
370
                return;
371
            }           
372
        }
373
                
374
        // format and transform the output
375
        if (qformat.equals("xml")) {
376
            response.setContentType("text/xml");
377
            out.println(sess.getMessage());
378
        } else {
379
            try {
380
                DBTransform trans = new DBTransform();
381
                response.setContentType("text/html");
382
                trans.transformXMLDocument(sess.getMessage(),
383
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
384
                        out, null, null);
385
            } catch (Exception e) {               
386
                logMetacat.error("MetaCatServlet.handleLoginAction - General error"
387
                        + e.getMessage());
388
                e.printStackTrace(System.out);
389
            }
390
        }
391
    }
392
    
393
    /**
394
     * Handle the logout request. Close the connection.
395
     */
396
    public void handleLogoutAction(PrintWriter out, Hashtable<String, String[]> params,
397
            HttpServletRequest request, HttpServletResponse response) {
398
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
399
        String qformat = "xml";
400
        if(params.get("qformat") != null){
401
            qformat = params.get("qformat")[0];
402
        }
403
        
404
        // close the connection
405
        HttpSession sess = request.getSession(false);
406
        logMetacat.info("MetaCatServlet.handleLogoutAction - After get session in logout request");
407
        if (sess != null) {
408
            logMetacat.info("MetaCatServlet.handleLogoutAction - The session id " + sess.getId()
409
            + " will be invalidate in logout action");
410
            logMetacat.info("MetaCatServlet.handleLogoutAction - The session contains user "
411
                    + sess.getAttribute("username")
412
                    + " will be invalidate in logout action");
413
            sess.invalidate();
414
            SessionService.unRegisterSession(sess.getId());
415
        }
416
        
417
        // produce output
418
        StringBuffer output = new StringBuffer();
419
        output.append("<?xml version=\"1.0\"?>");
420
        output.append("<logout>");
421
        output.append("User logged out");
422
        output.append("</logout>");
423
        
424
        //format and transform the output
425
        if (qformat.equals("xml")) {
426
            response.setContentType("text/xml");
427
            out.println(output.toString());
428
        } else {
429
            try {
430
                DBTransform trans = new DBTransform();
431
                response.setContentType("text/html");
432
                trans.transformXMLDocument(output.toString(),
433
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
434
                        out, null, null);
435
            } catch (Exception e) {
436
                logMetacat.error(
437
                        "MetaCatServlet.handleLogoutAction - General error: "
438
                        + e.getMessage());
439
                e.printStackTrace(System.out);
440
            }
441
        }
442
    }
443
    
444
    // END OF LOGIN & LOGOUT SECTION
445
    
446
    // SQUERY & QUERY SECTION
447
    /**
448
     * Retreive the squery xml, execute it and display it
449
     *
450
     * @param out the output stream to the client
451
     * @param params the Hashtable of parameters that should be included in the
452
     *            squery.
453
     * @param response the response object linked to the client
454
     * @param conn the database connection
455
     */
456
    protected void handleSQuery(PrintWriter out, Hashtable<String, String[]> params,
457
            HttpServletResponse response, String user, String[] groups,
458
            String sessionid) throws PropertyNotFoundException {
459
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
460
        long squeryWarnLimit = Long.parseLong(PropertyService.getProperty("database.squeryTimeWarnLimit"));
461
        
462
        long startTime = System.currentTimeMillis();
463
        DBQuery queryobj = new DBQuery();
464
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
465
        long outPutTime = System.currentTimeMillis();
466
        long runTime = outPutTime - startTime;
467

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2552
                } catch (Exception e) {
2553

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

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

    
2587
                logMetacat.error("MetaCatServlet.handleUploadAction - General error: "
2588
                        + e.getMessage());
2589
                e.printStackTrace(System.out);
2590
            }
2591
        }
2592
    }
2593
    
2594
    /*
2595
     * A method to handle set access action
2596
     */
2597
    protected void handleSetAccessAction(PrintWriter out, Hashtable<String, String[]> params,
2598
            String username, HttpServletRequest request, HttpServletResponse response) {
2599
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2600

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

    
2973
    /**
2974
     * @param sitemapScheduled toggle the _sitemapScheduled flag
2975
     */
2976
    public void set_sitemapScheduled(boolean sitemapScheduled) {
2977
        _sitemapScheduled = sitemapScheduled;
2978
    }
2979

    
2980
}
(43-43/63)