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

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

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

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

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

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

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

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

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

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

    
2456
        if(params.containsKey("qformat")) {
2457
            qformat = params.get("qformat")[0];
2458
        }
2459

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

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

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

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

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

    
2555
                } catch (Exception e) {
2556

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

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

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

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

    
2981
}
(43-43/63)