Project

General

Profile

1 51 jones
/**
2 203 jones
 *  '$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 3028 perry
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley, Matthew Perry
7 348 jones
 *    Release: @release@
8 154 jones
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
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 51 jones
 */
27
28
package edu.ucsb.nceas.metacat;
29
30 2098 jones
import java.io.BufferedInputStream;
31 733 bojilova
import java.io.File;
32 2098 jones
import java.io.FileInputStream;
33
import java.io.IOException;
34 46 jones
import java.io.PrintWriter;
35 50 jones
import java.io.StringReader;
36 2098 jones
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 2113 jones
import java.sql.Timestamp;
42
import java.text.ParseException;
43
import java.text.SimpleDateFormat;
44 46 jones
import java.util.Enumeration;
45 2893 sgarg
import java.util.HashMap;
46 46 jones
import java.util.Hashtable;
47 2312 jones
import java.util.Iterator;
48 2896 sgarg
import java.util.Properties;
49 2752 jones
import java.util.Timer;
50 1369 tao
import java.util.Vector;
51 2098 jones
import java.util.zip.ZipEntry;
52
import java.util.zip.ZipOutputStream;
53 46 jones
54
import javax.servlet.ServletConfig;
55
import javax.servlet.ServletContext;
56
import javax.servlet.ServletException;
57 2098 jones
import javax.servlet.ServletOutputStream;
58 46 jones
import javax.servlet.http.HttpServlet;
59
import javax.servlet.http.HttpServletRequest;
60
import javax.servlet.http.HttpServletResponse;
61 210 bojilova
import javax.servlet.http.HttpSession;
62 46 jones
63 2752 jones
import org.apache.log4j.Logger;
64
import org.apache.log4j.PropertyConfigurator;
65 2098 jones
import org.ecoinformatics.eml.EMLParser;
66 204 jones
67 2098 jones
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 2570 jones
import edu.ucsb.nceas.utilities.Options;
73 2912 harris
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialQuery;
74
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialDocument;
75
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialDataset;
76 2919 harris
import edu.ucsb.nceas.metacat.spatial.MetacatSpatialConstants;
77 2570 jones
78 46 jones
/**
79
 * A metadata catalog server implemented as a Java Servlet
80 2169 sgarg
 *
81 205 jones
 * <p>
82 2098 jones
 * 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 2113 jones
 * 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 2098 jones
 * <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 46 jones
 */
122 2098 jones
public class MetaCatServlet extends HttpServlet
123
{
124 2582 tao
    private static Hashtable sessionHash = new Hashtable();
125 2752 jones
    private Timer timer = null;
126
127
    // Constants -- these should be final in a servlet
128 2098 jones
    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 2711 sgarg
    public static final String NAMESPACEKEYWORD = "xmlns";
136 2098 jones
    public static final String EML2KEYWORD = ":eml";
137
    public static final String XMLFORMAT = "xml";
138
    private static final String CONFIG_DIR = "WEB-INF";
139 2752 jones
    private static final String CONFIG_NAME = "metacat.properties";
140 2663 sgarg
141 2098 jones
    /**
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 2752 jones
            ServletContext context = config.getServletContext();
149 1360 tao
150 2098 jones
            // Initialize the properties file for our options
151
            String dirPath = context.getRealPath(CONFIG_DIR);
152
            File propertyFile = new File(dirPath, CONFIG_NAME);
153 2594 sgarg
154 2663 sgarg
            String LOG_CONFIG_NAME = dirPath + "/log4j.properties";
155
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
156
157 2098 jones
            Options options = null;
158
            try {
159
                options = Options.initialize(propertyFile);
160 2663 sgarg
                MetaCatUtil.printMessage("Options configured: "
161
                        + options.getOption("configured"));
162 2098 jones
            } catch (IOException ioe) {
163 2753 jones
                Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
164 2663 sgarg
                logMetacat.error("Error in loading options: "
165
                        + ioe.getMessage());
166 2098 jones
            }
167 1716 berkley
168 2752 jones
            MetaCatUtil util = new MetaCatUtil();
169 2893 sgarg
170 2752 jones
            //initialize DBConnection pool
171
            DBConnectionPool connPool = DBConnectionPool.getInstance();
172
173 2521 sgarg
            // Index the paths specified in the metacat.properties
174
            checkIndexPaths();
175
176 2729 sgarg
            // 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 2893 sgarg
            // 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 2897 sgarg
                skinPropertyFile = new File(skinDirPath, skinName + ".properties");
196 2896 sgarg
                Properties skinOption = null;
197 2893 sgarg
                try	{
198 2896 sgarg
                	skinOption = new Properties();
199
                    FileInputStream fis = new FileInputStream(skinPropertyFile);
200
                    skinOption.load(fis);
201
                    fis.close();
202 2893 sgarg
                } catch (IOException ioe) {
203
                    Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
204
                    logMetacat.error("Error in loading options for skin " + "skinName" +" : "
205
                            + ioe.getMessage());
206 2896 sgarg
                }
207 2893 sgarg
                MetaCatUtil.skinconfigs.put(skinName, skinOption);
208
            }
209 2946 sgarg
210
211 2948 sgarg
	if (MetacatSpatialConstants.runSpatialOption == true ) {
212 2946 sgarg
213
	    // create a spatial index of the database
214 2919 harris
            MetacatSpatialConstants.setServerContext(MetaCatUtil.getOption("server"));
215 2913 harris
            MetacatSpatialQuery  _spatialQuery = new MetacatSpatialQuery();
216 2893 sgarg
217 2913 harris
            // 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 2946 sgarg
223
	}
224 2913 harris
225
226 2663 sgarg
            MetaCatUtil.printMessage("Metacat (" + Version.getVersion()
227 2521 sgarg
                               + ") initialized.");
228
229 2098 jones
        } catch (ServletException ex) {
230
            throw ex;
231
        } catch (SQLException e) {
232 2753 jones
            Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
233 2663 sgarg
            logMetacat.error("Error in MetacatServlet.init: "
234
                    + e.getMessage());
235 1221 tao
        }
236 2098 jones
    }
237 1360 tao
238 2570 jones
    /**
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 2759 sgarg
        timer.cancel();
246 2901 sgarg
        IndexingQueue.getInstance().setMetacatRunning(false);
247 2570 jones
        DBConnectionPool.release();
248
    }
249 2521 sgarg
250 2570 jones
    /** 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 2098 jones
    /**
269 2521 sgarg
     * Index the paths specified in the metacat.properties
270
     */
271 2753 jones
    private void checkIndexPaths() {
272
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
273 2521 sgarg
        MetaCatUtil.pathsForIndexing
274 2758 sgarg
            = MetaCatUtil.getOptionList(MetaCatUtil.getOption("indexPaths"));
275 2570 jones
276 2521 sgarg
        if (MetaCatUtil.pathsForIndexing != null) {
277 2570 jones
278 2663 sgarg
            MetaCatUtil.printMessage("Indexing paths specified in metacat.properties....");
279 2570 jones
280 2521 sgarg
            DBConnection conn = null;
281
            int serialNumber = -1;
282
            PreparedStatement pstmt = null;
283
            PreparedStatement pstmt1 = null;
284
            ResultSet rs = null;
285 2570 jones
286 2521 sgarg
            for (int i = 0; i < MetaCatUtil.pathsForIndexing.size(); i++) {
287 2753 jones
                logMetacat.debug("Checking if '"
288 2521 sgarg
                           + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
289 2663 sgarg
                           + "' is indexed.... ");
290 2570 jones
291 2521 sgarg
                try {
292
                    //check out DBConnection
293
                    conn = DBConnectionPool.
294
                        getDBConnection("MetaCatServlet.checkIndexPaths");
295
                    serialNumber = conn.getCheckOutSerialNumber();
296 2570 jones
297 2521 sgarg
                    pstmt = conn.prepareStatement(
298
                        "SELECT * FROM xml_path_index " + "WHERE path = ?");
299
                    pstmt.setString(1, (String) MetaCatUtil.pathsForIndexing
300
                                    .elementAt(i));
301 2570 jones
302 2521 sgarg
                    pstmt.execute();
303
                    rs = pstmt.getResultSet();
304 2570 jones
305 2521 sgarg
                    if (!rs.next()) {
306 2753 jones
                        logMetacat.debug(".....not indexed yet.");
307 2521 sgarg
                        rs.close();
308
                        pstmt.close();
309
                        conn.increaseUsageCount(1);
310 2570 jones
311 2663 sgarg
                        logMetacat.debug(
312 2521 sgarg
                              "Inserting following path in xml_path_index: "
313
                              + (String)MetaCatUtil.pathsForIndexing
314 2663 sgarg
                                                   .elementAt(i));
315 2836 sgarg
   			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 2521 sgarg
                        pstmt.setString(1, (String) MetaCatUtil.
329
                                        pathsForIndexing.elementAt(i));
330
                        pstmt.execute();
331
                        rs = pstmt.getResultSet();
332 2570 jones
333 2521 sgarg
                        int count = 0;
334 2663 sgarg
                        logMetacat.debug(
335 2521 sgarg
                                       "Executed the select statement for: "
336
                                       + (String) MetaCatUtil.pathsForIndexing
337 2663 sgarg
                                         .elementAt(i));
338 2570 jones
339 2521 sgarg
                        try {
340
                            while (rs.next()) {
341 2570 jones
342 2521 sgarg
                                String docid = rs.getString(1);
343
                                String nodedata = rs.getString(2);
344
                                float nodedatanumerical = rs.getFloat(3);
345
                                int parentnodeid = rs.getInt(4);
346 2570 jones
347 2521 sgarg
                                if (!nodedata.trim().equals("")) {
348
                                    pstmt1 = conn.prepareStatement(
349
                                        "INSERT INTO xml_path_index"
350
                                        + " (docid, path, nodedata, "
351
                                        + "nodedatanumerical, parentnodeid)"
352
                                        + " VALUES (?, ?, ?, ?, ?)");
353 2570 jones
354 2521 sgarg
                                    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 2701 sgarg
                                    pstmt1.setInt(5, parentnodeid);
360 2570 jones
361 2521 sgarg
                                    pstmt1.execute();
362
                                    pstmt1.close();
363 2570 jones
364 2521 sgarg
                                    count++;
365 2570 jones
366 2521 sgarg
                                }
367
                            }
368
                        }
369
                        catch (Exception e) {
370
                            System.out.println("Exception:" + e.getMessage());
371
                            e.printStackTrace();
372
                        }
373 2570 jones
374 2521 sgarg
                        rs.close();
375
                        pstmt.close();
376
                        conn.increaseUsageCount(1);
377 2570 jones
378 2753 jones
                        logMetacat.info("Indexed " + count
379 2521 sgarg
                                + " records from xml_nodes for '"
380
                                + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
381 2663 sgarg
                                + "'");
382 2570 jones
383 2521 sgarg
                    } else {
384 2753 jones
                    	logMetacat.debug(".....already indexed.");
385 2521 sgarg
                    }
386 2570 jones
387 2521 sgarg
                    rs.close();
388
                    pstmt.close();
389
                    conn.increaseUsageCount(1);
390 2570 jones
391 2521 sgarg
                } catch (Exception e) {
392 2663 sgarg
                    logMetacat.error("Error in MetaCatServlet.checkIndexPaths: "
393
                                             + e.getMessage());
394 2521 sgarg
                }finally {
395
                    //check in DBonnection
396
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
397
                }
398 2570 jones
399
400 2521 sgarg
            }
401 2570 jones
402 2663 sgarg
            MetaCatUtil.printMessage("Path Indexing Completed");
403 2521 sgarg
        }
404 2682 sgarg
    }
405 1723 berkley
406 2098 jones
    /**
407
     * Control servlet response depending on the action parameter specified
408
     */
409
    private void handleGetOrPost(HttpServletRequest request,
410
            HttpServletResponse response) throws ServletException, IOException
411 2045 tao
    {
412 2752 jones
        MetaCatUtil util = new MetaCatUtil();
413 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
414
415 2098 jones
        /*
416 2753 jones
         * logMetacat.debug("Connection pool size: "
417 2098 jones
         * +connPool.getSizeOfDBConnectionPool(),10);
418 2753 jones
         * logMetacat.debug("Free DBConnection number: "
419 2098 jones
         */
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 1360 tao
425 2098 jones
        //Debug message to print out the method which have a busy DBConnection
426 2752 jones
        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 1360 tao
435 2098 jones
        String ctype = request.getContentType();
436
        if (ctype != null && ctype.startsWith("multipart/form-data")) {
437
            handleMultipartForm(request, response);
438
        } else {
439 1360 tao
440 2098 jones
            String name = null;
441
            String[] value = null;
442
            String[] docid = new String[3];
443
            Hashtable params = new Hashtable();
444
            Enumeration paramlist = request.getParameterNames();
445 1360 tao
446 2098 jones
            while (paramlist.hasMoreElements()) {
447 1360 tao
448 2098 jones
                name = (String) paramlist.nextElement();
449
                value = request.getParameterValues(name);
450 509 bojilova
451 2098 jones
                // 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 509 bojilova
461 2098 jones
                params.put(name, value);
462
            }
463 509 bojilova
464 2098 jones
            //handle param is emptpy
465
            if (params.isEmpty() || params == null) { return; }
466 509 bojilova
467 2098 jones
            //if the user clicked on the input images, decode which image
468
            //was clicked then set the action.
469 2252 sgarg
            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 2098 jones
            String action = ((String[]) params.get("action"))[0];
481 2753 jones
            logMetacat.info("Action is: " + action);
482 509 bojilova
483 2098 jones
            // 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 2682 sgarg
            name = null;
491
492 2098 jones
            // handle login action
493
            if (action.equals("login")) {
494
                PrintWriter out = response.getWriter();
495
                handleLoginAction(out, params, request, response);
496
                out.close();
497 2912 harris
498 2098 jones
                // handle logout action
499 2919 harris
            }   else if (action.equals("logout")) {
500 2098 jones
                PrintWriter out = response.getWriter();
501
                handleLogoutAction(out, params, request, response);
502
                out.close();
503 1360 tao
504 2098 jones
                // 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 1360 tao
524 2098 jones
                // 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 2753 jones
                    logMetacat.info(
530 2663 sgarg
                            "The session is new or no sessionid is assigned. The user is public");
531 2098 jones
                    username = "public";
532
                    sess.setAttribute("username", username);
533
                } else {
534 2753 jones
                    logMetacat.info("The session is either old or "
535 2668 sgarg
                            + "has sessionid parameter");
536 2098 jones
                    try {
537
                        if (params.containsKey("sessionid")) {
538
                            sess_id = ((String[]) params.get("sessionid"))[0];
539 2663 sgarg
                            logMetacat.info("in has sessionid "
540
                                    + sess_id);
541 2098 jones
                            if (sessionHash.containsKey(sess_id)) {
542 2663 sgarg
                                logMetacat.info("find the id "
543
                                        + sess_id + " in hash table");
544 2098 jones
                                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 2663 sgarg
                             * logMetacat.info("in no sessionid
551 2098 jones
                             * parameter ", 40); sess_id =
552
                             * (String)sess.getId();
553 2663 sgarg
                             * logMetacat.info("storing the session id "
554 2098 jones
                             * + sess_id + " which has username " +
555
                             * sess.getAttribute("username") + " into session
556
                             * hash in handleGetOrPost method", 35);
557
                             */
558
                        }
559
                    } catch (IllegalStateException ise) {
560 2663 sgarg
                        logMetacat.error(
561
                                "Error in handleGetOrPost: this shouldn't "
562 2098 jones
                                + "happen: the session should be valid: "
563
                                + ise.getMessage());
564
                    }
565 1360 tao
566 2098 jones
                    username = (String) sess.getAttribute("username");
567 2668 sgarg
                    logMetacat.info("The user name from session is: "
568 2663 sgarg
                            + username);
569 2098 jones
                    password = (String) sess.getAttribute("password");
570
                    groupnames = (String[]) sess.getAttribute("groupnames");
571 2682 sgarg
                    name = (String) sess.getAttribute("name");
572 2098 jones
                }
573 1360 tao
574 2098 jones
                //make user user username should be public
575
                if (username == null || (username.trim().equals(""))) {
576
                    username = "public";
577
                }
578 2753 jones
                logMetacat.info("The user is : " + username);
579 2098 jones
            }
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 2919 harris
            } else if ( action.trim().equals("spatial_query")) {
600
601 2970 sgarg
              logMetacat.debug("******************* SPATIAL QUERY ********************");
602 2919 harris
              PrintWriter out = response.getWriter();
603
              handleSpatialQuery(out, params, response, username, groupnames, sess_id);
604
              out.close();
605
606 2098 jones
            } else if (action.equals("export")) {
607 1298 tao
608 2169 sgarg
                handleExportAction(params, response, username,
609 2102 jones
                        groupnames, password);
610 2098 jones
            } else if (action.equals("read")) {
611 2102 jones
                handleReadAction(params, request, response, username, password,
612 2098 jones
                        groupnames);
613
            } else if (action.equals("readinlinedata")) {
614 2102 jones
                handleReadInlineDataAction(params, request, response, username,
615 2098 jones
                        password, groupnames);
616
            } else if (action.equals("insert") || action.equals("update")) {
617
                PrintWriter out = response.getWriter();
618
                if ((username != null) && !username.equals("public")) {
619 2102 jones
                    handleInsertOrUpdateAction(request, response,
620
                            out, params, username, groupnames);
621 2098 jones
                } else {
622 2252 sgarg
                    response.setContentType("text/xml");
623
                    out.println("<?xml version=\"1.0\"?>");
624
                    out.println("<error>");
625 2098 jones
                    out.println("Permission denied for user " + username + " "
626
                            + action);
627 2252 sgarg
                    out.println("</error>");
628 2098 jones
                }
629
                out.close();
630
            } else if (action.equals("delete")) {
631
                PrintWriter out = response.getWriter();
632
                if ((username != null) && !username.equals("public")) {
633 2102 jones
                    handleDeleteAction(out, params, request, response, username,
634 2098 jones
                            groupnames);
635
                } else {
636 2252 sgarg
                    response.setContentType("text/xml");
637
                    out.println("<?xml version=\"1.0\"?>");
638
                    out.println("<error>");
639 2098 jones
                    out.println("Permission denied for " + action);
640 2252 sgarg
                    out.println("</error>");
641 2098 jones
                }
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 2113 jones
            } else if (action.equals("getlog")) {
682 2558 sgarg
                handleGetLogAction(params, request, response, username, groupnames);
683 2682 sgarg
            } 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 2312 jones
            } else if (action.equals("buildindex")) {
705 2558 sgarg
                handleBuildIndexAction(params, request, response, username, groupnames);
706 2098 jones
            } else if (action.equals("login") || action.equals("logout")) {
707 2312 jones
                /*
708 2098 jones
            } 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 2099 jones
                        Hashtable qparams = MetaCatUtil.parseQuery(u.getQuery());
736 2098 jones
                        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 2312 jones
                */
754 2098 jones
            } 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 1360 tao
764 2098 jones
            //util.closeConnections();
765
            // Close the stream to the client
766
            //out.close();
767
        }
768
    }
769 425 bojilova
770 2912 harris
    /////////////////////////////// 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 2938 harris
     *
776
     * handleSQuery(out, params, response, username, groupnames,
777
     *                        sess_id);
778 2912 harris
     */
779 2919 harris
    private void handleSpatialQuery(PrintWriter out, Hashtable params,
780
                                    HttpServletResponse response,
781
                                    String username, String[] groupnames,
782
                                    String sess_id) {
783
784 2912 harris
      Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
785 2970 sgarg
      //MBJDELETED MetacatSpatialQuery _spatialQuery = new MetacatSpatialQuery();
786 2946 sgarg
787 2948 sgarg
	if (MetacatSpatialConstants.runSpatialOption == false ) {
788 2946 sgarg
        	response.setContentType("text/html");
789
        	out.println("<html> Metacat Spatial Option is turned off <html>");
790
        	out.close();
791
		return ;
792
	}
793
794 2912 harris
      MetacatSpatialQuery _spatialQuery = new MetacatSpatialQuery();
795
796
797
      // switch -- html/xml print
798 2970 sgarg
      //MBJDELETED boolean printXML = false;
799 2912 harris
800
      // get the spatial parameters
801 2970 sgarg
      logMetacat.debug("params: " +  params);
802 2912 harris
      //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 2970 sgarg
      logMetacat.debug("\nxmax: " + _xmax + " \nymax:" + _ymax +
808 2912 harris
                      "\nxmin: " + _xmin + "\nymin: " + _ymin);
809
810 3028 perry
      // 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 2912 harris
816 3028 perry
      // 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 2912 harris
828 3028 perry
      // 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 2938 harris
      // issue the Spatial query
838 2970 sgarg
      //MBJ DELETED MetacatSpatialDataset _data =
839
        //MBJ DELETED _spatialQuery.queryDatasetByCartesianBounds(_xmin, _ymin, _xmax, _ymax);
840 2912 harris
841 2938 harris
      // report the number of documents returned:
842 2970 sgarg
      //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 2938 harris
      logMetacat.warn("\nThe number of documents in the BBOX query: "
847
              + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
848 2946 sgarg
849 2938 harris
850 2919 harris
      // create an s-query
851
      String[] queryArray = new String[1];
852
      queryArray[0] = DocumentIdQuery.createDocidQuery(_data.getDocidList());
853
      params.put("query", queryArray);
854 2938 harris
855
      // qformat
856 2919 harris
      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 2912 harris
      // return the list of docs and point at the spatial theme
866
      if ( printXML) {
867
        response.setContentType("text/xml");
868 2915 harris
        out.println(_data.toXML() ); // write the data as xml
869 2912 harris
        out.close();
870
      } else {
871 2919 harris
        logMetacat.warn("username: " + username+"\nsession: "+sess_id);
872
        handleSQuery(out, params, response, username, groupnames, sess_id);
873 2912 harris
      }
874 2946 sgarg
} else {
875
        response.setContentType("text/html");
876
        out.println("<html>No Datasets Selected <html>");
877
        out.close();
878
}
879 2970 sgarg
*/
880 2946 sgarg
881 2912 harris
    }
882
883 2970 sgarg
    /**
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 3028 perry
	sb.append("<queryterm searchmode=\"greater-than\" casesensitive=\"false\">");
912 2970 sgarg
	sb.append("<value>" + _ymin + "</value>");
913
	sb.append("<pathexpr>northBoundingCoordinate</pathexpr>");
914
	sb.append("</queryterm>");
915 3028 perry
	sb.append("<queryterm searchmode=\"less-than\" casesensitive=\"false\">");
916 2970 sgarg
	sb.append("<value>" + _ymax + "</value>");
917 3028 perry
	sb.append("<pathexpr>southBoundingCoordinate</pathexpr>");
918 2970 sgarg
	sb.append("</queryterm>");
919 3028 perry
	sb.append("<queryterm searchmode=\"greater-than\" casesensitive=\"false\">");
920 2970 sgarg
	sb.append("<value>" + _xmin + "</value>");
921 3028 perry
	sb.append("<pathexpr>eastBoundingCoordinate</pathexpr>");
922 2970 sgarg
	sb.append("</queryterm>");
923 3028 perry
 	sb.append("<queryterm searchmode=\"less-than\" casesensitive=\"false\">");
924 2970 sgarg
	sb.append("<value>" + _xmax + "</value>");
925
	sb.append("<pathexpr>westBoundingCoordinate</pathexpr>");
926
	sb.append("</queryterm>");
927
	sb.append("</querygroup>");
928
	sb.append("</pathquery>");
929 2912 harris
930 2970 sgarg
	return sb.toString();
931
    }
932
933 2098 jones
    // 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 943 tao
    {
941 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
942 2098 jones
        AuthSession sess = null;
943 2252 sgarg
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 2912 harris
        //}
954
955 2252 sgarg
        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 2098 jones
        String un = ((String[]) params.get("username"))[0];
965 2753 jones
        logMetacat.info("user " + un + " is trying to login");
966 2098 jones
        String pw = ((String[]) params.get("password"))[0];
967 943 tao
968 2252 sgarg
        String qformat = "xml";
969
        if(params.get("qformat") != null){
970
            qformat = ((String[]) params.get("qformat"))[0];
971
        }
972
973 2098 jones
        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 1360 tao
983 2098 jones
        //if it is authernticate is true, store the session
984
        if (isValid) {
985
            HttpSession session = sess.getSessions();
986
            String id = session.getId();
987 2663 sgarg
            logMetacat.info("Store session id " + id
988 2098 jones
                    + "which has username" + session.getAttribute("username")
989 2663 sgarg
                    + " into hash in login method");
990 2098 jones
            sessionHash.put(id, session);
991
        }
992 1360 tao
993 2098 jones
        // 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 1360 tao
1006 2663 sgarg
                logMetacat.error(
1007 2098 jones
                        "Error in MetaCatServlet.handleLoginAction: "
1008 2663 sgarg
                                + e.getMessage());
1009 2098 jones
            }
1010
        }
1011
    }
1012 1716 berkley
1013 2098 jones
    /**
1014
     * Handle the logout request. Close the connection.
1015
     */
1016
    private void handleLogoutAction(PrintWriter out, Hashtable params,
1017
            HttpServletRequest request, HttpServletResponse response)
1018 1483 tao
    {
1019 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1020 2252 sgarg
        String qformat = "xml";
1021
        if(params.get("qformat") != null){
1022
            qformat = ((String[]) params.get("qformat"))[0];
1023
        }
1024 1716 berkley
1025 2098 jones
        // close the connection
1026
        HttpSession sess = request.getSession(false);
1027 2663 sgarg
        logMetacat.info("After get session in logout request");
1028 2098 jones
        if (sess != null) {
1029 2663 sgarg
            logMetacat.info("The session id " + sess.getId()
1030
                    + " will be invalidate in logout action");
1031 2753 jones
            logMetacat.info("The session contains user "
1032 2098 jones
                    + sess.getAttribute("username")
1033 2663 sgarg
                    + " will be invalidate in logout action");
1034 2098 jones
            sess.invalidate();
1035
        }
1036 1716 berkley
1037 2098 jones
        // 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 1483 tao
1044 2098 jones
        //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 2663 sgarg
                logMetacat.error(
1057 2098 jones
                        "Error in MetaCatServlet.handleLogoutAction"
1058 2663 sgarg
                                + e.getMessage());
1059 2098 jones
            }
1060 1716 berkley
        }
1061 2098 jones
    }
1062 1483 tao
1063 2098 jones
    // END OF LOGIN & LOGOUT SECTION
1064 1716 berkley
1065 2098 jones
    // SQUERY & QUERY SECTION
1066
    /**
1067
     * Retreive the squery xml, execute it and display it
1068 2169 sgarg
     *
1069 2098 jones
     * @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 2570 jones
    private void handleSQuery(PrintWriter out, Hashtable params,
1076 2098 jones
            HttpServletResponse response, String user, String[] groups,
1077
            String sessionid)
1078
    {
1079
        double startTime = System.currentTimeMillis() / 1000;
1080 2752 jones
        DBQuery queryobj = new DBQuery();
1081 2098 jones
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1082
        double outPutTime = System.currentTimeMillis() / 1000;
1083 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1084
        logMetacat.info("Total search time for action 'squery': "
1085 2663 sgarg
                + (outPutTime - startTime));
1086 2098 jones
    }
1087 1716 berkley
1088 2098 jones
    /**
1089
     * Create the xml query, execute it and display the results.
1090 2169 sgarg
     *
1091 2098 jones
     * @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 2570 jones
    private void handleQuery(PrintWriter out, Hashtable params,
1097 2098 jones
            HttpServletResponse response, String user, String[] groups,
1098
            String sessionid)
1099 1490 tao
    {
1100 2098 jones
        //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 2752 jones
        DBQuery queryobj = new DBQuery();
1107 2098 jones
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1108
        double outPutTime = System.currentTimeMillis() / 1000;
1109 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1110
        logMetacat.info("Total search time for action 'query': "
1111 2663 sgarg
                + (outPutTime - startTime));
1112 1716 berkley
1113 2098 jones
        //handleSQuery(out, params, response,user, groups, sessionid);
1114 1490 tao
    }
1115 1716 berkley
1116 2098 jones
    // END OF SQUERY & QUERY SECTION
1117 1716 berkley
1118 2098 jones
    //Exoport section
1119
    /**
1120
     * Handle the "export" request of data package from Metacat in zip format
1121 2169 sgarg
     *
1122 2098 jones
     * @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 2169 sgarg
    private void handleExportAction(Hashtable params,
1128
            HttpServletResponse response,
1129 2102 jones
            String user, String[] groups, String passWord)
1130 2098 jones
    {
1131 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1132 2098 jones
        // Output stream
1133
        ServletOutputStream out = null;
1134
        // Zip output stream
1135
        ZipOutputStream zOut = null;
1136
        DBQuery queryObj = null;
1137 1716 berkley
1138 2098 jones
        String[] docs = new String[10];
1139
        String docId = "";
1140 1360 tao
1141 731 bojilova
        try {
1142 2098 jones
            // read the params
1143
            if (params.containsKey("docid")) {
1144
                docs = (String[]) params.get("docid");
1145 731 bojilova
            }
1146 2098 jones
            // Create a DBuery to handle export
1147 2752 jones
            queryObj = new DBQuery();
1148 2098 jones
            // 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 2556 sgarg
            response.setHeader("Content-Disposition",
1168
            		"attachment; filename="
1169
            		+ docId + ".zip"); // Set the name of the zip file
1170
1171 2098 jones
            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 731 bojilova
1177 2098 jones
        } 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 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1198 2098 jones
                        + "in MetacatServlet.handleExportAction: "
1199 2663 sgarg
                        + ioe.getMessage());
1200 731 bojilova
            }
1201
1202 2663 sgarg
            logMetacat.error(
1203 2098 jones
                    "Error in MetacatServlet.handleExportAction: "
1204 2663 sgarg
                            + e.getMessage());
1205 2098 jones
            e.printStackTrace(System.out);
1206
1207 731 bojilova
        }
1208 1360 tao
1209 2098 jones
    }
1210 1360 tao
1211 2098 jones
    /**
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 2169 sgarg
     *
1216 2098 jones
     * @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 2169 sgarg
            HttpServletRequest request, HttpServletResponse response,
1223 2102 jones
            String user, String passWord, String[] groups)
1224 2098 jones
    {
1225 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1226 2098 jones
        String[] docs = new String[10];
1227
        String inlineDataId = null;
1228
        String docId = "";
1229
        ServletOutputStream out = null;
1230 1360 tao
1231 2098 jones
        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 2169 sgarg
            if (inlineDataId == null || inlineDataId.equals("")) {
1240 2098 jones
                throw new Exception("You didn't specify requested inlinedataid"); }
1241 1360 tao
1242 2098 jones
            // 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 2245 sgarg
                    AccessControlInterface.READSTRING))
1249
            {
1250 2098 jones
                throw new Exception("User " + user
1251
                        + " doesn't have permission " + " to read document "
1252
                        + docId);
1253
            }
1254 2245 sgarg
            else
1255
            {
1256
              //check data access level
1257
              try
1258
              {
1259
                Hashtable unReadableInlineDataList =
1260 2292 sgarg
                    PermissionController.getUnReadableInlineDataIdList(docId,
1261
                    user, groups, false);
1262
                if (unReadableInlineDataList.containsValue(
1263
                          MetaCatUtil.getInlineDataIdWithoutRev(inlineDataId)))
1264 2245 sgarg
                {
1265
                  throw new Exception("User " + user
1266
                       + " doesn't have permission " + " to read inlinedata "
1267
                       + inlineDataId);
1268 2098 jones
1269 2245 sgarg
                }//if
1270
              }//try
1271
              catch (Exception e)
1272
              {
1273
                throw e;
1274
              }//catch
1275
            }//else
1276
1277 2098 jones
            // 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 1292 tao
            out.close();
1290 1360 tao
1291 2169 sgarg
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1292 2102 jones
                    inlineDataId, "readinlinedata");
1293 2098 jones
        } 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 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1314 2098 jones
                        + "in MetacatServlet.handleExportAction: "
1315 2663 sgarg
                        + ioe.getMessage());
1316 2098 jones
            }
1317 2663 sgarg
            logMetacat.error(
1318 2098 jones
                    "Error in MetacatServlet.handleReadInlineDataAction: "
1319 2663 sgarg
                            + e.getMessage());
1320 1292 tao
        }
1321 2098 jones
    }
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 1292 tao
    {
1329 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1330 2098 jones
        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 1360 tao
1341 2098 jones
        try {
1342
            //check out DBConnection
1343
            conn = DBConnectionPool
1344
                    .getDBConnection("AccessControlList.isAllowFirst");
1345
            serialNumber = conn.getCheckOutSerialNumber();
1346 1360 tao
1347 2098 jones
            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 1292 tao
        }
1370 2753 jones
        logMetacat.debug("The nodeid for inlinedataid " + inLineDataId
1371 2663 sgarg
                + " is: " + nodeId);
1372 2098 jones
        return nodeId;
1373
    }
1374 1360 tao
1375 2098 jones
    /**
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 2169 sgarg
     *
1380 2098 jones
     * @param params the Hashtable of HTTP request parameters
1381 2102 jones
     * @param request the HTTP request object linked to the client
1382 2098 jones
     * @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 2102 jones
    private void handleReadAction(Hashtable params, HttpServletRequest request,
1387 2098 jones
            HttpServletResponse response, String user, String passWord,
1388
            String[] groups)
1389
    {
1390 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1391 2098 jones
        ServletOutputStream out = null;
1392
        ZipOutputStream zout = null;
1393
        PrintWriter pw = null;
1394
        boolean zip = false;
1395
        boolean withInlineData = true;
1396 1360 tao
1397 2098 jones
        try {
1398
            String[] docs = new String[0];
1399
            String docid = "";
1400
            String qformat = "";
1401
            String abstrpath = null;
1402 731 bojilova
1403 2098 jones
            // 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 2245 sgarg
            // we don't support read a eml document without inline data now.
1412
            /*if (params.containsKey("inlinedata")) {
1413 1360 tao
1414 2098 jones
                String inlineData = ((String[]) params.get("inlinedata"))[0];
1415
                if (inlineData.equalsIgnoreCase("false")) {
1416
                    withInlineData = false;
1417
                }
1418 2245 sgarg
            }*/
1419 2098 jones
            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 1360 tao
1429 2098 jones
                    URL murl = new URL(docs[i]);
1430 2099 jones
                    Hashtable murlQueryStr = MetaCatUtil.parseQuery(
1431
                            murl.getQuery());
1432 2098 jones
                    // 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 2102 jones
                            addDocToZip(request, docid, zout, user, groups);
1439 2098 jones
                        } else {
1440 2102 jones
                            readFromMetacat(request, response, docid, qformat,
1441 2098 jones
                                    abstrpath, user, groups, zip, zout,
1442
                                    withInlineData, params);
1443
                        }
1444 1360 tao
1445 2098 jones
                        // case docid="http://.../filename"
1446
                    } else {
1447
                        docid = docs[i];
1448
                        if (zip) {
1449 2102 jones
                            addDocToZip(request, docid, zout, user, groups);
1450 2098 jones
                        } else {
1451
                            readFromURLConnection(response, docid);
1452
                        }
1453
                    }
1454 2169 sgarg
1455 2098 jones
                } catch (MalformedURLException mue) {
1456
                    docid = docs[i];
1457
                    if (zip) {
1458 2102 jones
                        addDocToZip(request, docid, zout, user, groups);
1459 2098 jones
                    } else {
1460 2169 sgarg
                        readFromMetacat(request, response, docid, qformat,
1461
                                abstrpath, user, groups, zip, zout,
1462 2102 jones
                                withInlineData, params);
1463 2098 jones
                    }
1464
                }
1465 2099 jones
            }
1466 1360 tao
1467 2098 jones
            if (zip) {
1468
                zout.finish(); //terminate the zip file
1469
                zout.close(); //close the zip stream
1470
            }
1471 1360 tao
1472 2098 jones
        } 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 2663 sgarg
            logMetacat.warn("Missed id: " + notFoundDocId);
1478
            logMetacat.warn("Missed rev: " + notFoundRevision);
1479 2098 jones
            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 1360 tao
1492 2098 jones
            } catch (Exception exc) {
1493 2663 sgarg
                logMetacat.error(
1494 2098 jones
                        "Erorr in MetacatServlet.hanldReadAction: "
1495 2663 sgarg
                                + exc.getMessage());
1496 2098 jones
                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 1360 tao
1508 2098 jones
                    } 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 2663 sgarg
                    logMetacat.error("Problem with the servlet output "
1527 2098 jones
                            + "in MetacatServlet.handleReadAction: "
1528 2663 sgarg
                            + ie.getMessage());
1529 2098 jones
                }
1530
            }
1531
        } catch (Exception e) {
1532
            try {
1533 1716 berkley
1534 2098 jones
                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 1360 tao
1555 2098 jones
                }
1556
                // Close zip output stream
1557
                if (zout != null) {
1558
                    zout.close();
1559
                }
1560 1360 tao
1561 2098 jones
            } catch (IOException ioe) {
1562 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1563 2098 jones
                        + "in MetacatServlet.handleReadAction: "
1564 2663 sgarg
                        + ioe.getMessage());
1565 2098 jones
                ioe.printStackTrace(System.out);
1566 731 bojilova
1567 2098 jones
            }
1568 1360 tao
1569 2663 sgarg
            logMetacat.error(
1570 2098 jones
                    "Error in MetacatServlet.handleReadAction: "
1571 2663 sgarg
                            + e.getMessage());
1572 2098 jones
            //e.printStackTrace(System.out);
1573 731 bojilova
        }
1574 2098 jones
    }
1575 1360 tao
1576 2169 sgarg
    /** read metadata or data from Metacat
1577 2098 jones
     */
1578 2169 sgarg
    private void readFromMetacat(HttpServletRequest request,
1579 2102 jones
            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 1292 tao
    {
1585 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1586 2098 jones
        try {
1587 2648 tao
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 2098 jones
            DocumentImpl doc = new DocumentImpl(docid);
1597 1360 tao
1598 2098 jones
            //check the permission for read
1599 2113 jones
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1600 2098 jones
                Exception e = new Exception("User " + user
1601
                        + " does not have permission"
1602
                        + " to read the document with the docid " + docid);
1603 731 bojilova
1604 2098 jones
                throw e;
1605
            }
1606 1360 tao
1607 2098 jones
            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 1360 tao
1617 2098 jones
                //MIME type
1618
                String contentType = getServletContext().getMimeType(filename);
1619
                if (contentType == null) {
1620
                    ContentTypeProvider provider = new ContentTypeProvider(
1621
                            docid);
1622
                    contentType = provider.getContentType();
1623 2753 jones
                    logMetacat.info("Final contenttype is: "
1624 2663 sgarg
                            + contentType);
1625 2098 jones
                }
1626 731 bojilova
1627 2098 jones
                response.setContentType(contentType);
1628
                // if we decide to use "application/octet-stream" for all data
1629
                // returns
1630
                // response.setContentType("application/octet-stream");
1631 731 bojilova
1632 2098 jones
                try {
1633 731 bojilova
1634 2098 jones
                    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 2169 sgarg
1645 2098 jones
            } else {
1646
                // this is metadata doc
1647 2273 sgarg
                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 2098 jones
                    // 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 1360 tao
1658 2098 jones
                    // 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 1360 tao
1667 2098 jones
            }
1668 2169 sgarg
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1669 2101 jones
                    docid, "read");
1670 2098 jones
        } catch (Exception except) {
1671
            throw except;
1672
        }
1673
    }
1674 1360 tao
1675 2169 sgarg
    /**
1676
     * read data from URLConnection
1677 2098 jones
     */
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 1360 tao
        }
1704 2098 jones
        response.setContentType(contentType);
1705
        // if we decide to use "application/octet-stream" for all data returns
1706
        // response.setContentType("application/octet-stream");
1707 1360 tao
1708 2098 jones
        // this is http url
1709
        URL url = new URL(docid);
1710
        BufferedInputStream bis = null;
1711
        try {
1712
            bis = new BufferedInputStream(url.openStream());
1713 731 bojilova
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1714 2098 jones
            int b = bis.read(buf);
1715 731 bojilova
            while (b != -1) {
1716 2098 jones
                out.write(buf, 0, b);
1717
                b = bis.read(buf);
1718 731 bojilova
            }
1719 2098 jones
        } finally {
1720
            if (bis != null) bis.close();
1721 636 berkley
        }
1722 1360 tao
1723 636 berkley
    }
1724 1360 tao
1725 2169 sgarg
    /**
1726 2098 jones
     * read file/doc and write to ZipOutputStream
1727 2169 sgarg
     *
1728 2098 jones
     * @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 2169 sgarg
    private void addDocToZip(HttpServletRequest request, String docid,
1739 2102 jones
            ZipOutputStream zout, String user, String[] groups) throws
1740
            ClassNotFoundException, IOException, SQLException, McdbException,
1741
            Exception
1742 1293 tao
    {
1743 2098 jones
        byte[] bytestring = null;
1744
        ZipEntry zentry = null;
1745 1360 tao
1746 598 bojilova
        try {
1747 2098 jones
            URL url = new URL(docid);
1748 1360 tao
1749 2098 jones
            // 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 1716 berkley
1766 2098 jones
        } catch (MalformedURLException mue) {
1767 203 jones
1768 2098 jones
            // this is metacat doc (data file or metadata doc)
1769
            try {
1770
                DocumentImpl doc = new DocumentImpl(docid);
1771 1360 tao
1772 2098 jones
                //check the permission for read
1773 2113 jones
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1774 2098 jones
                    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 1360 tao
1781 2098 jones
                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 1360 tao
1792 2098 jones
                        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 1716 berkley
1805 2098 jones
                } 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 2169 sgarg
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1815 2101 jones
                        docid, "read");
1816 2098 jones
            } catch (Exception except) {
1817
                throw except;
1818
            }
1819 1360 tao
        }
1820 2098 jones
    }
1821 309 bojilova
1822 2098 jones
    /**
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 1466 tao
    {
1831 2098 jones
        // 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 203 jones
    }
1852
1853 2098 jones
    /**
1854
     * Handle the database putdocument request and write an XML document to the
1855
     * database connection
1856
     */
1857 2102 jones
    private void handleInsertOrUpdateAction(HttpServletRequest request,
1858
            HttpServletResponse response, PrintWriter out, Hashtable params,
1859 2098 jones
            String user, String[] groups)
1860
    {
1861 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1862 2098 jones
        DBConnection dbConn = null;
1863
        int serialNumber = -1;
1864 1360 tao
1865 2252 sgarg
        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 2663 sgarg
            logMetacat.error("Docid not specified");
1871 2252 sgarg
            return;
1872
        }
1873 2576 sgarg
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 2663 sgarg
            logMetacat.error("User '" + user + "' not allowed to insert and update");
1880 2576 sgarg
            return;
1881
        }
1882 2252 sgarg
1883 2098 jones
        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 1360 tao
1891 2098 jones
            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 2347 sgarg
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 2098 jones
            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 2711 sgarg
                } else {
1923
1924 2169 sgarg
                    String namespace = findNamespace(xml);
1925 2711 sgarg
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 2169 sgarg
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1937 2711 sgarg
                			// 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 2098 jones
                }
1951 695 bojilova
1952 2098 jones
                String[] action = (String[]) params.get("action");
1953
                String[] docid = (String[]) params.get("docid");
1954
                String newdocid = null;
1955 695 bojilova
1956 2098 jones
                String doAction = null;
1957
                if (action[0].equals("insert")) {
1958
                    doAction = "INSERT";
1959
                } else if (action[0].equals("update")) {
1960
                    doAction = "UPDATE";
1961
                }
1962 695 bojilova
1963 2098 jones
                try {
1964
                    // get a connection from the pool
1965
                    dbConn = DBConnectionPool
1966
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1967
                    serialNumber = dbConn.getCheckOutSerialNumber();
1968 1716 berkley
1969 2098 jones
                    // write the document to the database
1970
                    try {
1971
                        String accNumber = docid[0];
1972 2753 jones
                        logMetacat.debug("" + doAction + " "
1973 2663 sgarg
                                + accNumber + "...");
1974 2098 jones
                        if (accNumber.equals("")) {
1975
                            accNumber = null;
1976 2102 jones
                        }
1977 2098 jones
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1978
                                doAction, accNumber, user, groups);
1979 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
1980 2102 jones
                                user, accNumber, action[0]);
1981
                    } catch (NullPointerException npe) {
1982 2098 jones
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1983
                                doAction, null, user, groups);
1984 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
1985 2102 jones
                                user, "", action[0]);
1986
                    }
1987
                }
1988 2098 jones
                finally {
1989
                    // Return db connection
1990
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1991
                }
1992 1716 berkley
1993 2098 jones
                // 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 1716 berkley
2000 2098 jones
            } 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 2690 sgarg
                logMetacat.warn("Error in writing eml document to the database" + npe.getMessage());
2007 2729 sgarg
                npe.printStackTrace();
2008 2098 jones
            }
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 2690 sgarg
            logMetacat.warn("Error in writing eml document to the database" + e.getMessage());
2016 2729 sgarg
            e.printStackTrace();
2017 1760 tao
        }
2018 1409 tao
    }
2019 1716 berkley
2020 2098 jones
    /**
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 1629 tao
    {
2027 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2028 2098 jones
        StringBuffer cbuff = new StringBuffer();
2029
        java.util.Stack st = new java.util.Stack();
2030
        boolean validate = false;
2031
        int c;
2032
        int inx;
2033 2089 tao
2034 2098 jones
        // 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 1716 berkley
2038 2098 jones
            // "<!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 203 jones
2062 2098 jones
        // close the stream
2063
        xmlreader.reset();
2064 1360 tao
2065 2098 jones
        // 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 1360 tao
2076 2753 jones
        logMetacat.info("Validation for dtd is " + validate);
2077 2098 jones
        return validate;
2078 1360 tao
    }
2079
2080 2098 jones
    // END OF INSERT/UPDATE SECTION
2081 68 higgins
2082 2098 jones
    /* check if the xml string contains key words to specify schema loocation */
2083 2169 sgarg
    private String findNamespace(StringReader xml) throws IOException
2084 2098 jones
    {
2085 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2086 2169 sgarg
        String namespace = null;
2087
2088
        String eml2_0_0NameSpace = DocumentImpl.EML2_0_0NAMESPACE;
2089 2224 sgarg
        String eml2_0_1NameSpace = DocumentImpl.EML2_0_1NAMESPACE;
2090 2169 sgarg
        String eml2_1_0NameSpace = DocumentImpl.EML2_1_0NAMESPACE;
2091
2092 2098 jones
        if (xml == null) {
2093 2753 jones
            logMetacat.debug("Validation for schema is "
2094 2663 sgarg
                    + namespace);
2095 2169 sgarg
            return namespace;
2096 2098 jones
        }
2097
        String targetLine = getSchemaLine(xml);
2098 2918 sgarg
2099 2098 jones
        if (targetLine != null) {
2100 1360 tao
2101 2711 sgarg
        	// find if the root element has prefix
2102
        	String prefix = getPrefix(targetLine);
2103 2729 sgarg
        	logMetacat.info("prefix is:" + prefix);
2104 2711 sgarg
        	int startIndex = 0;
2105
2106 2729 sgarg
2107 2711 sgarg
        	if(prefix != null)
2108
        	{
2109
        		// if prefix found then look for xmlns:prefix
2110
        		// element to find the ns
2111 2712 sgarg
        		String namespaceWithPrefix = NAMESPACEKEYWORD
2112
        					+ ":" + prefix;
2113 2711 sgarg
        		startIndex = targetLine.indexOf(namespaceWithPrefix);
2114 2753 jones
            	logMetacat.debug("namespaceWithPrefix is:" + namespaceWithPrefix+":");
2115
            	logMetacat.debug("startIndex is:" + startIndex);
2116 2712 sgarg
2117 2711 sgarg
        	} else {
2118
        		// if prefix not found then look for xmlns
2119
        		// attribute to find the ns
2120
        		startIndex = targetLine.indexOf(NAMESPACEKEYWORD);
2121 2753 jones
            	logMetacat.debug("startIndex is:" + startIndex);
2122 2711 sgarg
        	}
2123
2124 2098 jones
            int start = 1;
2125
            int end = 1;
2126 2711 sgarg
            String namespaceString = null;
2127 2098 jones
            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 2711 sgarg
            }
2142
            // else: xmlns not found. namespace = null will be returned
2143
2144 2753 jones
         	logMetacat.debug("targetLine is " + targetLine);
2145 2729 sgarg
         	logMetacat.debug("start is " + end);
2146
         	logMetacat.debug("end is " + end);
2147
2148 2711 sgarg
            if(start < end){
2149
            	namespaceString = targetLine.substring(start + 1, end);
2150 2753 jones
            	logMetacat.debug("namespaceString is " + namespaceString);
2151 2098 jones
            }
2152 2753 jones
            logMetacat.debug("namespace in xml is: "
2153 2711 sgarg
                    + namespaceString);
2154 2729 sgarg
            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 2098 jones
            }
2165
        }
2166 185 jones
2167 2753 jones
        logMetacat.debug("Validation for eml is " + namespace);
2168 2224 sgarg
2169 2169 sgarg
        return namespace;
2170 1360 tao
2171 103 jones
    }
2172 68 higgins
2173 2098 jones
    private String getSchemaLine(StringReader xml) throws IOException
2174
    {
2175 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2176 2098 jones
        // find the line
2177
        String secondLine = null;
2178
        int count = 0;
2179
        int endIndex = 0;
2180
        int startIndex = 0;
2181 3002 sgarg
        final int TARGETNUM = 1;
2182 2098 jones
        StringBuffer buffer = new StringBuffer();
2183
        boolean comment = false;
2184 3002 sgarg
        boolean processingInstruction = false;
2185 2098 jones
        char thirdPreviousCharacter = '?';
2186
        char secondPreviousCharacter = '?';
2187
        char previousCharacter = '?';
2188
        char currentCharacter = '?';
2189 2268 sgarg
        int tmp = xml.read();
2190
        while (tmp != -1) {
2191
            currentCharacter = (char)tmp;
2192 2098 jones
            //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 68 higgins
2204 3002 sgarg
            //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 2098 jones
                count++;
2219
            }
2220 3002 sgarg
2221 2098 jones
            // 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 2268 sgarg
            tmp = xml.read();
2232 2098 jones
        }
2233
        secondLine = buffer.toString();
2234 2753 jones
        logMetacat.debug("the second line string is: " + secondLine);
2235 2663 sgarg
2236 2098 jones
        xml.reset();
2237
        return secondLine;
2238
    }
2239 253 jones
2240 2711 sgarg
    private String getPrefix(String schemaLine)
2241
    {
2242 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2243 2922 jones
        String prefix = null;
2244 3002 sgarg
2245 2922 jones
        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 2711 sgarg
2255 2922 jones
            if(rootElement.indexOf(":") > 0){
2256
                prefix = rootElement.substring(rootElement.indexOf(":") + 1,
2257
                    rootElement.length());
2258
            }
2259 3002 sgarg
2260 2922 jones
            if(prefix != null){
2261
                return prefix.trim();
2262
            }
2263
        }
2264
        return null;
2265 2711 sgarg
    }
2266
2267 2098 jones
    /**
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 2169 sgarg
            HttpServletRequest request, HttpServletResponse response,
2273 2102 jones
            String user, String[] groups)
2274 2098 jones
    {
2275 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2276 2098 jones
        String[] docid = (String[]) params.get("docid");
2277 1360 tao
2278 2251 sgarg
        if(docid == null){
2279
          response.setContentType("text/xml");
2280
          out.println("<?xml version=\"1.0\"?>");
2281
          out.println("<error>");
2282 2252 sgarg
          out.println("Docid not specified.");
2283 2251 sgarg
          out.println("</error>");
2284 2668 sgarg
          logMetacat.error("Docid not specified for the document to be deleted.");
2285 2251 sgarg
        } else {
2286 1360 tao
2287 2251 sgarg
            // delete the document from the database
2288 2098 jones
            try {
2289 2251 sgarg
2290
                try {
2291 2298 tao
                    // null means notify server is null
2292
                    DocumentImpl.delete(docid[0], user, groups, null);
2293 2251 sgarg
                    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 2753 jones
                    logMetacat.info("Document deleted.");
2301 2251 sgarg
                }
2302
                catch (AccessionNumberException ane) {
2303
                    response.setContentType("text/xml");
2304
                    out.println("<?xml version=\"1.0\"?>");
2305
                    out.println("<error>");
2306 2253 sgarg
                    //out.println("Error deleting document!!!");
2307 2251 sgarg
                    out.println(ane.getMessage());
2308
                    out.println("</error>");
2309 2668 sgarg
                    logMetacat.error("Document could not be deleted: "
2310
                    		+ ane.getMessage());
2311 2251 sgarg
                }
2312
            }
2313
            catch (Exception e) {
2314 2098 jones
                response.setContentType("text/xml");
2315
                out.println("<?xml version=\"1.0\"?>");
2316
                out.println("<error>");
2317 2251 sgarg
                out.println(e.getMessage());
2318 2098 jones
                out.println("</error>");
2319 2668 sgarg
                logMetacat.error("Document could not be deleted: "
2320
                		+ e.getMessage());
2321 2098 jones
            }
2322
        }
2323 1292 tao
    }
2324 1360 tao
2325 2098 jones
    /**
2326
     * Handle the validation request and return the results to the requestor
2327
     */
2328
    private void handleValidateAction(PrintWriter out, Hashtable params)
2329 1292 tao
    {
2330 1360 tao
2331 2098 jones
        // Get the document indicated
2332
        String valtext = null;
2333
        DBConnection dbConn = null;
2334
        int serialNumber = -1;
2335 1292 tao
2336 2098 jones
        try {
2337
            valtext = ((String[]) params.get("valtext"))[0];
2338
        } catch (Exception nullpe) {
2339 1360 tao
2340 2098 jones
            String docid = null;
2341
            try {
2342
                // Find the document id number
2343
                docid = ((String[]) params.get("docid"))[0];
2344 1360 tao
2345 2098 jones
                // Get the document indicated from the db
2346
                DocumentImpl xmldoc = new DocumentImpl(docid);
2347
                valtext = xmldoc.toString();
2348 688 bojilova
2349 2098 jones
            } catch (NullPointerException npe) {
2350 1360 tao
2351 2098 jones
                out.println("<error>Error getting document ID: " + docid
2352
                        + "</error>");
2353
                //if ( conn != null ) { util.returnConnection(conn); }
2354
                return;
2355
            } catch (Exception e) {
2356 688 bojilova
2357 2098 jones
                out.println(e.getMessage());
2358
            }
2359
        }
2360 688 bojilova
2361 2098 jones
        try {
2362
            // get a connection from the pool
2363
            dbConn = DBConnectionPool
2364
                    .getDBConnection("MetaCatServlet.handleValidateAction");
2365
            serialNumber = dbConn.getCheckOutSerialNumber();
2366 2752 jones
            DBValidate valobj = new DBValidate(dbConn);
2367 2098 jones
            boolean valid = valobj.validateString(valtext);
2368 1360 tao
2369 2098 jones
            // set content type and other response header fields first
2370 688 bojilova
2371 2098 jones
            out.println(valobj.returnErrors());
2372 731 bojilova
2373 2098 jones
        } catch (NullPointerException npe2) {
2374
            // set content type and other response header fields first
2375 1360 tao
2376 2098 jones
            out.println("<error>Error validating document.</error>");
2377
        } catch (Exception e) {
2378 731 bojilova
2379 2098 jones
            out.println(e.getMessage());
2380
        } finally {
2381
            // Return db connection
2382
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2383
        }
2384
    }
2385 1360 tao
2386 2098 jones
    /**
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 731 bojilova
2405 2098 jones
        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 1360 tao
2410 2098 jones
            // 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 731 bojilova
2417 2098 jones
        } 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 302 bojilova
2425 2098 jones
    }
2426 1360 tao
2427 2098 jones
    /**
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 302 bojilova
2439 2098 jones
        try {
2440 1360 tao
2441 2098 jones
            // 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 302 bojilova
2449 2098 jones
        } 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 1360 tao
    }
2459
2460 2098 jones
    /**
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 302 bojilova
2472 2098 jones
        } 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 699 bojilova
2480 2098 jones
    /**
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 1360 tao
2499 2098 jones
    /**
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 699 bojilova
2507 2098 jones
        String doctype = null;
2508
        String[] doctypeArr = (String[]) params.get("doctype");
2509 699 bojilova
2510 2098 jones
        // 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 699 bojilova
2516 2098 jones
        try {
2517
            DBUtil dbutil = new DBUtil();
2518
            String dtdschema = dbutil.readDTDSchema(doctype);
2519
            out.println(dtdschema);
2520 1360 tao
2521 2098 jones
        } 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 699 bojilova
2528 1360 tao
    }
2529
2530 2098 jones
    /**
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 699 bojilova
2538 2098 jones
        String scope = ((String[]) params.get("scope"))[0];
2539
        if (scope == null) {
2540
            scope = ((String[]) params.get("username"))[0];
2541
        }
2542 793 bojilova
2543 2098 jones
        try {
2544 1217 tao
2545 2098 jones
            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 793 bojilova
2553 2098 jones
        } 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 1217 tao
    }
2560 1360 tao
2561 2098 jones
    /**
2562 2113 jones
     * Print a report from the event log based on filter parameters passed in
2563
     * from the web.
2564 2169 sgarg
     *
2565 2113 jones
     * @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 2558 sgarg
            HttpServletResponse response, String username, String[] groups)
2571 2113 jones
    {
2572 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2573 2113 jones
        try {
2574 2312 jones
            response.setContentType("text/xml");
2575
            PrintWriter out = response.getWriter();
2576 2347 sgarg
2577 2312 jones
            // Check that the user is authenticated as an administrator account
2578 2558 sgarg
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2579 2312 jones
                out.print("<error>");
2580 2347 sgarg
                out.print("The user \"" + username +
2581 2312 jones
                        "\" is not authorized for this action.");
2582
                out.print("</error>");
2583
                return;
2584 2113 jones
            }
2585 2347 sgarg
2586 2312 jones
            // 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 2347 sgarg
2615 2312 jones
            // 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 2663 sgarg
            logMetacat.error(
2621
                    "Could not open http response for writing: " + e.getMessage());
2622 2113 jones
        }
2623 2312 jones
    }
2624 2169 sgarg
2625 2312 jones
    /**
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 2347 sgarg
    private void handleBuildIndexAction(Hashtable params,
2637 2312 jones
            HttpServletRequest request, HttpServletResponse response,
2638 2558 sgarg
            String username, String[] groups)
2639 2312 jones
    {
2640 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2641
2642 2312 jones
        // 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 2113 jones
        try {
2647
            response.setContentType("text/xml");
2648
            PrintWriter out = response.getWriter();
2649 2347 sgarg
2650 2312 jones
            // Check that the user is authenticated as an administrator account
2651 2558 sgarg
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2652 2312 jones
                out.print("<error>");
2653 2347 sgarg
                out.print("The user \"" + username +
2654 2312 jones
                        "\" 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 2113 jones
            out.close();
2683
        } catch (IOException e) {
2684 2663 sgarg
            logMetacat.error(
2685 2169 sgarg
                    "Could not open http response for writing: "
2686 2663 sgarg
                    + e.getMessage());
2687 2113 jones
        }
2688
    }
2689 2169 sgarg
2690 2113 jones
    /**
2691 2347 sgarg
     * Build the index for one document by reading the document and
2692 2312 jones
     * 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 2098 jones
     * 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 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2720 2098 jones
        PrintWriter out = null;
2721
        String action = null;
2722 793 bojilova
2723 2098 jones
        // Parse the multipart form, and save the parameters in a Hashtable and
2724
        // save the FileParts in a hashtable
2725 798 jones
2726 2098 jones
        Hashtable params = new Hashtable();
2727
        Hashtable fileList = new Hashtable();
2728
        int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2729
                .intValue();
2730 2663 sgarg
        logMetacat.info(
2731 2753 jones
                "The size limit of uploaded data files is: " + sizeLimit);
2732 798 jones
2733 2098 jones
        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 798 jones
2740 2098 jones
                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 798 jones
2753 2098 jones
                    // 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 2663 sgarg
                logMetacat.fatal("Fatal Error: couldn't get response output stream.");
2766 2098 jones
            }
2767
            out.println("<?xml version=\"1.0\"?>");
2768
            out.println("<error>");
2769
            out.println("Error: problem reading multipart data.");
2770
            out.println("</error>");
2771 798 jones
        }
2772
2773 2098 jones
        // Get the session information
2774
        String username = null;
2775
        String password = null;
2776
        String[] groupnames = null;
2777
        String sess_id = null;
2778 798 jones
2779 2098 jones
        // 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 1360 tao
2799 2098 jones
        // Get the out stream
2800
        try {
2801
            out = response.getWriter();
2802 798 jones
        } catch (IOException ioe2) {
2803 2663 sgarg
            logMetacat.error("Fatal Error: couldn't get response "
2804
                    + "output stream.");
2805 798 jones
        }
2806 1360 tao
2807 2098 jones
        if (action.equals("upload")) {
2808
            if (username != null && !username.equals("public")) {
2809
                handleUploadAction(request, out, params, fileList, username,
2810
                        groupnames);
2811
            } else {
2812 1360 tao
2813 2098 jones
                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 798 jones
    }
2832
2833 2098 jones
    /**
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 1041 tao
    {
2841 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2842 2098 jones
        //PrintWriter out = null;
2843
        //Connection conn = null;
2844
        String action = null;
2845
        String docid = null;
2846 798 jones
2847 2098 jones
        /*
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 798 jones
2854 2098 jones
        if (params.containsKey("docid")) {
2855
            docid = (String) params.get("docid");
2856
        }
2857 798 jones
2858 2098 jones
        // Make sure we have a docid and datafile
2859
        if (docid != null && fileList.containsKey("datafile")) {
2860 2753 jones
            logMetacat.info("Uploading data docid: " + docid);
2861 2098 jones
            // Get a reference to the file part of the form
2862
            FilePart filePart = (FilePart) fileList.get("datafile");
2863
            String fileName = filePart.getFileName();
2864 2753 jones
            logMetacat.info("Uploading filename: " + fileName);
2865 2098 jones
            // Check if the right file existed in the uploaded data
2866
            if (fileName != null) {
2867 1360 tao
2868 2098 jones
                try {
2869 2663 sgarg
                    //logMetacat.info("Upload datafile " + docid
2870 2098 jones
                    // +"...", 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 2752 jones
                        String datafilepath = MetaCatUtil.getOption("datafilepath");
2875
                        File dataDirectory = new File(datafilepath);
2876 2098 jones
                        dataDirectory.mkdirs();
2877 2749 tao
                        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 1360 tao
2898 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
2899 2102 jones
                                username, docid, "upload");
2900 2098 jones
                        // 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 1360 tao
2910 2098 jones
                        // 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 2749 tao
2921 2098 jones
                    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 798 jones
        }
2941 2098 jones
    }
2942 1360 tao
2943 2098 jones
    /*
2944
     * A method to handle set access action
2945
     */
2946
    private void handleSetAccessAction(PrintWriter out, Hashtable params,
2947
            String username)
2948 1041 tao
    {
2949 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2950 2098 jones
        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 1716 berkley
2963 2098 jones
        // 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 1716 berkley
2973 2098 jones
        }
2974
        if (params.containsKey("permType")) {
2975
            permTypeList = (String[]) params.get("permType");
2976 1716 berkley
2977 2098 jones
        }
2978
        if (params.containsKey("permOrder")) {
2979
            permOrderList = (String[]) params.get("permOrder");
2980 1716 berkley
2981 2098 jones
        }
2982 1716 berkley
2983 2098 jones
        // 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 1716 berkley
2994 2098 jones
        // 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 1716 berkley
3001 2098 jones
        // 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 2753 jones
                logMetacat.debug("doctype in package set: "
3008 2663 sgarg
                        + (String) packageSet.elementAt(i));
3009 2098 jones
            }
3010
        }
3011 1716 berkley
3012 2098 jones
        // 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 2663 sgarg
                logMetacat.error("Error in handleSetAccessAction: "
3023
                        + e.getMessage());
3024 2098 jones
                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 1716 berkley
3038 2098 jones
            // 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 1716 berkley
3052 2098 jones
            // 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 2663 sgarg
                    logMetacat.error(
3066 2098 jones
                            "Erorr in handleSetAccessAction2: "
3067 2663 sgarg
                                    + ee.getMessage());
3068 2098 jones
                    error = "Faild to set access control for document "
3069
                            + accessionNumber + " because " + ee.getMessage();
3070
                    errorList.addElement(error);
3071
                    continue;
3072
                }
3073
            }
3074 1369 tao
        }
3075 2098 jones
        outputResponse(successList, errorList, out);
3076
    }
3077 1716 berkley
3078 2098 jones
    /*
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 1369 tao
    {
3085 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3086 2098 jones
        if (accessionNumber == null || accessionNumber.equals("")
3087
                || fieldName == null || fieldName.equals("")) { throw new Exception(
3088
                "Docid or field name was not specified"); }
3089 1716 berkley
3090 2098 jones
        PreparedStatement pstmt = null;
3091
        ResultSet rs = null;
3092
        String fieldValue = null;
3093
        String docId = null;
3094
        DBConnection conn = null;
3095
        int serialNumber = -1;
3096 1716 berkley
3097 2098 jones
        // 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 1716 berkley
3107 2098 jones
            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 2663 sgarg
            logMetacat.error(
3120 2098 jones
                    "Exception in MetacatServlet.getPublicIdForDoc: "
3121 2663 sgarg
                            + e.getMessage());
3122 2098 jones
            throw e;
3123
        } finally {
3124
            try {
3125
                rs.close();
3126
                pstmt.close();
3127 1716 berkley
3128 2098 jones
            } finally {
3129
                DBConnectionPool.returnDBConnection(conn, serialNumber);
3130
            }
3131
        }
3132
        return fieldValue;
3133 1369 tao
    }
3134 1716 berkley
3135 2098 jones
    /*
3136 2312 jones
     * 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 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3144 2312 jones
        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 2663 sgarg
            logMetacat.error(
3166 2312 jones
                    "Exception in MetacatServlet.getDocumentList: "
3167 2663 sgarg
                            + e.getMessage());
3168 2312 jones
            throw e;
3169
        } finally {
3170
            try {
3171
                rs.close();
3172
                pstmt.close();
3173
3174
            } catch (SQLException se) {
3175 2663 sgarg
                logMetacat.error(
3176 2312 jones
                    "Exception in MetacatServlet.getDocumentList: "
3177 2663 sgarg
                            + se.getMessage());
3178 2312 jones
                throw se;
3179
            } finally {
3180
                DBConnectionPool.returnDBConnection(conn, serialNumber);
3181
            }
3182
        }
3183
        return docList;
3184
    }
3185
3186
    /*
3187 2098 jones
     * A method to output setAccess action result
3188
     */
3189
    private void outputResponse(Vector successList, Vector errorList,
3190
            PrintWriter out)
3191 1369 tao
    {
3192 2098 jones
        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 1716 berkley
3215 2098 jones
        // 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 1369 tao
    }
3222 2582 tao
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 2648 tao
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 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3239 2648 tao
        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 2776 tao
                throw new Exception("the requested docid '"
3251
                        + docid+ "' does not exist");
3252 2648 tao
            }
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 2776 tao
        //logMetacat.debug("The docid will be read is "+newAccNum);
3264 2648 tao
        return newAccNum;
3265 2912 harris
  }
3266 46 jones
}