Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley, Matthew Perry
7
 *    Release: @release@
8
 *
9
 *   '$Author: perry $'
10
 *     '$Date: 2006-07-31 14:50:43 -0700 (Mon, 31 Jul 2006) $'
11
 * '$Revision: 3028 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.io.BufferedInputStream;
31
import java.io.File;
32
import java.io.FileInputStream;
33
import java.io.IOException;
34
import java.io.PrintWriter;
35
import java.io.StringReader;
36
import java.net.MalformedURLException;
37
import java.net.URL;
38
import java.sql.PreparedStatement;
39
import java.sql.ResultSet;
40
import java.sql.SQLException;
41
import java.sql.Timestamp;
42
import java.text.ParseException;
43
import java.text.SimpleDateFormat;
44
import java.util.Enumeration;
45
import java.util.HashMap;
46
import java.util.Hashtable;
47
import java.util.Iterator;
48
import java.util.Properties;
49
import java.util.Timer;
50
import java.util.Vector;
51
import java.util.zip.ZipEntry;
52
import java.util.zip.ZipOutputStream;
53

    
54
import javax.servlet.ServletConfig;
55
import javax.servlet.ServletContext;
56
import javax.servlet.ServletException;
57
import javax.servlet.ServletOutputStream;
58
import javax.servlet.http.HttpServlet;
59
import javax.servlet.http.HttpServletRequest;
60
import javax.servlet.http.HttpServletResponse;
61
import javax.servlet.http.HttpSession;
62

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

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

    
72
import edu.ucsb.nceas.utilities.Options;
73
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialQuery;
74
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialDocument;
75
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialDataset;
76
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialConstants;
77

    
78
/**
79
 * A metadata catalog server implemented as a Java Servlet
80
 *
81
 * <p>
82
 * Valid parameters are: <br>
83
 * action=query -- query the values of all elements and attributes and return a
84
 * result set of nodes <br>
85
 * action=squery -- structured query (see pathquery.dtd) <br>
86
 * action= -- export a zip format for data packadge <br>
87
 * action=read -- read any metadata/data file from Metacat and from Internet
88
 * <br>
89
 * action=insert -- insert an XML document into the database store <br>
90
 * action=update -- update an XML document that is in the database store <br>
91
 * action=delete -- delete an XML document from the database store <br>
92
 * action=validate -- vallidate the xml contained in valtext <br>
93
 * doctype -- document type list returned by the query (publicID) <br>
94
 * qformat=xml -- display resultset from query in XML <br>
95
 * qformat=html -- display resultset from query in HTML <br>
96
 * qformat=zip -- zip resultset from query <br>
97
 * docid=34 -- display the document with the document ID number 34 <br>
98
 * doctext -- XML text of the document to load into the database <br>
99
 * acltext -- XML access text for a document to load into the database <br>
100
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog <br>
101
 * query -- actual query text (to go with 'action=query' or 'action=squery')
102
 * <br>
103
 * valtext -- XML text to be validated <br>
104
 * action=getaccesscontrol -- retrieve acl info for Metacat document <br>
105
 * action=getdoctypes -- retrieve all doctypes (publicID) <br>
106
 * action=getdtdschema -- retrieve a DTD or Schema file <br>
107
 * action=getdataguide -- retrieve a Data Guide <br>
108
 * action=getprincipals -- retrieve a list of principals in XML <br>
109
 * datadoc -- data document name (id) <br>
110
 * action=getlog -- get a report of events that have occurred in the system<br>
111
 * ipAddress --  filter on one or more IP addresses<br>
112
 * principal -- filter on one or more principals (LDAP DN syntax)<br>
113
 * docid -- filter on one or more document identifiers (with revision)<br>
114
 * event -- filter on event type (e.g., read, insert, update, delete)<br>
115
 * start -- filter out events before the start date-time<br>
116
 * end -- filter out events before the end date-time<br>
117
 * <p>
118
 * The particular combination of parameters that are valid for each particular
119
 * action value is quite specific. This documentation will be reorganized to
120
 * reflect this information.
121
 */
122
public class MetaCatServlet extends HttpServlet
123
{
124
    private static Hashtable sessionHash = new Hashtable();
125
    private Timer timer = null;
126
    
127
    // Constants -- these should be final in a servlet
128
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
129
    private static final String SUCCESS = "<success>";
130
    private static final String SUCCESSCLOSE = "</success>";
131
    private static final String ERROR = "<error>";
132
    private static final String ERRORCLOSE = "</error>";
133
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
134
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
135
    public static final String NAMESPACEKEYWORD = "xmlns";
136
    public static final String EML2KEYWORD = ":eml";
137
    public static final String XMLFORMAT = "xml";
138
    private static final String CONFIG_DIR = "WEB-INF";
139
    private static final String CONFIG_NAME = "metacat.properties"; 
140
    
141
    /**
142
     * Initialize the servlet by creating appropriate database connections
143
     */
144
    public void init(ServletConfig config) throws ServletException
145
    {
146
        try {
147
            super.init(config);
148
            ServletContext context = config.getServletContext();
149

    
150
            // Initialize the properties file for our options
151
            String dirPath = context.getRealPath(CONFIG_DIR);
152
            File propertyFile = new File(dirPath, CONFIG_NAME);
153

    
154
            String LOG_CONFIG_NAME = dirPath + "/log4j.properties";
155
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
156
            
157
            Options options = null;
158
            try {
159
                options = Options.initialize(propertyFile);
160
                MetaCatUtil.printMessage("Options configured: "
161
                        + options.getOption("configured"));
162
            } catch (IOException ioe) {
163
                Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
164
                logMetacat.error("Error in loading options: "
165
                        + ioe.getMessage());
166
            }
167

    
168
            MetaCatUtil util = new MetaCatUtil();
169
            
170
            //initialize DBConnection pool
171
            DBConnectionPool connPool = DBConnectionPool.getInstance();
172
            
173
            // Index the paths specified in the metacat.properties
174
            checkIndexPaths();
175

    
176
            // initiate the indexing Queue
177
            IndexingQueue.getInstance();
178
            
179
            // start the IndexingThread if indexingTimerTaskTime more than 0. 
180
            // It will index all the documents not yet indexed in the database             
181
            int indexingTimerTaskTime = Integer.parseInt(MetaCatUtil.getOption("indexingTimerTaskTime"));
182
            if(indexingTimerTaskTime > 0){
183
            	timer = new Timer();
184
            	timer.schedule(new IndexingTimerTask(), 0, indexingTimerTaskTime);
185
            }
186
            
187
            // read the config files: 
188
            Vector skins = MetaCatUtil.getOptionList(MetaCatUtil.getOption("skinconfigfiles"));
189
            String skinName, skinDirPath = null;
190
            File skinPropertyFile = null;
191
           
192
            for (int i = 0; i < skins.size(); i++) {
193
            	skinName = (String) skins.elementAt(i);
194
                skinDirPath = context.getRealPath(CONFIG_DIR + "/skin.configs/" + skinName);
195
                skinPropertyFile = new File(skinDirPath, skinName + ".properties"); 
196
                Properties skinOption = null;
197
                try	{
198
                	skinOption = new Properties();
199
                    FileInputStream fis = new FileInputStream(skinPropertyFile);
200
                    skinOption.load(fis);
201
                    fis.close();
202
                } catch (IOException ioe) {
203
                    Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
204
                    logMetacat.error("Error in loading options for skin " + "skinName" +" : "
205
                            + ioe.getMessage());
206
                }                
207
                MetaCatUtil.skinconfigs.put(skinName, skinOption);
208
            }
209

    
210

    
211
	if (MetacatSpatialConstants.runSpatialOption == true ) {	    
212
        
213
	    // create a spatial index of the database
214
            MetacatSpatialConstants.setServerContext(MetaCatUtil.getOption("server"));
215
            MetacatSpatialQuery  _spatialQuery = new MetacatSpatialQuery();
216
            
217
            // issue the query  -- using the geographic bounds of the Earth
218
            MetacatSpatialDataset _data = _spatialQuery.queryDatasetByCartesianBounds(-180, -90, 180, 90);
219
            
220
            // write the data to the appropriate theme 
221
            _data.writeMetacatSpatialCache();
222
	 
223
	}
224
           
225
           
226
            MetaCatUtil.printMessage("Metacat (" + Version.getVersion()
227
                               + ") initialized.");
228

    
229
        } catch (ServletException ex) {
230
            throw ex;
231
        } catch (SQLException e) {
232
            Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
233
            logMetacat.error("Error in MetacatServlet.init: "
234
                    + e.getMessage());
235
        }
236
    }
237

    
238
    /**
239
     * Close all db connections from the pool
240
     */
241
    public void destroy()
242
    {
243
        // Close all db connection
244
        System.out.println("Destroying MetacatServlet");
245
        timer.cancel();
246
        IndexingQueue.getInstance().setMetacatRunning(false);
247
        DBConnectionPool.release();
248
    }
249

    
250
    /** Handle "GET" method requests from HTTP clients */
251
    public void doGet(HttpServletRequest request, HttpServletResponse response)
252
            throws ServletException, IOException
253
    {
254

    
255
        // Process the data and send back the response
256
        handleGetOrPost(request, response);
257
    }
258

    
259
    /** Handle "POST" method requests from HTTP clients */
260
    public void doPost(HttpServletRequest request, HttpServletResponse response)
261
            throws ServletException, IOException
262
    {
263

    
264
        // Process the data and send back the response
265
        handleGetOrPost(request, response);
266
    }
267

    
268
    /**
269
     * Index the paths specified in the metacat.properties
270
     */
271
    private void checkIndexPaths() {
272
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
273
        MetaCatUtil.pathsForIndexing
274
            = MetaCatUtil.getOptionList(MetaCatUtil.getOption("indexPaths"));
275
    
276
        if (MetaCatUtil.pathsForIndexing != null) {
277
    
278
            MetaCatUtil.printMessage("Indexing paths specified in metacat.properties....");
279
    
280
            DBConnection conn = null;
281
            int serialNumber = -1;
282
            PreparedStatement pstmt = null;
283
            PreparedStatement pstmt1 = null;
284
            ResultSet rs = null;
285
    
286
            for (int i = 0; i < MetaCatUtil.pathsForIndexing.size(); i++) {
287
                logMetacat.debug("Checking if '"
288
                           + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
289
                           + "' is indexed.... ");
290
    
291
                try {
292
                    //check out DBConnection
293
                    conn = DBConnectionPool.
294
                        getDBConnection("MetaCatServlet.checkIndexPaths");
295
                    serialNumber = conn.getCheckOutSerialNumber();
296
    
297
                    pstmt = conn.prepareStatement(
298
                        "SELECT * FROM xml_path_index " + "WHERE path = ?");
299
                    pstmt.setString(1, (String) MetaCatUtil.pathsForIndexing
300
                                    .elementAt(i));
301
    
302
                    pstmt.execute();
303
                    rs = pstmt.getResultSet();
304
    
305
                    if (!rs.next()) {
306
                        logMetacat.debug(".....not indexed yet.");
307
                        rs.close();
308
                        pstmt.close();
309
                        conn.increaseUsageCount(1);
310
    
311
                        logMetacat.debug(
312
                              "Inserting following path in xml_path_index: "
313
                              + (String)MetaCatUtil.pathsForIndexing
314
                                                   .elementAt(i));
315
   			if(((String)MetaCatUtil.pathsForIndexing.elementAt(i)).indexOf("@")<0){ 
316
                        	pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
317
                              		+ "n.nodedata, n.nodedatanumerical, n.parentnodeid"
318
                              		+ " FROM xml_nodes n, xml_index i WHERE"
319
                              		+ " i.path = ? and n.parentnodeid=i.nodeid and"
320
                              		+ " n.nodetype LIKE 'TEXT' order by n.parentnodeid");
321
			} else {
322
                        	pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
323
                              		+ "n.nodedata, n.nodedatanumerical, n.parentnodeid"
324
                              		+ " FROM xml_nodes n, xml_index i WHERE"
325
                              		+ " i.path = ? and n.nodeid=i.nodeid and"
326
                              		+ " n.nodetype LIKE 'ATTRIBUTE' order by n.parentnodeid");
327
			}
328
                        pstmt.setString(1, (String) MetaCatUtil.
329
                                        pathsForIndexing.elementAt(i));
330
                        pstmt.execute();
331
                        rs = pstmt.getResultSet();
332
    
333
                        int count = 0;
334
                        logMetacat.debug(
335
                                       "Executed the select statement for: "
336
                                       + (String) MetaCatUtil.pathsForIndexing
337
                                         .elementAt(i));
338
    
339
                        try {
340
                            while (rs.next()) {
341
    
342
                                String docid = rs.getString(1);
343
                                String nodedata = rs.getString(2);
344
                                float nodedatanumerical = rs.getFloat(3);
345
                                int parentnodeid = rs.getInt(4);
346
    
347
                                if (!nodedata.trim().equals("")) {
348
                                    pstmt1 = conn.prepareStatement(
349
                                        "INSERT INTO xml_path_index"
350
                                        + " (docid, path, nodedata, "
351
                                        + "nodedatanumerical, parentnodeid)"
352
                                        + " VALUES (?, ?, ?, ?, ?)");
353
    
354
                                    pstmt1.setString(1, docid);
355
                                    pstmt1.setString(2, (String) MetaCatUtil.
356
                                                pathsForIndexing.elementAt(i));
357
                                    pstmt1.setString(3, nodedata);
358
                                    pstmt1.setFloat(4, nodedatanumerical);
359
                                    pstmt1.setInt(5, parentnodeid);
360
    
361
                                    pstmt1.execute();
362
                                    pstmt1.close();
363
    
364
                                    count++;
365
    
366
                                }
367
                            }
368
                        }
369
                        catch (Exception e) {
370
                            System.out.println("Exception:" + e.getMessage());
371
                            e.printStackTrace();
372
                        }
373
    
374
                        rs.close();
375
                        pstmt.close();
376
                        conn.increaseUsageCount(1);
377
    
378
                        logMetacat.info("Indexed " + count
379
                                + " records from xml_nodes for '"
380
                                + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
381
                                + "'");
382
    
383
                    } else {
384
                    	logMetacat.debug(".....already indexed.");
385
                    }
386
    
387
                    rs.close();
388
                    pstmt.close();
389
                    conn.increaseUsageCount(1);
390
    
391
                } catch (Exception e) {
392
                    logMetacat.error("Error in MetaCatServlet.checkIndexPaths: "
393
                                             + e.getMessage());
394
                }finally {
395
                    //check in DBonnection
396
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
397
                }
398
    
399
    
400
            }
401
    
402
            MetaCatUtil.printMessage("Path Indexing Completed");
403
        }
404
    }    
405

    
406
    /**
407
     * Control servlet response depending on the action parameter specified
408
     */
409
    private void handleGetOrPost(HttpServletRequest request,
410
            HttpServletResponse response) throws ServletException, IOException
411
    {
412
        MetaCatUtil util = new MetaCatUtil();
413
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
414
        
415
        /*
416
         * logMetacat.debug("Connection pool size: "
417
         * +connPool.getSizeOfDBConnectionPool(),10);
418
         * logMetacat.debug("Free DBConnection number: "
419
         */
420
        //If all DBConnection in the pool are free and DBConnection pool
421
        //size is greater than initial value, shrink the connection pool
422
        //size to initial value
423
        DBConnectionPool.shrinkDBConnectionPoolSize();
424

    
425
        //Debug message to print out the method which have a busy DBConnection
426
        try {
427
            DBConnectionPool pool = DBConnectionPool.getInstance();
428
            pool.printMethodNameHavingBusyDBConnection();
429
        } catch (SQLException e) {
430
            logMetacat.error("Error in MetacatServlet.handleGetOrPost: "
431
                    + e.getMessage());
432
            e.printStackTrace();
433
        }
434

    
435
        String ctype = request.getContentType();
436
        if (ctype != null && ctype.startsWith("multipart/form-data")) {
437
            handleMultipartForm(request, response);
438
        } else {
439

    
440
            String name = null;
441
            String[] value = null;
442
            String[] docid = new String[3];
443
            Hashtable params = new Hashtable();
444
            Enumeration paramlist = request.getParameterNames();
445

    
446
            while (paramlist.hasMoreElements()) {
447

    
448
                name = (String) paramlist.nextElement();
449
                value = request.getParameterValues(name);
450

    
451
                // Decode the docid and mouse click information
452
                if (name.endsWith(".y")) {
453
                    docid[0] = name.substring(0, name.length() - 2);
454
                    params.put("docid", docid);
455
                    name = "ypos";
456
                }
457
                if (name.endsWith(".x")) {
458
                    name = "xpos";
459
                }
460

    
461
                params.put(name, value);
462
            }
463

    
464
            //handle param is emptpy
465
            if (params.isEmpty() || params == null) { return; }
466

    
467
            //if the user clicked on the input images, decode which image
468
            //was clicked then set the action.
469
            if(params.get("action") == null){
470
                PrintWriter out = response.getWriter();
471
                response.setContentType("text/xml");
472
                out.println("<?xml version=\"1.0\"?>");
473
                out.println("<error>");
474
                out.println("Action not specified");
475
                out.println("</error>");
476
                out.close();
477
                return;
478
            }
479

    
480
            String action = ((String[]) params.get("action"))[0];
481
            logMetacat.info("Action is: " + action);
482

    
483
            // This block handles session management for the servlet
484
            // by looking up the current session information for all actions
485
            // other than "login" and "logout"
486
            String username = null;
487
            String password = null;
488
            String[] groupnames = null;
489
            String sess_id = null;
490
            name = null;
491
            
492
            // handle login action
493
            if (action.equals("login")) {
494
                PrintWriter out = response.getWriter();
495
                handleLoginAction(out, params, request, response);
496
                out.close();
497
        
498
                // handle logout action
499
            }   else if (action.equals("logout")) {
500
                PrintWriter out = response.getWriter();
501
                handleLogoutAction(out, params, request, response);
502
                out.close();
503

    
504
                // handle shrink DBConnection request
505
            } else if (action.equals("shrink")) {
506
                PrintWriter out = response.getWriter();
507
                boolean success = false;
508
                //If all DBConnection in the pool are free and DBConnection
509
                // pool
510
                //size is greater than initial value, shrink the connection
511
                // pool
512
                //size to initial value
513
                success = DBConnectionPool.shrinkConnectionPoolSize();
514
                if (success) {
515
                    //if successfully shrink the pool size to initial value
516
                    out.println("DBConnection Pool shrunk successfully.");
517
                }//if
518
                else {
519
                    out.println("DBConnection pool not shrunk successfully.");
520
                }
521
                //close out put
522
                out.close();
523

    
524
                // aware of session expiration on every request
525
            } else {
526
                HttpSession sess = request.getSession(true);
527
                if (sess.isNew() && !params.containsKey("sessionid")) {
528
                    // session expired or has not been stored b/w user requests
529
                    logMetacat.info(
530
                            "The session is new or no sessionid is assigned. The user is public");
531
                    username = "public";
532
                    sess.setAttribute("username", username);
533
                } else {
534
                    logMetacat.info("The session is either old or "
535
                            + "has sessionid parameter");
536
                    try {
537
                        if (params.containsKey("sessionid")) {
538
                            sess_id = ((String[]) params.get("sessionid"))[0];
539
                            logMetacat.info("in has sessionid "
540
                                    + sess_id);
541
                            if (sessionHash.containsKey(sess_id)) {
542
                                logMetacat.info("find the id "
543
                                        + sess_id + " in hash table");
544
                                sess = (HttpSession) sessionHash.get(sess_id);
545
                            }
546
                        } else {
547
                            // we already store the session in login, so we
548
                            // don't need here
549
                            /*
550
                             * logMetacat.info("in no sessionid
551
                             * parameter ", 40); sess_id =
552
                             * (String)sess.getId();
553
                             * logMetacat.info("storing the session id "
554
                             * + sess_id + " which has username " +
555
                             * sess.getAttribute("username") + " into session
556
                             * hash in handleGetOrPost method", 35);
557
                             */
558
                        }
559
                    } catch (IllegalStateException ise) {
560
                        logMetacat.error(
561
                                "Error in handleGetOrPost: this shouldn't "
562
                                + "happen: the session should be valid: "
563
                                + ise.getMessage());
564
                    }
565

    
566
                    username = (String) sess.getAttribute("username");
567
                    logMetacat.info("The user name from session is: "
568
                            + username);
569
                    password = (String) sess.getAttribute("password");
570
                    groupnames = (String[]) sess.getAttribute("groupnames");
571
                    name = (String) sess.getAttribute("name");
572
                }
573

    
574
                //make user user username should be public
575
                if (username == null || (username.trim().equals(""))) {
576
                    username = "public";
577
                }
578
                logMetacat.info("The user is : " + username);
579
            }
580
            // Now that we know the session is valid, we can delegate the
581
            // request
582
            // to a particular action handler
583
            if (action.equals("query")) {
584
                PrintWriter out = response.getWriter();
585
                handleQuery(out, params, response, username, groupnames,
586
                        sess_id);
587
                out.close();
588
            } else if (action.equals("squery")) {
589
                PrintWriter out = response.getWriter();
590
                if (params.containsKey("query")) {
591
                    handleSQuery(out, params, response, username, groupnames,
592
                            sess_id);
593
                    out.close();
594
                } else {
595
                    out.println(
596
                            "Illegal action squery without \"query\" parameter");
597
                    out.close();
598
                }
599
            } else if ( action.trim().equals("spatial_query")) {
600

    
601
              logMetacat.debug("******************* SPATIAL QUERY ********************");
602
              PrintWriter out = response.getWriter();
603
              handleSpatialQuery(out, params, response, username, groupnames, sess_id);
604
              out.close();
605
            
606
            } else if (action.equals("export")) {
607

    
608
                handleExportAction(params, response, username,
609
                        groupnames, password);
610
            } else if (action.equals("read")) {
611
                handleReadAction(params, request, response, username, password,
612
                        groupnames);
613
            } else if (action.equals("readinlinedata")) {
614
                handleReadInlineDataAction(params, request, response, username,
615
                        password, groupnames);
616
            } else if (action.equals("insert") || action.equals("update")) {
617
                PrintWriter out = response.getWriter();
618
                if ((username != null) && !username.equals("public")) {
619
                    handleInsertOrUpdateAction(request, response,
620
                            out, params, username, groupnames);
621
                } else {
622
                    response.setContentType("text/xml");
623
                    out.println("<?xml version=\"1.0\"?>");
624
                    out.println("<error>");
625
                    out.println("Permission denied for user " + username + " "
626
                            + action);
627
                    out.println("</error>");
628
                }
629
                out.close();
630
            } else if (action.equals("delete")) {
631
                PrintWriter out = response.getWriter();
632
                if ((username != null) && !username.equals("public")) {
633
                    handleDeleteAction(out, params, request, response, username,
634
                            groupnames);
635
                } else {
636
                    response.setContentType("text/xml");
637
                    out.println("<?xml version=\"1.0\"?>");
638
                    out.println("<error>");
639
                    out.println("Permission denied for " + action);
640
                    out.println("</error>");
641
                }
642
                out.close();
643
            } else if (action.equals("validate")) {
644
                PrintWriter out = response.getWriter();
645
                handleValidateAction(out, params);
646
                out.close();
647
            } else if (action.equals("setaccess")) {
648
                PrintWriter out = response.getWriter();
649
                handleSetAccessAction(out, params, username);
650
                out.close();
651
            } else if (action.equals("getaccesscontrol")) {
652
                PrintWriter out = response.getWriter();
653
                handleGetAccessControlAction(out, params, response, username,
654
                        groupnames);
655
                out.close();
656
            } else if (action.equals("getprincipals")) {
657
                PrintWriter out = response.getWriter();
658
                handleGetPrincipalsAction(out, username, password);
659
                out.close();
660
            } else if (action.equals("getdoctypes")) {
661
                PrintWriter out = response.getWriter();
662
                handleGetDoctypesAction(out, params, response);
663
                out.close();
664
            } else if (action.equals("getdtdschema")) {
665
                PrintWriter out = response.getWriter();
666
                handleGetDTDSchemaAction(out, params, response);
667
                out.close();
668
            } else if (action.equals("getlastdocid")) {
669
                PrintWriter out = response.getWriter();
670
                handleGetMaxDocidAction(out, params, response);
671
                out.close();
672
            } else if (action.equals("getrevisionanddoctype")) {
673
                PrintWriter out = response.getWriter();
674
                handleGetRevisionAndDocTypeAction(out, params);
675
                out.close();
676
            } else if (action.equals("getversion")) {
677
                response.setContentType("text/xml");
678
                PrintWriter out = response.getWriter();
679
                out.println(Version.getVersionAsXml());
680
                out.close();
681
            } else if (action.equals("getlog")) {
682
                handleGetLogAction(params, request, response, username, groupnames);
683
            } else if (action.equals("getloggedinuserinfo")) {
684
                PrintWriter out = response.getWriter();
685
                response.setContentType("text/xml");
686
                out.println("<?xml version=\"1.0\"?>");
687
                out.println("\n<user>\n");
688
                out.println("\n<username>\n");
689
                out.println(username);
690
                out.println("\n</username>\n");
691
                if(name!=null){
692
                	out.println("\n<name>\n");
693
                	out.println(name);
694
                	out.println("\n</name>\n");
695
                }
696
                if(MetaCatUtil.isAdministrator(username, groupnames)){
697
                	out.println("<isAdministrator></isAdministrator>\n");	
698
                }
699
                if(MetaCatUtil.isModerator(username, groupnames)){
700
                	out.println("<isModerator></isModerator>\n");	
701
                }
702
                out.println("\n</user>\n");
703
                out.close();
704
            } else if (action.equals("buildindex")) {
705
                handleBuildIndexAction(params, request, response, username, groupnames);
706
            } else if (action.equals("login") || action.equals("logout")) {
707
                /*
708
            } else if (action.equals("protocoltest")) {
709
                String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
710
                try {
711
                    testURL = ((String[]) params.get("url"))[0];
712
                } catch (Throwable t) {
713
                }
714
                String phandler = System
715
                        .getProperty("java.protocol.handler.pkgs");
716
                response.setContentType("text/html");
717
                PrintWriter out = response.getWriter();
718
                out.println("<body bgcolor=\"white\">");
719
                out.println("<p>Handler property: <code>" + phandler
720
                        + "</code></p>");
721
                out.println("<p>Starting test for:<br>");
722
                out.println("    " + testURL + "</p>");
723
                try {
724
                    URL u = new URL(testURL);
725
                    out.println("<pre>");
726
                    out.println("Protocol: " + u.getProtocol());
727
                    out.println("    Host: " + u.getHost());
728
                    out.println("    Port: " + u.getPort());
729
                    out.println("    Path: " + u.getPath());
730
                    out.println("     Ref: " + u.getRef());
731
                    String pquery = u.getQuery();
732
                    out.println("   Query: " + pquery);
733
                    out.println("  Params: ");
734
                    if (pquery != null) {
735
                        Hashtable qparams = MetaCatUtil.parseQuery(u.getQuery());
736
                        for (Enumeration en = qparams.keys(); en
737
                                .hasMoreElements();) {
738
                            String pname = (String) en.nextElement();
739
                            String pvalue = (String) qparams.get(pname);
740
                            out.println("    " + pname + ": " + pvalue);
741
                        }
742
                    }
743
                    out.println("</pre>");
744
                    out.println("</body>");
745
                    out.close();
746
                } catch (MalformedURLException mue) {
747
                    System.out.println(
748
                            "bad url from MetacatServlet.handleGetOrPost");
749
                    out.println(mue.getMessage());
750
                    mue.printStackTrace(out);
751
                    out.close();
752
                }
753
                */
754
            } else {
755
                PrintWriter out = response.getWriter();
756
                out.println("<?xml version=\"1.0\"?>");
757
                out.println("<error>");
758
                out.println(
759
                     "Error: action not registered.  Please report this error.");
760
                out.println("</error>");
761
                out.close();
762
            }
763

    
764
            //util.closeConnections();
765
            // Close the stream to the client
766
            //out.close();
767
        }
768
    }
769

    
770
    /////////////////////////////// METACAT SPATIAL ///////////////////////////
771

    
772
    /**
773
     * handles all spatial queries -- these queries may include any of the 
774
     * queries supported by the WFS / WMS standards
775
     * 
776
     * handleSQuery(out, params, response, username, groupnames,
777
     *                        sess_id);
778
     */
779
    private void handleSpatialQuery(PrintWriter out, Hashtable params, 
780
                                    HttpServletResponse response,
781
                                    String username, String[] groupnames, 
782
                                    String sess_id) {
783
      
784
      Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
785
      //MBJDELETED MetacatSpatialQuery _spatialQuery = new MetacatSpatialQuery();
786

    
787
	if (MetacatSpatialConstants.runSpatialOption == false ) {
788
        	response.setContentType("text/html");
789
        	out.println("<html> Metacat Spatial Option is turned off <html>");
790
        	out.close();
791
		return ;
792
	}		
793
      
794
      MetacatSpatialQuery _spatialQuery = new MetacatSpatialQuery();
795
      
796
      
797
      // switch -- html/xml print
798
      //MBJDELETED boolean printXML = false; 
799
      
800
      // get the spatial parameters
801
      logMetacat.debug("params: " +  params);
802
      //String _xmax =  (String)params.get("XMAX");
803
      float _xmax = Float.parseFloat( ((String[]) params.get("XMAX"))[0] );
804
      float _ymax = Float.parseFloat( ((String[]) params.get("YMAX"))[0] );
805
      float _xmin = Float.parseFloat( ((String[]) params.get("XMIN"))[0] );
806
      float _ymin = Float.parseFloat( ((String[]) params.get("YMIN"))[0] );
807
      logMetacat.debug("\nxmax: " + _xmax + " \nymax:" + _ymax +
808
                      "\nxmin: " + _xmin + "\nymin: " + _ymin);
809

    
810
      // create an s-query
811
      String spatialQuery = createSpatialQuery(_xmin, _ymin, _xmax, _ymax);
812
      String[] queryArray = new String[1];
813
      queryArray[0] = spatialQuery;
814
      params.put("query", queryArray);
815

    
816
      // qformat
817
      String[] qformatArray = new String[1];
818
      try {
819
          String _skin = ((String[]) params.get("SKIN"))[0];
820
          qformatArray[0] = _skin;
821
      } catch (java.lang.NullPointerException e) {
822
          // should be "default" but keep this for backwards compatibility with knp site
823
          logMetacat.warn("No SKIN specified for metacat actions=spatial_query... defaulting to 'knp' skin !\n");
824
          qformatArray[0] = "knp";
825
      }
826
      params.put("qformat", qformatArray);
827

    
828
      // change the action
829
      String[] actionArray = new String[1];
830
      actionArray[0] = "squery";
831
      params.put("action", actionArray);
832

    
833
      handleSQuery(out, params, response, username, groupnames, sess_id);
834

    
835

    
836
/* MBJ DELETED -- using Metacat query instead
837
      // issue the Spatial query 
838
      //MBJ DELETED MetacatSpatialDataset _data =  
839
        //MBJ DELETED _spatialQuery.queryDatasetByCartesianBounds(_xmin, _ymin, _xmax, _ymax);
840

    
841
      // report the number of documents returned:
842
      //MBJ DELETED logMetacat.warn("\nThe number of documents in the BBOX query: " 
843
              //MBJ DELETED + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
844
     
845
if (  _data.size() > 0) { 
846
      logMetacat.warn("\nThe number of documents in the BBOX query: " 
847
              + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
848
     
849
      
850
      // create an s-query
851
      String[] queryArray = new String[1];
852
      queryArray[0] = DocumentIdQuery.createDocidQuery(_data.getDocidList());
853
      params.put("query", queryArray);
854
      
855
      // qformat        
856
      String[] qformatArray = new String[1];
857
      qformatArray[0] = "knp";
858
      params.put("qformat", qformatArray);
859

    
860
      // change the action 
861
      String[] actionArray = new String[1];
862
      actionArray[0] = "squery";
863
      params.put("action", actionArray);
864

    
865
      // return the list of docs and point at the spatial theme 
866
      if ( printXML) {
867
        response.setContentType("text/xml");
868
        out.println(_data.toXML() ); // write the data as xml
869
        out.close();
870
      } else {
871
        logMetacat.warn("username: " + username+"\nsession: "+sess_id);
872
        handleSQuery(out, params, response, username, groupnames, sess_id);  
873
      }
874
} else {
875
        response.setContentType("text/html");
876
        out.println("<html>No Datasets Selected <html>");
877
        out.close();
878
}
879
*/
880

    
881
    }
882

    
883
    /**
884
     * Create a metacat squery for spatial data coordinates.
885
     */
886
    private String createSpatialQuery(float _xmin, float _ymin, float _xmax, float _ymax) {
887
	StringBuffer sb = new StringBuffer();
888
	    
889
	sb.append("<pathquery version=\"1.2\">");
890
	sb.append("<querytitle>Untitled-Search-3</querytitle>");
891
	sb.append("<returndoctype>-//ecoinformatics.org//eml-dataset-2.0.0beta4//EN</returndoctype>");
892
	sb.append("<returndoctype>-//ecoinformatics.org//eml-dataset-2.0.0beta6//EN</returndoctype>");
893
	sb.append("<returndoctype>-//NCEAS//eml-dataset-2.0//EN</returndoctype>");
894
	sb.append("<returndoctype>-//NCEAS//resource//EN</returndoctype>");
895
	sb.append("<returndoctype>eml://ecoinformatics.org/eml-2.0.0</returndoctype>");
896
	sb.append("<returndoctype>eml://ecoinformatics.org/eml-2.0.1</returndoctype>");
897
	sb.append("<returndoctype>metadata</returndoctype>");
898
	sb.append("<returnfield>dataset/title</returnfield>");
899
	sb.append("<returnfield>originator/individualName/surName</returnfield>");
900
	sb.append("<returnfield>originator/individualName/givenName</returnfield>");
901
	sb.append("<returnfield>originator/organizationName</returnfield>");
902
	sb.append("<returnfield>creator/individualName/surName</returnfield>");
903
	sb.append("<returnfield>creator/individualName/givenName</returnfield>");
904
	sb.append("<returnfield>creator/organizationName</returnfield>");
905
	sb.append("<returnfield>keyword</returnfield>");
906
	sb.append("<returnfield>entityName</returnfield>");
907
	sb.append("<returnfield>idinfo/citation/citeinfo/title</returnfield>");
908
	sb.append("<returnfield>idinfo/citation/citeinfo/origin</returnfield>");
909
	sb.append("<returnfield>idinfo/keywords/theme/themekey</returnfield>");
910
	sb.append("<querygroup operator=\"INTERSECT\">");
911
	sb.append("<queryterm searchmode=\"greater-than\" casesensitive=\"false\">");
912
	sb.append("<value>" + _ymin + "</value>");
913
	sb.append("<pathexpr>northBoundingCoordinate</pathexpr>");
914
	sb.append("</queryterm>");
915
	sb.append("<queryterm searchmode=\"less-than\" casesensitive=\"false\">");
916
	sb.append("<value>" + _ymax + "</value>");
917
	sb.append("<pathexpr>southBoundingCoordinate</pathexpr>");
918
	sb.append("</queryterm>");
919
	sb.append("<queryterm searchmode=\"greater-than\" casesensitive=\"false\">");
920
	sb.append("<value>" + _xmin + "</value>");
921
	sb.append("<pathexpr>eastBoundingCoordinate</pathexpr>");
922
	sb.append("</queryterm>");
923
 	sb.append("<queryterm searchmode=\"less-than\" casesensitive=\"false\">");
924
	sb.append("<value>" + _xmax + "</value>");
925
	sb.append("<pathexpr>westBoundingCoordinate</pathexpr>");
926
	sb.append("</queryterm>");
927
	sb.append("</querygroup>");
928
	sb.append("</pathquery>");
929

    
930
	return sb.toString();
931
    }
932

    
933
    // LOGIN & LOGOUT SECTION
934
    /**
935
     * Handle the login request. Create a new session object. Do user
936
     * authentication through the session.
937
     */
938
    private void handleLoginAction(PrintWriter out, Hashtable params,
939
            HttpServletRequest request, HttpServletResponse response)
940
    {
941
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
942
        AuthSession sess = null;
943

    
944
        if(params.get("username") == null){
945
            response.setContentType("text/xml");
946
            out.println("<?xml version=\"1.0\"?>");
947
            out.println("<error>");
948
            out.println("Username not specified");
949
            out.println("</error>");
950
            return;
951
        }
952

    
953
        //}
954

    
955
        if(params.get("password") == null){
956
            response.setContentType("text/xml");
957
            out.println("<?xml version=\"1.0\"?>");
958
            out.println("<error>");
959
            out.println("Password not specified");
960
            out.println("</error>");
961
            return;
962
        }
963

    
964
        String un = ((String[]) params.get("username"))[0];
965
        logMetacat.info("user " + un + " is trying to login");
966
        String pw = ((String[]) params.get("password"))[0];
967

    
968
        String qformat = "xml";
969
        if(params.get("qformat") != null){
970
            qformat = ((String[]) params.get("qformat"))[0];
971
        }
972

    
973
        try {
974
            sess = new AuthSession();
975
        } catch (Exception e) {
976
            System.out.println("error in MetacatServlet.handleLoginAction: "
977
                    + e.getMessage());
978
            out.println(e.getMessage());
979
            return;
980
        }
981
        boolean isValid = sess.authenticate(request, un, pw);
982

    
983
        //if it is authernticate is true, store the session
984
        if (isValid) {
985
            HttpSession session = sess.getSessions();
986
            String id = session.getId();
987
            logMetacat.info("Store session id " + id
988
                    + "which has username" + session.getAttribute("username")
989
                    + " into hash in login method");
990
            sessionHash.put(id, session);
991
        }
992

    
993
        // format and transform the output
994
        if (qformat.equals("xml")) {
995
            response.setContentType("text/xml");
996
            out.println(sess.getMessage());
997
        } else {
998
            try {
999
                DBTransform trans = new DBTransform();
1000
                response.setContentType("text/html");
1001
                trans.transformXMLDocument(sess.getMessage(),
1002
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1003
                        out, null);
1004
            } catch (Exception e) {
1005

    
1006
                logMetacat.error(
1007
                        "Error in MetaCatServlet.handleLoginAction: "
1008
                                + e.getMessage());
1009
            }
1010
        }
1011
    }
1012

    
1013
    /**
1014
     * Handle the logout request. Close the connection.
1015
     */
1016
    private void handleLogoutAction(PrintWriter out, Hashtable params,
1017
            HttpServletRequest request, HttpServletResponse response)
1018
    {
1019
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1020
        String qformat = "xml";
1021
        if(params.get("qformat") != null){
1022
            qformat = ((String[]) params.get("qformat"))[0];
1023
        }
1024

    
1025
        // close the connection
1026
        HttpSession sess = request.getSession(false);
1027
        logMetacat.info("After get session in logout request");
1028
        if (sess != null) {
1029
            logMetacat.info("The session id " + sess.getId()
1030
                    + " will be invalidate in logout action");
1031
            logMetacat.info("The session contains user "
1032
                    + sess.getAttribute("username")
1033
                    + " will be invalidate in logout action");
1034
            sess.invalidate();
1035
        }
1036

    
1037
        // produce output
1038
        StringBuffer output = new StringBuffer();
1039
        output.append("<?xml version=\"1.0\"?>");
1040
        output.append("<logout>");
1041
        output.append("User logged out");
1042
        output.append("</logout>");
1043

    
1044
        //format and transform the output
1045
        if (qformat.equals("xml")) {
1046
            response.setContentType("text/xml");
1047
            out.println(output.toString());
1048
        } else {
1049
            try {
1050
                DBTransform trans = new DBTransform();
1051
                response.setContentType("text/html");
1052
                trans.transformXMLDocument(output.toString(),
1053
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1054
                        out, null);
1055
            } catch (Exception e) {
1056
                logMetacat.error(
1057
                        "Error in MetaCatServlet.handleLogoutAction"
1058
                                + e.getMessage());
1059
            }
1060
        }
1061
    }
1062

    
1063
    // END OF LOGIN & LOGOUT SECTION
1064

    
1065
    // SQUERY & QUERY SECTION
1066
    /**
1067
     * Retreive the squery xml, execute it and display it
1068
     *
1069
     * @param out the output stream to the client
1070
     * @param params the Hashtable of parameters that should be included in the
1071
     *            squery.
1072
     * @param response the response object linked to the client
1073
     * @param conn the database connection
1074
     */
1075
    private void handleSQuery(PrintWriter out, Hashtable params,
1076
            HttpServletResponse response, String user, String[] groups,
1077
            String sessionid)
1078
    {
1079
        double startTime = System.currentTimeMillis() / 1000;
1080
        DBQuery queryobj = new DBQuery();
1081
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1082
        double outPutTime = System.currentTimeMillis() / 1000;
1083
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1084
        logMetacat.info("Total search time for action 'squery': "
1085
                + (outPutTime - startTime));
1086
    }
1087

    
1088
    /**
1089
     * Create the xml query, execute it and display the results.
1090
     *
1091
     * @param out the output stream to the client
1092
     * @param params the Hashtable of parameters that should be included in the
1093
     *            squery.
1094
     * @param response the response object linked to the client
1095
     */
1096
    private void handleQuery(PrintWriter out, Hashtable params,
1097
            HttpServletResponse response, String user, String[] groups,
1098
            String sessionid)
1099
    {
1100
        //create the query and run it
1101
        String xmlquery = DBQuery.createSQuery(params);
1102
        String[] queryArray = new String[1];
1103
        queryArray[0] = xmlquery;
1104
        params.put("query", queryArray);
1105
        double startTime = System.currentTimeMillis() / 1000;
1106
        DBQuery queryobj = new DBQuery();
1107
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1108
        double outPutTime = System.currentTimeMillis() / 1000;
1109
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1110
        logMetacat.info("Total search time for action 'query': "
1111
                + (outPutTime - startTime));
1112

    
1113
        //handleSQuery(out, params, response,user, groups, sessionid);
1114
    }
1115

    
1116
    // END OF SQUERY & QUERY SECTION
1117

    
1118
    //Exoport section
1119
    /**
1120
     * Handle the "export" request of data package from Metacat in zip format
1121
     *
1122
     * @param params the Hashtable of HTTP request parameters
1123
     * @param response the HTTP response object linked to the client
1124
     * @param user the username sent the request
1125
     * @param groups the user's groupnames
1126
     */
1127
    private void handleExportAction(Hashtable params,
1128
            HttpServletResponse response,
1129
            String user, String[] groups, String passWord)
1130
    {
1131
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1132
        // Output stream
1133
        ServletOutputStream out = null;
1134
        // Zip output stream
1135
        ZipOutputStream zOut = null;
1136
        DBQuery queryObj = null;
1137

    
1138
        String[] docs = new String[10];
1139
        String docId = "";
1140

    
1141
        try {
1142
            // read the params
1143
            if (params.containsKey("docid")) {
1144
                docs = (String[]) params.get("docid");
1145
            }
1146
            // Create a DBuery to handle export
1147
            queryObj = new DBQuery();
1148
            // Get the docid
1149
            docId = docs[0];
1150
            // Make sure the client specify docid
1151
            if (docId == null || docId.equals("")) {
1152
                response.setContentType("text/xml"); //MIME type
1153
                // Get a printwriter
1154
                PrintWriter pw = response.getWriter();
1155
                // Send back message
1156
                pw.println("<?xml version=\"1.0\"?>");
1157
                pw.println("<error>");
1158
                pw.println("You didn't specify requested docid");
1159
                pw.println("</error>");
1160
                // Close printwriter
1161
                pw.close();
1162
                return;
1163
            }
1164
            // Get output stream
1165
            out = response.getOutputStream();
1166
            response.setContentType("application/zip"); //MIME type
1167
            response.setHeader("Content-Disposition", 
1168
            		"attachment; filename=" 
1169
            		+ docId + ".zip"); // Set the name of the zip file
1170
            		
1171
            zOut = new ZipOutputStream(out);
1172
            zOut = queryObj
1173
                    .getZippedPackage(docId, out, user, groups, passWord);
1174
            zOut.finish(); //terminate the zip file
1175
            zOut.close(); //close the zip stream
1176

    
1177
        } catch (Exception e) {
1178
            try {
1179
                response.setContentType("text/xml"); //MIME type
1180
                // Send error message back
1181
                if (out != null) {
1182
                    PrintWriter pw = new PrintWriter(out);
1183
                    pw.println("<?xml version=\"1.0\"?>");
1184
                    pw.println("<error>");
1185
                    pw.println(e.getMessage());
1186
                    pw.println("</error>");
1187
                    // Close printwriter
1188
                    pw.close();
1189
                    // Close output stream
1190
                    out.close();
1191
                }
1192
                // Close zip output stream
1193
                if (zOut != null) {
1194
                    zOut.close();
1195
                }
1196
            } catch (IOException ioe) {
1197
                logMetacat.error("Problem with the servlet output "
1198
                        + "in MetacatServlet.handleExportAction: "
1199
                        + ioe.getMessage());
1200
            }
1201

    
1202
            logMetacat.error(
1203
                    "Error in MetacatServlet.handleExportAction: "
1204
                            + e.getMessage());
1205
            e.printStackTrace(System.out);
1206

    
1207
        }
1208

    
1209
    }
1210

    
1211
    /**
1212
     * In eml2 document, the xml can have inline data and data was stripped off
1213
     * and store in file system. This action can be used to read inline data
1214
     * only
1215
     *
1216
     * @param params the Hashtable of HTTP request parameters
1217
     * @param response the HTTP response object linked to the client
1218
     * @param user the username sent the request
1219
     * @param groups the user's groupnames
1220
     */
1221
    private void handleReadInlineDataAction(Hashtable params,
1222
            HttpServletRequest request, HttpServletResponse response,
1223
            String user, String passWord, String[] groups)
1224
    {
1225
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1226
        String[] docs = new String[10];
1227
        String inlineDataId = null;
1228
        String docId = "";
1229
        ServletOutputStream out = null;
1230

    
1231
        try {
1232
            // read the params
1233
            if (params.containsKey("inlinedataid")) {
1234
                docs = (String[]) params.get("inlinedataid");
1235
            }
1236
            // Get the docid
1237
            inlineDataId = docs[0];
1238
            // Make sure the client specify docid
1239
            if (inlineDataId == null || inlineDataId.equals("")) {
1240
                throw new Exception("You didn't specify requested inlinedataid"); }
1241

    
1242
            // check for permission
1243
            docId = MetaCatUtil
1244
                    .getDocIdWithoutRevFromInlineDataID(inlineDataId);
1245
            PermissionController controller = new PermissionController(docId);
1246
            // check top level read permission
1247
            if (!controller.hasPermission(user, groups,
1248
                    AccessControlInterface.READSTRING))
1249
            {
1250
                throw new Exception("User " + user
1251
                        + " doesn't have permission " + " to read document "
1252
                        + docId);
1253
            }
1254
            else
1255
            {
1256
              //check data access level
1257
              try
1258
              {
1259
                Hashtable unReadableInlineDataList =
1260
                    PermissionController.getUnReadableInlineDataIdList(docId,
1261
                    user, groups, false);
1262
                if (unReadableInlineDataList.containsValue(
1263
                          MetaCatUtil.getInlineDataIdWithoutRev(inlineDataId)))
1264
                {
1265
                  throw new Exception("User " + user
1266
                       + " doesn't have permission " + " to read inlinedata "
1267
                       + inlineDataId);
1268

    
1269
                }//if
1270
              }//try
1271
              catch (Exception e)
1272
              {
1273
                throw e;
1274
              }//catch
1275
            }//else
1276

    
1277
            // Get output stream
1278
            out = response.getOutputStream();
1279
            // read the inline data from the file
1280
            String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
1281
            File lineData = new File(inlinePath, inlineDataId);
1282
            FileInputStream input = new FileInputStream(lineData);
1283
            byte[] buffer = new byte[4 * 1024];
1284
            int bytes = input.read(buffer);
1285
            while (bytes != -1) {
1286
                out.write(buffer, 0, bytes);
1287
                bytes = input.read(buffer);
1288
            }
1289
            out.close();
1290

    
1291
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1292
                    inlineDataId, "readinlinedata");
1293
        } catch (Exception e) {
1294
            try {
1295
                PrintWriter pw = null;
1296
                // Send error message back
1297
                if (out != null) {
1298
                    pw = new PrintWriter(out);
1299
                } else {
1300
                    pw = response.getWriter();
1301
                }
1302
                pw.println("<?xml version=\"1.0\"?>");
1303
                pw.println("<error>");
1304
                pw.println(e.getMessage());
1305
                pw.println("</error>");
1306
                // Close printwriter
1307
                pw.close();
1308
                // Close output stream if out is not null
1309
                if (out != null) {
1310
                    out.close();
1311
                }
1312
            } catch (IOException ioe) {
1313
                logMetacat.error("Problem with the servlet output "
1314
                        + "in MetacatServlet.handleExportAction: "
1315
                        + ioe.getMessage());
1316
            }
1317
            logMetacat.error(
1318
                    "Error in MetacatServlet.handleReadInlineDataAction: "
1319
                            + e.getMessage());
1320
        }
1321
    }
1322

    
1323
    /*
1324
     * Get the nodeid from xml_nodes for the inlinedataid
1325
     */
1326
    private long getInlineDataNodeId(String inLineDataId, String docId)
1327
            throws SQLException
1328
    {
1329
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1330
        long nodeId = 0;
1331
        String INLINE = "inline";
1332
        boolean hasRow;
1333
        PreparedStatement pStmt = null;
1334
        DBConnection conn = null;
1335
        int serialNumber = -1;
1336
        String sql = "SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? "
1337
                + "AND nodetype='TEXT' AND parentnodeid IN "
1338
                + "(SELECT nodeid FROM xml_nodes WHERE docid=? AND "
1339
                + "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
1340

    
1341
        try {
1342
            //check out DBConnection
1343
            conn = DBConnectionPool
1344
                    .getDBConnection("AccessControlList.isAllowFirst");
1345
            serialNumber = conn.getCheckOutSerialNumber();
1346

    
1347
            pStmt = conn.prepareStatement(sql);
1348
            //bind value
1349
            pStmt.setString(1, docId);//docid
1350
            pStmt.setString(2, inLineDataId);//inlinedataid
1351
            pStmt.setString(3, docId);
1352
            // excute query
1353
            pStmt.execute();
1354
            ResultSet rs = pStmt.getResultSet();
1355
            hasRow = rs.next();
1356
            // get result
1357
            if (hasRow) {
1358
                nodeId = rs.getLong(1);
1359
            }//if
1360

    
1361
        } catch (SQLException e) {
1362
            throw e;
1363
        } finally {
1364
            try {
1365
                pStmt.close();
1366
            } finally {
1367
                DBConnectionPool.returnDBConnection(conn, serialNumber);
1368
            }
1369
        }
1370
        logMetacat.debug("The nodeid for inlinedataid " + inLineDataId
1371
                + " is: " + nodeId);
1372
        return nodeId;
1373
    }
1374

    
1375
    /**
1376
     * Handle the "read" request of metadata/data files from Metacat or any
1377
     * files from Internet; transformed metadata XML document into HTML
1378
     * presentation if requested; zip files when more than one were requested.
1379
     *
1380
     * @param params the Hashtable of HTTP request parameters
1381
     * @param request the HTTP request object linked to the client
1382
     * @param response the HTTP response object linked to the client
1383
     * @param user the username sent the request
1384
     * @param groups the user's groupnames
1385
     */
1386
    private void handleReadAction(Hashtable params, HttpServletRequest request,
1387
            HttpServletResponse response, String user, String passWord,
1388
            String[] groups)
1389
    {
1390
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1391
        ServletOutputStream out = null;
1392
        ZipOutputStream zout = null;
1393
        PrintWriter pw = null;
1394
        boolean zip = false;
1395
        boolean withInlineData = true;
1396

    
1397
        try {
1398
            String[] docs = new String[0];
1399
            String docid = "";
1400
            String qformat = "";
1401
            String abstrpath = null;
1402

    
1403
            // read the params
1404
            if (params.containsKey("docid")) {
1405
                docs = (String[]) params.get("docid");
1406
            }
1407
            if (params.containsKey("qformat")) {
1408
                qformat = ((String[]) params.get("qformat"))[0];
1409
            }
1410
            // the param for only metadata (eml)
1411
            // we don't support read a eml document without inline data now.
1412
            /*if (params.containsKey("inlinedata")) {
1413

    
1414
                String inlineData = ((String[]) params.get("inlinedata"))[0];
1415
                if (inlineData.equalsIgnoreCase("false")) {
1416
                    withInlineData = false;
1417
                }
1418
            }*/
1419
            if ((docs.length > 1) || qformat.equals("zip")) {
1420
                zip = true;
1421
                out = response.getOutputStream();
1422
                response.setContentType("application/zip"); //MIME type
1423
                zout = new ZipOutputStream(out);
1424
            }
1425
            // go through the list of docs to read
1426
            for (int i = 0; i < docs.length; i++) {
1427
                try {
1428

    
1429
                    URL murl = new URL(docs[i]);
1430
                    Hashtable murlQueryStr = MetaCatUtil.parseQuery(
1431
                            murl.getQuery());
1432
                    // case docid="http://.../?docid=aaa"
1433
                    // or docid="metacat://.../?docid=bbb"
1434
                    if (murlQueryStr.containsKey("docid")) {
1435
                        // get only docid, eliminate the rest
1436
                        docid = (String) murlQueryStr.get("docid");
1437
                        if (zip) {
1438
                            addDocToZip(request, docid, zout, user, groups);
1439
                        } else {
1440
                            readFromMetacat(request, response, docid, qformat,
1441
                                    abstrpath, user, groups, zip, zout,
1442
                                    withInlineData, params);
1443
                        }
1444

    
1445
                        // case docid="http://.../filename"
1446
                    } else {
1447
                        docid = docs[i];
1448
                        if (zip) {
1449
                            addDocToZip(request, docid, zout, user, groups);
1450
                        } else {
1451
                            readFromURLConnection(response, docid);
1452
                        }
1453
                    }
1454

    
1455
                } catch (MalformedURLException mue) {
1456
                    docid = docs[i];
1457
                    if (zip) {
1458
                        addDocToZip(request, docid, zout, user, groups);
1459
                    } else {
1460
                        readFromMetacat(request, response, docid, qformat,
1461
                                abstrpath, user, groups, zip, zout,
1462
                                withInlineData, params);
1463
                    }
1464
                }
1465
            }
1466

    
1467
            if (zip) {
1468
                zout.finish(); //terminate the zip file
1469
                zout.close(); //close the zip stream
1470
            }
1471

    
1472
        } catch (McdbDocNotFoundException notFoundE) {
1473
            // To handle doc not found exception
1474
            // the docid which didn't be found
1475
            String notFoundDocId = notFoundE.getUnfoundDocId();
1476
            String notFoundRevision = notFoundE.getUnfoundRevision();
1477
            logMetacat.warn("Missed id: " + notFoundDocId);
1478
            logMetacat.warn("Missed rev: " + notFoundRevision);
1479
            try {
1480
                // read docid from remote server
1481
                readFromRemoteMetaCat(response, notFoundDocId,
1482
                        notFoundRevision, user, passWord, out, zip, zout);
1483
                // Close zout outputstream
1484
                if (zout != null) {
1485
                    zout.close();
1486
                }
1487
                // close output stream
1488
                if (out != null) {
1489
                    out.close();
1490
                }
1491

    
1492
            } catch (Exception exc) {
1493
                logMetacat.error(
1494
                        "Erorr in MetacatServlet.hanldReadAction: "
1495
                                + exc.getMessage());
1496
                try {
1497
                    if (out != null) {
1498
                        response.setContentType("text/xml");
1499
                        // Send back error message by printWriter
1500
                        pw = new PrintWriter(out);
1501
                        pw.println("<?xml version=\"1.0\"?>");
1502
                        pw.println("<error>");
1503
                        pw.println(notFoundE.getMessage());
1504
                        pw.println("</error>");
1505
                        pw.close();
1506
                        out.close();
1507

    
1508
                    } else {
1509
                        response.setContentType("text/xml"); //MIME type
1510
                        // Send back error message if out = null
1511
                        if (pw == null) {
1512
                            // If pw is null, open the respnose
1513
                            pw = response.getWriter();
1514
                        }
1515
                        pw.println("<?xml version=\"1.0\"?>");
1516
                        pw.println("<error>");
1517
                        pw.println(notFoundE.getMessage());
1518
                        pw.println("</error>");
1519
                        pw.close();
1520
                    }
1521
                    // close zout
1522
                    if (zout != null) {
1523
                        zout.close();
1524
                    }
1525
                } catch (IOException ie) {
1526
                    logMetacat.error("Problem with the servlet output "
1527
                            + "in MetacatServlet.handleReadAction: "
1528
                            + ie.getMessage());
1529
                }
1530
            }
1531
        } catch (Exception e) {
1532
            try {
1533

    
1534
                if (out != null) {
1535
                    response.setContentType("text/xml"); //MIME type
1536
                    pw = new PrintWriter(out);
1537
                    pw.println("<?xml version=\"1.0\"?>");
1538
                    pw.println("<error>");
1539
                    pw.println(e.getMessage());
1540
                    pw.println("</error>");
1541
                    pw.close();
1542
                    out.close();
1543
                } else {
1544
                    response.setContentType("text/xml"); //MIME type
1545
                    // Send back error message if out = null
1546
                    if (pw == null) {
1547
                        pw = response.getWriter();
1548
                    }
1549
                    pw.println("<?xml version=\"1.0\"?>");
1550
                    pw.println("<error>");
1551
                    pw.println(e.getMessage());
1552
                    pw.println("</error>");
1553
                    pw.close();
1554

    
1555
                }
1556
                // Close zip output stream
1557
                if (zout != null) {
1558
                    zout.close();
1559
                }
1560

    
1561
            } catch (IOException ioe) {
1562
                logMetacat.error("Problem with the servlet output "
1563
                        + "in MetacatServlet.handleReadAction: "
1564
                        + ioe.getMessage());
1565
                ioe.printStackTrace(System.out);
1566

    
1567
            }
1568

    
1569
            logMetacat.error(
1570
                    "Error in MetacatServlet.handleReadAction: "
1571
                            + e.getMessage());
1572
            //e.printStackTrace(System.out);
1573
        }
1574
    }
1575

    
1576
    /** read metadata or data from Metacat
1577
     */
1578
    private void readFromMetacat(HttpServletRequest request,
1579
            HttpServletResponse response, String docid, String qformat,
1580
            String abstrpath, String user, String[] groups, boolean zip,
1581
            ZipOutputStream zout, boolean withInlineData, Hashtable params)
1582
            throws ClassNotFoundException, IOException, SQLException,
1583
            McdbException, Exception
1584
    {
1585
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1586
        try {
1587
            
1588
            // here is hack for handle docid=john.10(in order to tell mike.jim.10.1
1589
            // mike.jim.10, we require to provide entire docid with rev). But
1590
            // some old client they only provide docid without rev, so we need
1591
            // to handle this suituation. First we will check how many
1592
            // seperator here, if only one, we will append the rev in xml_documents
1593
            // to the id.
1594
            docid = appendRev(docid);
1595
         
1596
            DocumentImpl doc = new DocumentImpl(docid);
1597

    
1598
            //check the permission for read
1599
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1600
                Exception e = new Exception("User " + user
1601
                        + " does not have permission"
1602
                        + " to read the document with the docid " + docid);
1603

    
1604
                throw e;
1605
            }
1606

    
1607
            if (doc.getRootNodeID() == 0) {
1608
                // this is data file
1609
                String filepath = MetaCatUtil.getOption("datafilepath");
1610
                if (!filepath.endsWith("/")) {
1611
                    filepath += "/";
1612
                }
1613
                String filename = filepath + docid;
1614
                FileInputStream fin = null;
1615
                fin = new FileInputStream(filename);
1616

    
1617
                //MIME type
1618
                String contentType = getServletContext().getMimeType(filename);
1619
                if (contentType == null) {
1620
                    ContentTypeProvider provider = new ContentTypeProvider(
1621
                            docid);
1622
                    contentType = provider.getContentType();
1623
                    logMetacat.info("Final contenttype is: "
1624
                            + contentType);
1625
                }
1626

    
1627
                response.setContentType(contentType);
1628
                // if we decide to use "application/octet-stream" for all data
1629
                // returns
1630
                // response.setContentType("application/octet-stream");
1631

    
1632
                try {
1633

    
1634
                    ServletOutputStream out = response.getOutputStream();
1635
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
1636
                    int b = fin.read(buf);
1637
                    while (b != -1) {
1638
                        out.write(buf, 0, b);
1639
                        b = fin.read(buf);
1640
                    }
1641
                } finally {
1642
                    if (fin != null) fin.close();
1643
                }
1644

    
1645
            } else {
1646
                // this is metadata doc
1647
                if (qformat.equals("xml") || qformat.equals("")) {
1648
                    // if equals "", that means no qformat is specified. hence
1649
                    // by default the document should be returned in xml format
1650
                    // set content type first
1651
                    response.setContentType("text/xml"); //MIME type
1652
                    PrintWriter out = response.getWriter();
1653
                    doc.toXml(out, user, groups, withInlineData);
1654
                } else {
1655
                    response.setContentType("text/html"); //MIME type
1656
                    PrintWriter out = response.getWriter();
1657

    
1658
                    // Look up the document type
1659
                    String doctype = doc.getDoctype();
1660
                    // Transform the document to the new doctype
1661
                    DBTransform dbt = new DBTransform();
1662
                    dbt.transformXMLDocument(doc.toString(user, groups,
1663
                            withInlineData), doctype, "-//W3C//HTML//EN",
1664
                            qformat, out, params);
1665
                }
1666

    
1667
            }
1668
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1669
                    docid, "read");
1670
        } catch (Exception except) {
1671
            throw except;
1672
        }
1673
    }
1674

    
1675
    /**
1676
     * read data from URLConnection
1677
     */
1678
    private void readFromURLConnection(HttpServletResponse response,
1679
            String docid) throws IOException, MalformedURLException
1680
    {
1681
        ServletOutputStream out = response.getOutputStream();
1682
        String contentType = getServletContext().getMimeType(docid); //MIME
1683
                                                                     // type
1684
        if (contentType == null) {
1685
            if (docid.endsWith(".xml")) {
1686
                contentType = "text/xml";
1687
            } else if (docid.endsWith(".css")) {
1688
                contentType = "text/css";
1689
            } else if (docid.endsWith(".dtd")) {
1690
                contentType = "text/plain";
1691
            } else if (docid.endsWith(".xsd")) {
1692
                contentType = "text/xml";
1693
            } else if (docid.endsWith("/")) {
1694
                contentType = "text/html";
1695
            } else {
1696
                File f = new File(docid);
1697
                if (f.isDirectory()) {
1698
                    contentType = "text/html";
1699
                } else {
1700
                    contentType = "application/octet-stream";
1701
                }
1702
            }
1703
        }
1704
        response.setContentType(contentType);
1705
        // if we decide to use "application/octet-stream" for all data returns
1706
        // response.setContentType("application/octet-stream");
1707

    
1708
        // this is http url
1709
        URL url = new URL(docid);
1710
        BufferedInputStream bis = null;
1711
        try {
1712
            bis = new BufferedInputStream(url.openStream());
1713
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1714
            int b = bis.read(buf);
1715
            while (b != -1) {
1716
                out.write(buf, 0, b);
1717
                b = bis.read(buf);
1718
            }
1719
        } finally {
1720
            if (bis != null) bis.close();
1721
        }
1722

    
1723
    }
1724

    
1725
    /**
1726
     * read file/doc and write to ZipOutputStream
1727
     *
1728
     * @param docid
1729
     * @param zout
1730
     * @param user
1731
     * @param groups
1732
     * @throws ClassNotFoundException
1733
     * @throws IOException
1734
     * @throws SQLException
1735
     * @throws McdbException
1736
     * @throws Exception
1737
     */
1738
    private void addDocToZip(HttpServletRequest request, String docid,
1739
            ZipOutputStream zout, String user, String[] groups) throws
1740
            ClassNotFoundException, IOException, SQLException, McdbException,
1741
            Exception
1742
    {
1743
        byte[] bytestring = null;
1744
        ZipEntry zentry = null;
1745

    
1746
        try {
1747
            URL url = new URL(docid);
1748

    
1749
            // this http url; read from URLConnection; add to zip
1750
            zentry = new ZipEntry(docid);
1751
            zout.putNextEntry(zentry);
1752
            BufferedInputStream bis = null;
1753
            try {
1754
                bis = new BufferedInputStream(url.openStream());
1755
                byte[] buf = new byte[4 * 1024]; // 4K buffer
1756
                int b = bis.read(buf);
1757
                while (b != -1) {
1758
                    zout.write(buf, 0, b);
1759
                    b = bis.read(buf);
1760
                }
1761
            } finally {
1762
                if (bis != null) bis.close();
1763
            }
1764
            zout.closeEntry();
1765

    
1766
        } catch (MalformedURLException mue) {
1767

    
1768
            // this is metacat doc (data file or metadata doc)
1769
            try {
1770
                DocumentImpl doc = new DocumentImpl(docid);
1771

    
1772
                //check the permission for read
1773
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1774
                    Exception e = new Exception("User " + user
1775
                            + " does not have "
1776
                            + "permission to read the document with the docid "
1777
                            + docid);
1778
                    throw e;
1779
                }
1780

    
1781
                if (doc.getRootNodeID() == 0) {
1782
                    // this is data file; add file to zip
1783
                    String filepath = MetaCatUtil.getOption("datafilepath");
1784
                    if (!filepath.endsWith("/")) {
1785
                        filepath += "/";
1786
                    }
1787
                    String filename = filepath + docid;
1788
                    FileInputStream fin = null;
1789
                    fin = new FileInputStream(filename);
1790
                    try {
1791

    
1792
                        zentry = new ZipEntry(docid);
1793
                        zout.putNextEntry(zentry);
1794
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
1795
                        int b = fin.read(buf);
1796
                        while (b != -1) {
1797
                            zout.write(buf, 0, b);
1798
                            b = fin.read(buf);
1799
                        }
1800
                    } finally {
1801
                        if (fin != null) fin.close();
1802
                    }
1803
                    zout.closeEntry();
1804

    
1805
                } else {
1806
                    // this is metadata doc; add doc to zip
1807
                    bytestring = doc.toString().getBytes();
1808
                    zentry = new ZipEntry(docid + ".xml");
1809
                    zentry.setSize(bytestring.length);
1810
                    zout.putNextEntry(zentry);
1811
                    zout.write(bytestring, 0, bytestring.length);
1812
                    zout.closeEntry();
1813
                }
1814
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1815
                        docid, "read");
1816
            } catch (Exception except) {
1817
                throw except;
1818
            }
1819
        }
1820
    }
1821

    
1822
    /**
1823
     * If metacat couldn't find a data file or document locally, it will read
1824
     * this docid from its home server. This is for the replication feature
1825
     */
1826
    private void readFromRemoteMetaCat(HttpServletResponse response,
1827
            String docid, String rev, String user, String password,
1828
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
1829
            throws Exception
1830
    {
1831
        // Create a object of RemoteDocument, "" is for zipEntryPath
1832
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
1833
                password, "");
1834
        String docType = remoteDoc.getDocType();
1835
        // Only read data file
1836
        if (docType.equals("BIN")) {
1837
            // If it is zip format
1838
            if (zip) {
1839
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
1840
            } else {
1841
                if (out == null) {
1842
                    out = response.getOutputStream();
1843
                }
1844
                response.setContentType("application/octet-stream");
1845
                remoteDoc.readDocumentFromRemoteServer(out);
1846
            }
1847
        } else {
1848
            throw new Exception("Docid: " + docid + "." + rev
1849
                    + " couldn't find");
1850
        }
1851
    }
1852

    
1853
    /**
1854
     * Handle the database putdocument request and write an XML document to the
1855
     * database connection
1856
     */
1857
    private void handleInsertOrUpdateAction(HttpServletRequest request,
1858
            HttpServletResponse response, PrintWriter out, Hashtable params,
1859
            String user, String[] groups)
1860
    {
1861
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1862
        DBConnection dbConn = null;
1863
        int serialNumber = -1;
1864

    
1865
        if(params.get("docid") == null){
1866
            out.println("<?xml version=\"1.0\"?>");
1867
            out.println("<error>");
1868
            out.println("Docid not specified");
1869
            out.println("</error>");
1870
            logMetacat.error("Docid not specified");
1871
            return;
1872
        }
1873
        
1874
        if(!MetaCatUtil.canInsertOrUpdate(user, groups)){
1875
        	out.println("<?xml version=\"1.0\"?>");
1876
            out.println("<error>");
1877
            out.println("User '" + user + "' not allowed to insert and update");
1878
            out.println("</error>");
1879
            logMetacat.error("User '" + user + "' not allowed to insert and update");
1880
            return;
1881
        }
1882

    
1883
        try {
1884
            // Get the document indicated
1885
            String[] doctext = (String[]) params.get("doctext");
1886
            String pub = null;
1887
            if (params.containsKey("public")) {
1888
                pub = ((String[]) params.get("public"))[0];
1889
            }
1890

    
1891
            StringReader dtd = null;
1892
            if (params.containsKey("dtdtext")) {
1893
                String[] dtdtext = (String[]) params.get("dtdtext");
1894
                try {
1895
                    if (!dtdtext[0].equals("")) {
1896
                        dtd = new StringReader(dtdtext[0]);
1897
                    }
1898
                } catch (NullPointerException npe) {
1899
                }
1900
            }
1901

    
1902
            if(doctext == null){
1903
                out.println("<?xml version=\"1.0\"?>");
1904
                out.println("<error>");
1905
                out.println("Document text not submitted");
1906
                out.println("</error>");
1907
                return;
1908
            }
1909

    
1910
            StringReader xml = new StringReader(doctext[0]);
1911
            boolean validate = false;
1912
            DocumentImplWrapper documentWrapper = null;
1913
            try {
1914
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1915
                // >
1916
                // in order to decide whether to use validation parser
1917
                validate = needDTDValidation(xml);
1918
                if (validate) {
1919
                    // set a dtd base validation parser
1920
                    String rule = DocumentImpl.DTD;
1921
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1922
                } else {
1923

    
1924
                    String namespace = findNamespace(xml);
1925
                    
1926
                	if (namespace != null) {
1927
                		if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1928
                				|| namespace.compareTo(
1929
                				DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1930
                			// set eml2 base	 validation parser
1931
                			String rule = DocumentImpl.EML200;
1932
                			// using emlparser to check id validation
1933
                			EMLParser parser = new EMLParser(doctext[0]);
1934
                			documentWrapper = new DocumentImplWrapper(rule, true);
1935
                		} else if (namespace.compareTo(
1936
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1937
                			// set eml2 base validation parser
1938
                			String rule = DocumentImpl.EML210;
1939
                			// using emlparser to check id validation
1940
                			EMLParser parser = new EMLParser(doctext[0]);
1941
                			documentWrapper = new DocumentImplWrapper(rule, true);
1942
                		} else {
1943
                			// set schema base validation parser
1944
                			String rule = DocumentImpl.SCHEMA;
1945
                			documentWrapper = new DocumentImplWrapper(rule, true);
1946
                		}
1947
                	} else {
1948
                		documentWrapper = new DocumentImplWrapper("", false);
1949
                	}
1950
                }
1951

    
1952
                String[] action = (String[]) params.get("action");
1953
                String[] docid = (String[]) params.get("docid");
1954
                String newdocid = null;
1955

    
1956
                String doAction = null;
1957
                if (action[0].equals("insert")) {
1958
                    doAction = "INSERT";
1959
                } else if (action[0].equals("update")) {
1960
                    doAction = "UPDATE";
1961
                }
1962

    
1963
                try {
1964
                    // get a connection from the pool
1965
                    dbConn = DBConnectionPool
1966
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1967
                    serialNumber = dbConn.getCheckOutSerialNumber();
1968

    
1969
                    // write the document to the database
1970
                    try {
1971
                        String accNumber = docid[0];
1972
                        logMetacat.debug("" + doAction + " "
1973
                                + accNumber + "...");
1974
                        if (accNumber.equals("")) {
1975
                            accNumber = null;
1976
                        }
1977
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1978
                                doAction, accNumber, user, groups);
1979
                        EventLog.getInstance().log(request.getRemoteAddr(),
1980
                                user, accNumber, action[0]);
1981
                    } catch (NullPointerException npe) {
1982
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1983
                                doAction, null, user, groups);
1984
                        EventLog.getInstance().log(request.getRemoteAddr(),
1985
                                user, "", action[0]);
1986
                    }
1987
                }
1988
                finally {
1989
                    // Return db connection
1990
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1991
                }
1992

    
1993
                // set content type and other response header fields first
1994
                //response.setContentType("text/xml");
1995
                out.println("<?xml version=\"1.0\"?>");
1996
                out.println("<success>");
1997
                out.println("<docid>" + newdocid + "</docid>");
1998
                out.println("</success>");
1999

    
2000
            } catch (NullPointerException npe) {
2001
                //response.setContentType("text/xml");
2002
                out.println("<?xml version=\"1.0\"?>");
2003
                out.println("<error>");
2004
                out.println(npe.getMessage());
2005
                out.println("</error>");
2006
                logMetacat.warn("Error in writing eml document to the database" + npe.getMessage());
2007
                npe.printStackTrace();
2008
            }
2009
        } catch (Exception e) {
2010
            //response.setContentType("text/xml");
2011
            out.println("<?xml version=\"1.0\"?>");
2012
            out.println("<error>");
2013
            out.println(e.getMessage());
2014
            out.println("</error>");
2015
            logMetacat.warn("Error in writing eml document to the database" + e.getMessage());
2016
            e.printStackTrace();
2017
        }
2018
    }
2019

    
2020
    /**
2021
     * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > in
2022
     * order to decide whether to use validation parser
2023
     */
2024
    private static boolean needDTDValidation(StringReader xmlreader)
2025
            throws IOException
2026
    {
2027
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2028
        StringBuffer cbuff = new StringBuffer();
2029
        java.util.Stack st = new java.util.Stack();
2030
        boolean validate = false;
2031
        int c;
2032
        int inx;
2033

    
2034
        // read from the stream until find the keywords
2035
        while ((st.empty() || st.size() < 4) && ((c = xmlreader.read()) != -1)) {
2036
            cbuff.append((char) c);
2037

    
2038
            // "<!DOCTYPE" keyword is found; put it in the stack
2039
            if ((inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1) {
2040
                cbuff = new StringBuffer();
2041
                st.push("<!DOCTYPE");
2042
            }
2043
            // "PUBLIC" keyword is found; put it in the stack
2044
            if ((inx = cbuff.toString().indexOf("PUBLIC")) != -1) {
2045
                cbuff = new StringBuffer();
2046
                st.push("PUBLIC");
2047
            }
2048
            // "SYSTEM" keyword is found; put it in the stack
2049
            if ((inx = cbuff.toString().indexOf("SYSTEM")) != -1) {
2050
                cbuff = new StringBuffer();
2051
                st.push("SYSTEM");
2052
            }
2053
            // ">" character is found; put it in the stack
2054
            // ">" is found twice: fisrt from <?xml ...?>
2055
            // and second from <!DOCTYPE ... >
2056
            if ((inx = cbuff.toString().indexOf(">")) != -1) {
2057
                cbuff = new StringBuffer();
2058
                st.push(">");
2059
            }
2060
        }
2061

    
2062
        // close the stream
2063
        xmlreader.reset();
2064

    
2065
        // check the stack whether it contains the keywords:
2066
        // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
2067
        if (st.size() == 4) {
2068
            if (((String) st.pop()).equals(">")
2069
                    && (((String) st.peek()).equals("PUBLIC") | ((String) st
2070
                            .pop()).equals("SYSTEM"))
2071
                    && ((String) st.pop()).equals("<!DOCTYPE")) {
2072
                validate = true;
2073
            }
2074
        }
2075

    
2076
        logMetacat.info("Validation for dtd is " + validate);
2077
        return validate;
2078
    }
2079

    
2080
    // END OF INSERT/UPDATE SECTION
2081

    
2082
    /* check if the xml string contains key words to specify schema loocation */
2083
    private String findNamespace(StringReader xml) throws IOException
2084
    {
2085
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2086
        String namespace = null;
2087

    
2088
        String eml2_0_0NameSpace = DocumentImpl.EML2_0_0NAMESPACE;
2089
        String eml2_0_1NameSpace = DocumentImpl.EML2_0_1NAMESPACE;
2090
        String eml2_1_0NameSpace = DocumentImpl.EML2_1_0NAMESPACE;
2091

    
2092
        if (xml == null) {
2093
            logMetacat.debug("Validation for schema is "
2094
                    + namespace);
2095
            return namespace;
2096
        }
2097
        String targetLine = getSchemaLine(xml);
2098
		
2099
        if (targetLine != null) {
2100

    
2101
        	// find if the root element has prefix
2102
        	String prefix = getPrefix(targetLine);
2103
        	logMetacat.info("prefix is:" + prefix);
2104
        	int startIndex = 0;
2105
        	
2106
        	
2107
        	if(prefix != null)
2108
        	{
2109
        		// if prefix found then look for xmlns:prefix
2110
        		// element to find the ns 
2111
        		String namespaceWithPrefix = NAMESPACEKEYWORD 
2112
        					+ ":" + prefix;
2113
        		startIndex = targetLine.indexOf(namespaceWithPrefix);
2114
            	logMetacat.debug("namespaceWithPrefix is:" + namespaceWithPrefix+":");
2115
            	logMetacat.debug("startIndex is:" + startIndex);
2116
        		
2117
        	} else {
2118
        		// if prefix not found then look for xmlns
2119
        		// attribute to find the ns 
2120
        		startIndex = targetLine.indexOf(NAMESPACEKEYWORD);
2121
            	logMetacat.debug("startIndex is:" + startIndex);
2122
        	}
2123
        		
2124
            int start = 1;
2125
            int end = 1;
2126
            String namespaceString = null;
2127
            int count = 0;
2128
            if (startIndex != -1) {
2129
                for (int i = startIndex; i < targetLine.length(); i++) {
2130
                    if (targetLine.charAt(i) == '"') {
2131
                        count++;
2132
                    }
2133
                    if (targetLine.charAt(i) == '"' && count == 1) {
2134
                        start = i;
2135
                    }
2136
                    if (targetLine.charAt(i) == '"' && count == 2) {
2137
                        end = i;
2138
                        break;
2139
                    }
2140
                }
2141
            } 
2142
            // else: xmlns not found. namespace = null will be returned
2143

    
2144
         	logMetacat.debug("targetLine is " + targetLine);
2145
         	logMetacat.debug("start is " + end);
2146
         	logMetacat.debug("end is " + end);
2147
           
2148
            if(start < end){
2149
            	namespaceString = targetLine.substring(start + 1, end);
2150
            	logMetacat.debug("namespaceString is " + namespaceString);
2151
            }
2152
            logMetacat.debug("namespace in xml is: "
2153
                    + namespaceString);
2154
            if(namespaceString != null){
2155
            	if (namespaceString.indexOf(eml2_0_0NameSpace) != -1) {
2156
            		namespace = eml2_0_0NameSpace;
2157
            	} else if (namespaceString.indexOf(eml2_0_1NameSpace) != -1) {
2158
            		namespace = eml2_0_1NameSpace;
2159
            	} else if (namespaceString.indexOf(eml2_1_0NameSpace) != -1) {
2160
            		namespace = eml2_1_0NameSpace;
2161
            	} else {
2162
            		namespace = namespaceString;
2163
            	}
2164
            }
2165
        }
2166

    
2167
        logMetacat.debug("Validation for eml is " + namespace);
2168

    
2169
        return namespace;
2170

    
2171
    }
2172

    
2173
    private String getSchemaLine(StringReader xml) throws IOException
2174
    {
2175
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2176
        // find the line
2177
        String secondLine = null;
2178
        int count = 0;
2179
        int endIndex = 0;
2180
        int startIndex = 0;
2181
        final int TARGETNUM = 1;
2182
        StringBuffer buffer = new StringBuffer();
2183
        boolean comment = false;
2184
        boolean processingInstruction = false;
2185
        char thirdPreviousCharacter = '?';
2186
        char secondPreviousCharacter = '?';
2187
        char previousCharacter = '?';
2188
        char currentCharacter = '?';
2189
        int tmp = xml.read();
2190
        while (tmp != -1) {
2191
            currentCharacter = (char)tmp;
2192
            //in a comment
2193
            if (currentCharacter == '-' && previousCharacter == '-'
2194
                    && secondPreviousCharacter == '!'
2195
                    && thirdPreviousCharacter == '<') {
2196
                comment = true;
2197
            }
2198
            //out of comment
2199
            if (comment && currentCharacter == '>' && previousCharacter == '-'
2200
                    && secondPreviousCharacter == '-') {
2201
                comment = false;
2202
            }
2203

    
2204
            //in a processingInstruction
2205
            if (currentCharacter == '?' && previousCharacter == '<') {
2206
            	processingInstruction = true;
2207
            }
2208
            
2209
            //out of processingInstruction
2210
            if (processingInstruction && currentCharacter == '>' 
2211
            	&& previousCharacter == '?') {
2212
            	processingInstruction = false;
2213
            }
2214
            
2215
            //this is not comment or a processingInstruction
2216
            if (currentCharacter != '!' && previousCharacter == '<' 
2217
            	&& !comment && !processingInstruction) {
2218
                count++;
2219
            }
2220
            
2221
            // get target line
2222
            if (count == TARGETNUM && currentCharacter != '>') {
2223
                buffer.append(currentCharacter);
2224
            }
2225
            if (count == TARGETNUM && currentCharacter == '>') {
2226
                break;
2227
            }
2228
            thirdPreviousCharacter = secondPreviousCharacter;
2229
            secondPreviousCharacter = previousCharacter;
2230
            previousCharacter = currentCharacter;
2231
            tmp = xml.read();
2232
        }
2233
        secondLine = buffer.toString();
2234
        logMetacat.debug("the second line string is: " + secondLine);
2235
        
2236
        xml.reset();
2237
        return secondLine;
2238
    }
2239

    
2240
    private String getPrefix(String schemaLine)
2241
    {
2242
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2243
        String prefix = null;
2244
        
2245
        if(schemaLine.indexOf(" ") > 0){
2246
            String rootElement = "";
2247
            try {
2248
                rootElement = schemaLine.substring(0, schemaLine.indexOf(" "));
2249
            } catch (StringIndexOutOfBoundsException sioobe) {
2250
                rootElement = schemaLine;
2251
            }
2252

    
2253
            logMetacat.debug("rootElement:" + rootElement);
2254
        
2255
            if(rootElement.indexOf(":") > 0){
2256
                prefix = rootElement.substring(rootElement.indexOf(":") + 1,
2257
                    rootElement.length());
2258
            }
2259
            
2260
            if(prefix != null){
2261
                return prefix.trim();
2262
            }
2263
        }
2264
        return null;
2265
    }
2266

    
2267
    /**
2268
     * Handle the database delete request and delete an XML document from the
2269
     * database connection
2270
     */
2271
    private void handleDeleteAction(PrintWriter out, Hashtable params,
2272
            HttpServletRequest request, HttpServletResponse response,
2273
            String user, String[] groups)
2274
    {
2275
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2276
        String[] docid = (String[]) params.get("docid");
2277

    
2278
        if(docid == null){
2279
          response.setContentType("text/xml");
2280
          out.println("<?xml version=\"1.0\"?>");
2281
          out.println("<error>");
2282
          out.println("Docid not specified.");
2283
          out.println("</error>");
2284
          logMetacat.error("Docid not specified for the document to be deleted.");
2285
        } else {
2286

    
2287
            // delete the document from the database
2288
            try {
2289

    
2290
                try {
2291
                    // null means notify server is null
2292
                    DocumentImpl.delete(docid[0], user, groups, null);
2293
                    EventLog.getInstance().log(request.getRemoteAddr(),
2294
                                               user, docid[0], "delete");
2295
                    response.setContentType("text/xml");
2296
                    out.println("<?xml version=\"1.0\"?>");
2297
                    out.println("<success>");
2298
                    out.println("Document deleted.");
2299
                    out.println("</success>");
2300
                    logMetacat.info("Document deleted.");
2301
                }
2302
                catch (AccessionNumberException ane) {
2303
                    response.setContentType("text/xml");
2304
                    out.println("<?xml version=\"1.0\"?>");
2305
                    out.println("<error>");
2306
                    //out.println("Error deleting document!!!");
2307
                    out.println(ane.getMessage());
2308
                    out.println("</error>");
2309
                    logMetacat.error("Document could not be deleted: " 
2310
                    		+ ane.getMessage());
2311
                }
2312
            }
2313
            catch (Exception e) {
2314
                response.setContentType("text/xml");
2315
                out.println("<?xml version=\"1.0\"?>");
2316
                out.println("<error>");
2317
                out.println(e.getMessage());
2318
                out.println("</error>");
2319
                logMetacat.error("Document could not be deleted: " 
2320
                		+ e.getMessage());
2321
            }
2322
        }
2323
    }
2324

    
2325
    /**
2326
     * Handle the validation request and return the results to the requestor
2327
     */
2328
    private void handleValidateAction(PrintWriter out, Hashtable params)
2329
    {
2330

    
2331
        // Get the document indicated
2332
        String valtext = null;
2333
        DBConnection dbConn = null;
2334
        int serialNumber = -1;
2335

    
2336
        try {
2337
            valtext = ((String[]) params.get("valtext"))[0];
2338
        } catch (Exception nullpe) {
2339

    
2340
            String docid = null;
2341
            try {
2342
                // Find the document id number
2343
                docid = ((String[]) params.get("docid"))[0];
2344

    
2345
                // Get the document indicated from the db
2346
                DocumentImpl xmldoc = new DocumentImpl(docid);
2347
                valtext = xmldoc.toString();
2348

    
2349
            } catch (NullPointerException npe) {
2350

    
2351
                out.println("<error>Error getting document ID: " + docid
2352
                        + "</error>");
2353
                //if ( conn != null ) { util.returnConnection(conn); }
2354
                return;
2355
            } catch (Exception e) {
2356

    
2357
                out.println(e.getMessage());
2358
            }
2359
        }
2360

    
2361
        try {
2362
            // get a connection from the pool
2363
            dbConn = DBConnectionPool
2364
                    .getDBConnection("MetaCatServlet.handleValidateAction");
2365
            serialNumber = dbConn.getCheckOutSerialNumber();
2366
            DBValidate valobj = new DBValidate(dbConn);
2367
            boolean valid = valobj.validateString(valtext);
2368

    
2369
            // set content type and other response header fields first
2370

    
2371
            out.println(valobj.returnErrors());
2372

    
2373
        } catch (NullPointerException npe2) {
2374
            // set content type and other response header fields first
2375

    
2376
            out.println("<error>Error validating document.</error>");
2377
        } catch (Exception e) {
2378

    
2379
            out.println(e.getMessage());
2380
        } finally {
2381
            // Return db connection
2382
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2383
        }
2384
    }
2385

    
2386
    /**
2387
     * Handle "getrevsionanddoctype" action Given a docid, return it's current
2388
     * revision and doctype from data base The output is String look like
2389
     * "rev;doctype"
2390
     */
2391
    private void handleGetRevisionAndDocTypeAction(PrintWriter out,
2392
            Hashtable params)
2393
    {
2394
        // To store doc parameter
2395
        String[] docs = new String[10];
2396
        // Store a single doc id
2397
        String givenDocId = null;
2398
        // Get docid from parameters
2399
        if (params.containsKey("docid")) {
2400
            docs = (String[]) params.get("docid");
2401
        }
2402
        // Get first docid form string array
2403
        givenDocId = docs[0];
2404

    
2405
        try {
2406
            // Make sure there is a docid
2407
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
2408
                    "User didn't specify docid!"); }//if
2409

    
2410
            // Create a DBUtil object
2411
            DBUtil dbutil = new DBUtil();
2412
            // Get a rev and doctype
2413
            String revAndDocType = dbutil
2414
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
2415
            out.println(revAndDocType);
2416

    
2417
        } catch (Exception e) {
2418
            // Handle exception
2419
            out.println("<?xml version=\"1.0\"?>");
2420
            out.println("<error>");
2421
            out.println(e.getMessage());
2422
            out.println("</error>");
2423
        }
2424

    
2425
    }
2426

    
2427
    /**
2428
     * Handle "getaccesscontrol" action. Read Access Control List from db
2429
     * connection in XML format
2430
     */
2431
    private void handleGetAccessControlAction(PrintWriter out,
2432
            Hashtable params, HttpServletResponse response, String username,
2433
            String[] groupnames)
2434
    {
2435
        DBConnection dbConn = null;
2436
        int serialNumber = -1;
2437
        String docid = ((String[]) params.get("docid"))[0];
2438

    
2439
        try {
2440

    
2441
            // get connection from the pool
2442
            dbConn = DBConnectionPool
2443
                    .getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2444
            serialNumber = dbConn.getCheckOutSerialNumber();
2445
            AccessControlList aclobj = new AccessControlList(dbConn);
2446
            String acltext = aclobj.getACL(docid, username, groupnames);
2447
            out.println(acltext);
2448

    
2449
        } catch (Exception e) {
2450
            out.println("<?xml version=\"1.0\"?>");
2451
            out.println("<error>");
2452
            out.println(e.getMessage());
2453
            out.println("</error>");
2454
        } finally {
2455
            // Retrun db connection to pool
2456
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2457
        }
2458
    }
2459

    
2460
    /**
2461
     * Handle the "getprincipals" action. Read all principals from
2462
     * authentication scheme in XML format
2463
     */
2464
    private void handleGetPrincipalsAction(PrintWriter out, String user,
2465
            String password)
2466
    {
2467
        try {
2468
            AuthSession auth = new AuthSession();
2469
            String principals = auth.getPrincipals(user, password);
2470
            out.println(principals);
2471

    
2472
        } catch (Exception e) {
2473
            out.println("<?xml version=\"1.0\"?>");
2474
            out.println("<error>");
2475
            out.println(e.getMessage());
2476
            out.println("</error>");
2477
        }
2478
    }
2479

    
2480
    /**
2481
     * Handle "getdoctypes" action. Read all doctypes from db connection in XML
2482
     * format
2483
     */
2484
    private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
2485
            HttpServletResponse response)
2486
    {
2487
        try {
2488
            DBUtil dbutil = new DBUtil();
2489
            String doctypes = dbutil.readDoctypes();
2490
            out.println(doctypes);
2491
        } catch (Exception e) {
2492
            out.println("<?xml version=\"1.0\"?>");
2493
            out.println("<error>");
2494
            out.println(e.getMessage());
2495
            out.println("</error>");
2496
        }
2497
    }
2498

    
2499
    /**
2500
     * Handle the "getdtdschema" action. Read DTD or Schema file for a given
2501
     * doctype from Metacat catalog system
2502
     */
2503
    private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2504
            HttpServletResponse response)
2505
    {
2506

    
2507
        String doctype = null;
2508
        String[] doctypeArr = (String[]) params.get("doctype");
2509

    
2510
        // get only the first doctype specified in the list of doctypes
2511
        // it could be done for all doctypes in that list
2512
        if (doctypeArr != null) {
2513
            doctype = ((String[]) params.get("doctype"))[0];
2514
        }
2515

    
2516
        try {
2517
            DBUtil dbutil = new DBUtil();
2518
            String dtdschema = dbutil.readDTDSchema(doctype);
2519
            out.println(dtdschema);
2520

    
2521
        } catch (Exception e) {
2522
            out.println("<?xml version=\"1.0\"?>");
2523
            out.println("<error>");
2524
            out.println(e.getMessage());
2525
            out.println("</error>");
2526
        }
2527

    
2528
    }
2529

    
2530
    /**
2531
     * Handle the "getlastdocid" action. Get the latest docid with rev number
2532
     * from db connection in XML format
2533
     */
2534
    private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2535
            HttpServletResponse response)
2536
    {
2537

    
2538
        String scope = ((String[]) params.get("scope"))[0];
2539
        if (scope == null) {
2540
            scope = ((String[]) params.get("username"))[0];
2541
        }
2542

    
2543
        try {
2544

    
2545
            DBUtil dbutil = new DBUtil();
2546
            String lastDocid = dbutil.getMaxDocid(scope);
2547
            out.println("<?xml version=\"1.0\"?>");
2548
            out.println("<lastDocid>");
2549
            out.println("  <scope>" + scope + "</scope>");
2550
            out.println("  <docid>" + lastDocid + "</docid>");
2551
            out.println("</lastDocid>");
2552

    
2553
        } catch (Exception e) {
2554
            out.println("<?xml version=\"1.0\"?>");
2555
            out.println("<error>");
2556
            out.println(e.getMessage());
2557
            out.println("</error>");
2558
        }
2559
    }
2560

    
2561
    /**
2562
     * Print a report from the event log based on filter parameters passed in
2563
     * from the web.
2564
     *
2565
     * @param params the parameters from the web request
2566
     * @param request the http request object for getting request details
2567
     * @param response the http response object for writing output
2568
     */
2569
    private void handleGetLogAction(Hashtable params, HttpServletRequest request,
2570
            HttpServletResponse response, String username, String[] groups)
2571
    {
2572
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2573
        try {
2574
            response.setContentType("text/xml");
2575
            PrintWriter out = response.getWriter();
2576

    
2577
            // Check that the user is authenticated as an administrator account
2578
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2579
                out.print("<error>");
2580
                out.print("The user \"" + username +
2581
                        "\" is not authorized for this action.");
2582
                out.print("</error>");
2583
                return;
2584
            }
2585

    
2586
            // Get all of the parameters in the correct formats
2587
            String[] ipAddress = (String[])params.get("ipaddress");
2588
            String[] principal = (String[])params.get("principal");
2589
            String[] docid = (String[])params.get("docid");
2590
            String[] event = (String[])params.get("event");
2591
            String[] startArray = (String[]) params.get("start");
2592
            String[] endArray = (String[]) params.get("end");
2593
            String start = null;
2594
            String end = null;
2595
            if (startArray != null) {
2596
                start = startArray[0];
2597
            }
2598
            if (endArray != null) {
2599
                end = endArray[0];
2600
            }
2601
            Timestamp startDate = null;
2602
            Timestamp endDate = null;
2603
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2604
            try {
2605
                if (start != null) {
2606
                    startDate = new Timestamp((format.parse(start)).getTime());
2607
                }
2608
                if (end != null) {
2609
                    endDate = new Timestamp((format.parse(end)).getTime());
2610
                }
2611
            } catch (ParseException e) {
2612
                System.out.println("Failed to created Timestamp from input.");
2613
            }
2614

    
2615
            // Request the report by passing the filter parameters
2616
            out.println(EventLog.getInstance().getReport(ipAddress, principal,
2617
                    docid, event, startDate, endDate));
2618
            out.close();
2619
        } catch (IOException e) {
2620
            logMetacat.error(
2621
                    "Could not open http response for writing: " + e.getMessage());
2622
        }
2623
    }
2624

    
2625
    /**
2626
     * Rebuild the index for one or more documents. If the docid parameter is
2627
     * provided, rebuild for just that one document or list of documents. If
2628
     * not, then rebuild the index for all documents in the xml_documents
2629
     * table.
2630
     *
2631
     * @param params the parameters from the web request
2632
     * @param request the http request object for getting request details
2633
     * @param response the http response object for writing output
2634
     * @param username the username of the authenticated user
2635
     */
2636
    private void handleBuildIndexAction(Hashtable params,
2637
            HttpServletRequest request, HttpServletResponse response,
2638
            String username, String[] groups)
2639
    {
2640
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2641
        
2642
        // Get all of the parameters in the correct formats
2643
        String[] docid = (String[])params.get("docid");
2644

    
2645
        // Rebuild the indices for appropriate documents
2646
        try {
2647
            response.setContentType("text/xml");
2648
            PrintWriter out = response.getWriter();
2649

    
2650
            // Check that the user is authenticated as an administrator account
2651
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2652
                out.print("<error>");
2653
                out.print("The user \"" + username +
2654
                        "\" is not authorized for this action.");
2655
                out.print("</error>");
2656
                return;
2657
            }
2658

    
2659
            // Process the documents
2660
            out.println("<success>");
2661
            if (docid == null || docid.length == 0) {
2662
                // Process all of the documents
2663
                try {
2664
                    Vector documents = getDocumentList();
2665
                    Iterator it = documents.iterator();
2666
                    while (it.hasNext()) {
2667
                        String id = (String) it.next();
2668
                        buildDocumentIndex(id, out);
2669
                    }
2670
                } catch (SQLException se) {
2671
                    out.print("<error>");
2672
                    out.print(se.getMessage());
2673
                    out.println("</error>");
2674
                }
2675
            } else {
2676
                // Only process the requested documents
2677
                for (int i = 0; i < docid.length; i++) {
2678
                    buildDocumentIndex(docid[i], out);
2679
                }
2680
            }
2681
            out.println("</success>");
2682
            out.close();
2683
        } catch (IOException e) {
2684
            logMetacat.error(
2685
                    "Could not open http response for writing: "
2686
                    + e.getMessage());
2687
        }
2688
    }
2689

    
2690
    /**
2691
     * Build the index for one document by reading the document and
2692
     * calling its buildIndex() method.
2693
     *
2694
     * @param docid the document (with revision) to rebuild
2695
     * @param out the PrintWriter to which output is printed
2696
     */
2697
    private void buildDocumentIndex(String docid, PrintWriter out)
2698
    {
2699
        try {
2700
            DocumentImpl doc = new DocumentImpl(docid, false);
2701
            doc.buildIndex();
2702
            out.print("<docid>" + docid);
2703
            out.println("</docid>");
2704
        } catch (McdbException me) {
2705
            out.print("<error>");
2706
            out.print(me.getMessage());
2707
            out.println("</error>");
2708
        }
2709
    }
2710

    
2711
    /**
2712
     * Handle documents passed to metacat that are encoded using the
2713
     * "multipart/form-data" mime type. This is typically used for uploading
2714
     * data files which may be binary and large.
2715
     */
2716
    private void handleMultipartForm(HttpServletRequest request,
2717
            HttpServletResponse response)
2718
    {
2719
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2720
        PrintWriter out = null;
2721
        String action = null;
2722

    
2723
        // Parse the multipart form, and save the parameters in a Hashtable and
2724
        // save the FileParts in a hashtable
2725

    
2726
        Hashtable params = new Hashtable();
2727
        Hashtable fileList = new Hashtable();
2728
        int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2729
                .intValue();
2730
        logMetacat.info(
2731
                "The size limit of uploaded data files is: " + sizeLimit);
2732

    
2733
        try {
2734
            MultipartParser mp = new MultipartParser(request,
2735
                    sizeLimit * 1024 * 1024);
2736
            Part part;
2737
            while ((part = mp.readNextPart()) != null) {
2738
                String name = part.getName();
2739

    
2740
                if (part.isParam()) {
2741
                    // it's a parameter part
2742
                    ParamPart paramPart = (ParamPart) part;
2743
                    String value = paramPart.getStringValue();
2744
                    params.put(name, value);
2745
                    if (name.equals("action")) {
2746
                        action = value;
2747
                    }
2748
                } else if (part.isFile()) {
2749
                    // it's a file part
2750
                    FilePart filePart = (FilePart) part;
2751
                    fileList.put(name, filePart);
2752

    
2753
                    // Stop once the first file part is found, otherwise going
2754
                    // onto the
2755
                    // next part prevents access to the file contents. So...for
2756
                    // upload
2757
                    // to work, the datafile must be the last part
2758
                    break;
2759
                }
2760
            }
2761
        } catch (IOException ioe) {
2762
            try {
2763
                out = response.getWriter();
2764
            } catch (IOException ioe2) {
2765
                logMetacat.fatal("Fatal Error: couldn't get response output stream.");
2766
            }
2767
            out.println("<?xml version=\"1.0\"?>");
2768
            out.println("<error>");
2769
            out.println("Error: problem reading multipart data.");
2770
            out.println("</error>");
2771
        }
2772

    
2773
        // Get the session information
2774
        String username = null;
2775
        String password = null;
2776
        String[] groupnames = null;
2777
        String sess_id = null;
2778

    
2779
        // be aware of session expiration on every request
2780
        HttpSession sess = request.getSession(true);
2781
        if (sess.isNew()) {
2782
            // session expired or has not been stored b/w user requests
2783
            username = "public";
2784
            sess.setAttribute("username", username);
2785
        } else {
2786
            username = (String) sess.getAttribute("username");
2787
            password = (String) sess.getAttribute("password");
2788
            groupnames = (String[]) sess.getAttribute("groupnames");
2789
            try {
2790
                sess_id = (String) sess.getId();
2791
            } catch (IllegalStateException ise) {
2792
                System.out
2793
                        .println("error in  handleMultipartForm: this shouldn't "
2794
                                + "happen: the session should be valid: "
2795
                                + ise.getMessage());
2796
            }
2797
        }
2798

    
2799
        // Get the out stream
2800
        try {
2801
            out = response.getWriter();
2802
        } catch (IOException ioe2) {
2803
            logMetacat.error("Fatal Error: couldn't get response "
2804
                    + "output stream.");
2805
        }
2806

    
2807
        if (action.equals("upload")) {
2808
            if (username != null && !username.equals("public")) {
2809
                handleUploadAction(request, out, params, fileList, username,
2810
                        groupnames);
2811
            } else {
2812

    
2813
                out.println("<?xml version=\"1.0\"?>");
2814
                out.println("<error>");
2815
                out.println("Permission denied for " + action);
2816
                out.println("</error>");
2817
            }
2818
        } else {
2819
            /*
2820
             * try { out = response.getWriter(); } catch (IOException ioe2) {
2821
             * System.err.println("Fatal Error: couldn't get response output
2822
             * stream.");
2823
             */
2824
            out.println("<?xml version=\"1.0\"?>");
2825
            out.println("<error>");
2826
            out.println(
2827
                    "Error: action not registered.  Please report this error.");
2828
            out.println("</error>");
2829
        }
2830
        out.close();
2831
    }
2832

    
2833
    /**
2834
     * Handle the upload action by saving the attached file to disk and
2835
     * registering it in the Metacat db
2836
     */
2837
    private void handleUploadAction(HttpServletRequest request,
2838
            PrintWriter out, Hashtable params, Hashtable fileList,
2839
            String username, String[] groupnames)
2840
    {
2841
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2842
        //PrintWriter out = null;
2843
        //Connection conn = null;
2844
        String action = null;
2845
        String docid = null;
2846

    
2847
        /*
2848
         * response.setContentType("text/xml"); try { out =
2849
         * response.getWriter(); } catch (IOException ioe2) {
2850
         * System.err.println("Fatal Error: couldn't get response output
2851
         * stream.");
2852
         */
2853

    
2854
        if (params.containsKey("docid")) {
2855
            docid = (String) params.get("docid");
2856
        }
2857

    
2858
        // Make sure we have a docid and datafile
2859
        if (docid != null && fileList.containsKey("datafile")) {
2860
            logMetacat.info("Uploading data docid: " + docid);
2861
            // Get a reference to the file part of the form
2862
            FilePart filePart = (FilePart) fileList.get("datafile");
2863
            String fileName = filePart.getFileName();
2864
            logMetacat.info("Uploading filename: " + fileName);
2865
            // Check if the right file existed in the uploaded data
2866
            if (fileName != null) {
2867

    
2868
                try {
2869
                    //logMetacat.info("Upload datafile " + docid
2870
                    // +"...", 10);
2871
                    //If document get lock data file grant
2872
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2873
                        // Save the data file to disk using "docid" as the name
2874
                        String datafilepath = MetaCatUtil.getOption("datafilepath");
2875
                        File dataDirectory = new File(datafilepath);
2876
                        dataDirectory.mkdirs();
2877
                        File newFile = null;
2878
                        long size = 0;
2879
                        try
2880
                        {
2881
                          newFile = new File(dataDirectory, docid);
2882
                          size = filePart.writeTo(newFile);
2883
                        
2884
//                        register the file in the database (which generates
2885
                          // an exception
2886
                          //if the docid is not acceptable or other untoward
2887
                          // things happen
2888
                          DocumentImpl.registerDocument(fileName, "BIN", docid,
2889
                                username, groupnames);
2890
                        }
2891
                        catch (Exception ee)
2892
                        {
2893
                           //detelte the file to create
2894
                            newFile.delete();
2895
                            throw ee;
2896
                        }
2897

    
2898
                        EventLog.getInstance().log(request.getRemoteAddr(),
2899
                                username, docid, "upload");
2900
                        // Force replication this data file
2901
                        // To data file, "insert" and update is same
2902
                        // The fourth parameter is null. Because it is
2903
                        // notification server
2904
                        // and this method is in MetaCatServerlet. It is
2905
                        // original command,
2906
                        // not get force replication info from another metacat
2907
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2908
                                docid, "insert", false, null);
2909

    
2910
                        // set content type and other response header fields
2911
                        // first
2912
                        out.println("<?xml version=\"1.0\"?>");
2913
                        out.println("<success>");
2914
                        out.println("<docid>" + docid + "</docid>");
2915
                        out.println("<size>" + size + "</size>");
2916
                        out.println("</success>");
2917
                    }
2918

    
2919
                } catch (Exception e) {
2920
                    
2921
                    out.println("<?xml version=\"1.0\"?>");
2922
                    out.println("<error>");
2923
                    out.println(e.getMessage());
2924
                    out.println("</error>");
2925
                }
2926
            } else {
2927
                // the field did not contain a file
2928
                out.println("<?xml version=\"1.0\"?>");
2929
                out.println("<error>");
2930
                out.println("The uploaded data did not contain a valid file.");
2931
                out.println("</error>");
2932
            }
2933
        } else {
2934
            // Error bcse docid missing or file missing
2935
            out.println("<?xml version=\"1.0\"?>");
2936
            out.println("<error>");
2937
            out.println("The uploaded data did not contain a valid docid "
2938
                    + "or valid file.");
2939
            out.println("</error>");
2940
        }
2941
    }
2942

    
2943
    /*
2944
     * A method to handle set access action
2945
     */
2946
    private void handleSetAccessAction(PrintWriter out, Hashtable params,
2947
            String username)
2948
    {
2949
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2950
        String[] docList = null;
2951
        String[] principalList = null;
2952
        String[] permissionList = null;
2953
        String[] permTypeList = null;
2954
        String[] permOrderList = null;
2955
        String permission = null;
2956
        String permType = null;
2957
        String permOrder = null;
2958
        Vector errorList = new Vector();
2959
        String error = null;
2960
        Vector successList = new Vector();
2961
        String success = null;
2962

    
2963
        // Get parameters
2964
        if (params.containsKey("docid")) {
2965
            docList = (String[]) params.get("docid");
2966
        }
2967
        if (params.containsKey("principal")) {
2968
            principalList = (String[]) params.get("principal");
2969
        }
2970
        if (params.containsKey("permission")) {
2971
            permissionList = (String[]) params.get("permission");
2972

    
2973
        }
2974
        if (params.containsKey("permType")) {
2975
            permTypeList = (String[]) params.get("permType");
2976

    
2977
        }
2978
        if (params.containsKey("permOrder")) {
2979
            permOrderList = (String[]) params.get("permOrder");
2980

    
2981
        }
2982

    
2983
        // Make sure the parameter is not null
2984
        if (docList == null || principalList == null || permTypeList == null
2985
                || permissionList == null) {
2986
            error = "Please check your parameter list, it should look like: "
2987
                    + "?action=setaccess&docid=pipeline.1.1&principal=public"
2988
                    + "&permission=read&permType=allow&permOrder=allowFirst";
2989
            errorList.addElement(error);
2990
            outputResponse(successList, errorList, out);
2991
            return;
2992
        }
2993

    
2994
        // Only select first element for permission, type and order
2995
        permission = permissionList[0];
2996
        permType = permTypeList[0];
2997
        if (permOrderList != null) {
2998
            permOrder = permOrderList[0];
2999
        }
3000

    
3001
        // Get package doctype set
3002
        Vector packageSet = MetaCatUtil.getOptionList(MetaCatUtil
3003
                .getOption("packagedoctypeset"));
3004
        //debug
3005
        if (packageSet != null) {
3006
            for (int i = 0; i < packageSet.size(); i++) {
3007
                logMetacat.debug("doctype in package set: "
3008
                        + (String) packageSet.elementAt(i));
3009
            }
3010
        }
3011

    
3012
        // handle every accessionNumber
3013
        for (int i = 0; i < docList.length; i++) {
3014
            String accessionNumber = docList[i];
3015
            String owner = null;
3016
            String publicId = null;
3017
            // Get document owner and public id
3018
            try {
3019
                owner = getFieldValueForDoc(accessionNumber, "user_owner");
3020
                publicId = getFieldValueForDoc(accessionNumber, "doctype");
3021
            } catch (Exception e) {
3022
                logMetacat.error("Error in handleSetAccessAction: "
3023
                        + e.getMessage());
3024
                error = "Error in set access control for document - "
3025
                        + accessionNumber + e.getMessage();
3026
                errorList.addElement(error);
3027
                continue;
3028
            }
3029
            //check if user is the owner. Only owner can do owner
3030
            if (username == null || owner == null || !username.equals(owner)) {
3031
                error = "User - " + username
3032
                        + " does not have permission to set "
3033
                        + "access control for docid - " + accessionNumber;
3034
                errorList.addElement(error);
3035
                continue;
3036
            }
3037

    
3038
            // If docid publicid is BIN data file or other beta4, 6 package
3039
            // document
3040
            // we could not do set access control. Because we don't want
3041
            // inconsistent
3042
            // to its access docuemnt
3043
            if (publicId != null && packageSet != null
3044
                    && packageSet.contains(publicId)) {
3045
                error = "Could not set access control to document "
3046
                        + accessionNumber
3047
                        + "because it is in a pakcage and it has a access file for it";
3048
                errorList.addElement(error);
3049
                continue;
3050
            }
3051

    
3052
            // for every principle
3053
            for (int j = 0; j < principalList.length; j++) {
3054
                String principal = principalList[j];
3055
                try {
3056
                    //insert permission
3057
                    AccessControlForSingleFile accessControl = new AccessControlForSingleFile(
3058
                            accessionNumber, principal, permission, permType,
3059
                            permOrder);
3060
                    accessControl.insertPermissions();
3061
                    success = "Set access control to document "
3062
                            + accessionNumber + " successfully";
3063
                    successList.addElement(success);
3064
                } catch (Exception ee) {
3065
                    logMetacat.error(
3066
                            "Erorr in handleSetAccessAction2: "
3067
                                    + ee.getMessage());
3068
                    error = "Faild to set access control for document "
3069
                            + accessionNumber + " because " + ee.getMessage();
3070
                    errorList.addElement(error);
3071
                    continue;
3072
                }
3073
            }
3074
        }
3075
        outputResponse(successList, errorList, out);
3076
    }
3077

    
3078
    /*
3079
     * A method try to determin a docid's public id, if couldn't find null will
3080
     * be returned.
3081
     */
3082
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
3083
            throws Exception
3084
    {
3085
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3086
        if (accessionNumber == null || accessionNumber.equals("")
3087
                || fieldName == null || fieldName.equals("")) { throw new Exception(
3088
                "Docid or field name was not specified"); }
3089

    
3090
        PreparedStatement pstmt = null;
3091
        ResultSet rs = null;
3092
        String fieldValue = null;
3093
        String docId = null;
3094
        DBConnection conn = null;
3095
        int serialNumber = -1;
3096

    
3097
        // get rid of revision if access number has
3098
        docId = MetaCatUtil.getDocIdFromString(accessionNumber);
3099
        try {
3100
            //check out DBConnection
3101
            conn = DBConnectionPool
3102
                    .getDBConnection("MetaCatServlet.getPublicIdForDoc");
3103
            serialNumber = conn.getCheckOutSerialNumber();
3104
            pstmt = conn.prepareStatement("SELECT " + fieldName
3105
                    + " FROM xml_documents " + "WHERE docid = ? ");
3106

    
3107
            pstmt.setString(1, docId);
3108
            pstmt.execute();
3109
            rs = pstmt.getResultSet();
3110
            boolean hasRow = rs.next();
3111
            int perm = 0;
3112
            if (hasRow) {
3113
                fieldValue = rs.getString(1);
3114
            } else {
3115
                throw new Exception("Could not find document: "
3116
                        + accessionNumber);
3117
            }
3118
        } catch (Exception e) {
3119
            logMetacat.error(
3120
                    "Exception in MetacatServlet.getPublicIdForDoc: "
3121
                            + e.getMessage());
3122
            throw e;
3123
        } finally {
3124
            try {
3125
                rs.close();
3126
                pstmt.close();
3127

    
3128
            } finally {
3129
                DBConnectionPool.returnDBConnection(conn, serialNumber);
3130
            }
3131
        }
3132
        return fieldValue;
3133
    }
3134

    
3135
    /*
3136
     * Get the list of documents from the database and return the list in an
3137
     * Vector of identifiers.
3138
     *
3139
     * @ returns the array of identifiers
3140
     */
3141
    private Vector getDocumentList() throws SQLException
3142
    {
3143
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3144
        Vector docList = new Vector();
3145
        PreparedStatement pstmt = null;
3146
        ResultSet rs = null;
3147
        DBConnection conn = null;
3148
        int serialNumber = -1;
3149

    
3150
        try {
3151
            //check out DBConnection
3152
            conn = DBConnectionPool
3153
                    .getDBConnection("MetaCatServlet.getDocumentList");
3154
            serialNumber = conn.getCheckOutSerialNumber();
3155
            pstmt = conn.prepareStatement("SELECT docid, rev"
3156
                    + " FROM xml_documents ");
3157
            pstmt.execute();
3158
            rs = pstmt.getResultSet();
3159
            while (rs.next()) {
3160
                String docid = rs.getString(1);
3161
                String rev = rs.getString(2);
3162
                docList.add(docid + "." + rev);
3163
            }
3164
        } catch (SQLException e) {
3165
            logMetacat.error(
3166
                    "Exception in MetacatServlet.getDocumentList: "
3167
                            + e.getMessage());
3168
            throw e;
3169
        } finally {
3170
            try {
3171
                rs.close();
3172
                pstmt.close();
3173

    
3174
            } catch (SQLException se) {
3175
                logMetacat.error(
3176
                    "Exception in MetacatServlet.getDocumentList: "
3177
                            + se.getMessage());
3178
                throw se;
3179
            } finally {
3180
                DBConnectionPool.returnDBConnection(conn, serialNumber);
3181
            }
3182
        }
3183
        return docList;
3184
    }
3185

    
3186
    /*
3187
     * A method to output setAccess action result
3188
     */
3189
    private void outputResponse(Vector successList, Vector errorList,
3190
            PrintWriter out)
3191
    {
3192
        boolean error = false;
3193
        boolean success = false;
3194
        // Output prolog
3195
        out.println(PROLOG);
3196
        // output success message
3197
        if (successList != null) {
3198
            for (int i = 0; i < successList.size(); i++) {
3199
                out.println(SUCCESS);
3200
                out.println((String) successList.elementAt(i));
3201
                out.println(SUCCESSCLOSE);
3202
                success = true;
3203
            }
3204
        }
3205
        // output error message
3206
        if (errorList != null) {
3207
            for (int i = 0; i < errorList.size(); i++) {
3208
                out.println(ERROR);
3209
                out.println((String) errorList.elementAt(i));
3210
                out.println(ERRORCLOSE);
3211
                error = true;
3212
            }
3213
        }
3214

    
3215
        // if no error and no success info, send a error that nothing happened
3216
        if (!error && !success) {
3217
            out.println(ERROR);
3218
            out.println("Nothing happend for setaccess action");
3219
            out.println(ERRORCLOSE);
3220
        }
3221
    }
3222
    
3223
    /**
3224
     * Method to get session table which store the session info
3225
     * @return
3226
     */
3227
    public static Hashtable getSessionHash()
3228
    {
3229
        return sessionHash;
3230
    }
3231
    
3232
    /*
3233
     * If the given docid only have one seperter, we need 
3234
     * append rev for it. The rev come from xml_documents
3235
     */
3236
    private static String appendRev(String docid) throws Exception
3237
    {
3238
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3239
        String newAccNum = null;
3240
        String separator = MetaCatUtil.getOption("accNumSeparator");
3241
        int firstIndex = docid.indexOf(separator);
3242
        int lastIndex = docid.lastIndexOf(separator);
3243
        if (firstIndex == lastIndex)
3244
        {
3245
            
3246
           //only one seperater
3247
            int rev = DBUtil.getLatestRevisionInDocumentTable(docid);
3248
            if (rev == -1)
3249
            {
3250
                throw new Exception("the requested docid '"
3251
                        + docid+ "' does not exist");
3252
            }
3253
            else
3254
            {
3255
                newAccNum = docid+ separator+ rev;
3256
            }
3257
        }
3258
        else
3259
        {
3260
            // in other suituation we don't change the docid
3261
            newAccNum = docid;
3262
        }
3263
        //logMetacat.debug("The docid will be read is "+newAccNum);
3264
        return newAccNum;
3265
  }
3266
}
(44-44/65)