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 361 berkley
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley
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
811
812 2938 harris
      // issue the Spatial query
813 2970 sgarg
      //MBJ DELETED MetacatSpatialDataset _data =
814
        //MBJ DELETED _spatialQuery.queryDatasetByCartesianBounds(_xmin, _ymin, _xmax, _ymax);
815 2912 harris
816 2938 harris
      // report the number of documents returned:
817 2970 sgarg
      //MBJ DELETED logMetacat.warn("\nThe number of documents in the BBOX query: "
818
              //MBJ DELETED + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
819
820
/* MBJ DELETED -- using Metacat query instead
821
if (  _data.size() > 0) {
822 2938 harris
      logMetacat.warn("\nThe number of documents in the BBOX query: "
823
              + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
824 2946 sgarg
825 2938 harris
826 2919 harris
      // create an s-query
827
      String[] queryArray = new String[1];
828
      queryArray[0] = DocumentIdQuery.createDocidQuery(_data.getDocidList());
829
      params.put("query", queryArray);
830 2938 harris
831
      // qformat
832 2919 harris
      String[] qformatArray = new String[1];
833
      qformatArray[0] = "knp";
834
      params.put("qformat", qformatArray);
835
836
      // change the action
837
      String[] actionArray = new String[1];
838
      actionArray[0] = "squery";
839
      params.put("action", actionArray);
840
841 2912 harris
      // return the list of docs and point at the spatial theme
842
      if ( printXML) {
843
        response.setContentType("text/xml");
844 2915 harris
        out.println(_data.toXML() ); // write the data as xml
845 2912 harris
        out.close();
846
      } else {
847 2919 harris
        logMetacat.warn("username: " + username+"\nsession: "+sess_id);
848
        handleSQuery(out, params, response, username, groupnames, sess_id);
849 2912 harris
      }
850 2946 sgarg
} else {
851
        response.setContentType("text/html");
852
        out.println("<html>No Datasets Selected <html>");
853
        out.close();
854
}
855 2970 sgarg
*/
856
      	// create an s-query
857
        String spatialQuery = createSpatialQuery(_xmax, _ymax, _xmin, _ymin);
858
      	String[] queryArray = new String[1];
859
      	queryArray[0] = spatialQuery;
860
      	params.put("query", queryArray);
861
862
      	// qformat
863
      	String[] qformatArray = new String[1];
864
      	qformatArray[0] = "knp";
865
      	params.put("qformat", qformatArray);
866
867
      	// change the action
868
      	String[] actionArray = new String[1];
869
      	actionArray[0] = "squery";
870
      	params.put("action", actionArray);
871 2946 sgarg
872 2970 sgarg
        handleSQuery(out, params, response, username, groupnames, sess_id);
873 2912 harris
    }
874
875 2970 sgarg
    /**
876
     * Create a metacat squery for spatial data coordinates.
877
     */
878
    private String createSpatialQuery(float _xmin, float _ymin, float _xmax, float _ymax) {
879
	StringBuffer sb = new StringBuffer();
880
881
	sb.append("<pathquery version=\"1.2\">");
882
	sb.append("<querytitle>Untitled-Search-3</querytitle>");
883
	sb.append("<returndoctype>-//ecoinformatics.org//eml-dataset-2.0.0beta4//EN</returndoctype>");
884
	sb.append("<returndoctype>-//ecoinformatics.org//eml-dataset-2.0.0beta6//EN</returndoctype>");
885
	sb.append("<returndoctype>-//NCEAS//eml-dataset-2.0//EN</returndoctype>");
886
	sb.append("<returndoctype>-//NCEAS//resource//EN</returndoctype>");
887
	sb.append("<returndoctype>eml://ecoinformatics.org/eml-2.0.0</returndoctype>");
888
	sb.append("<returndoctype>eml://ecoinformatics.org/eml-2.0.1</returndoctype>");
889
	sb.append("<returndoctype>metadata</returndoctype>");
890
	sb.append("<returnfield>dataset/title</returnfield>");
891
	sb.append("<returnfield>originator/individualName/surName</returnfield>");
892
	sb.append("<returnfield>originator/individualName/givenName</returnfield>");
893
	sb.append("<returnfield>originator/organizationName</returnfield>");
894
	sb.append("<returnfield>creator/individualName/surName</returnfield>");
895
	sb.append("<returnfield>creator/individualName/givenName</returnfield>");
896
	sb.append("<returnfield>creator/organizationName</returnfield>");
897
	sb.append("<returnfield>keyword</returnfield>");
898
	sb.append("<returnfield>entityName</returnfield>");
899
	sb.append("<returnfield>idinfo/citation/citeinfo/title</returnfield>");
900
	sb.append("<returnfield>idinfo/citation/citeinfo/origin</returnfield>");
901
	sb.append("<returnfield>idinfo/keywords/theme/themekey</returnfield>");
902
	sb.append("<querygroup operator=\"INTERSECT\">");
903
	sb.append("<queryterm searchmode=\"less-than\" casesensitive=\"false\">");
904
	sb.append("<value>" + _ymin + "</value>");
905
	sb.append("<pathexpr>northBoundingCoordinate</pathexpr>");
906
	sb.append("</queryterm>");
907
	sb.append("<queryterm searchmode=\"greater-than\" casesensitive=\"false\">");
908
	sb.append("<value>" + _ymax + "</value>");
909
	sb.append("<pathexpr>northBoundingCoordinate</pathexpr>");
910
	sb.append("</queryterm>");
911
	sb.append("<queryterm searchmode=\"less-than\" casesensitive=\"false\">");
912
	sb.append("<value>" + _xmin + "</value>");
913
	sb.append("<pathexpr>westBoundingCoordinate</pathexpr>");
914
	sb.append("</queryterm>");
915
	sb.append("<queryterm searchmode=\"greater-than\" casesensitive=\"false\">");
916
	sb.append("<value>" + _xmax + "</value>");
917
	sb.append("<pathexpr>westBoundingCoordinate</pathexpr>");
918
	sb.append("</queryterm>");
919
	sb.append("</querygroup>");
920
	sb.append("</pathquery>");
921 2912 harris
922 2970 sgarg
	return sb.toString();
923
    }
924
925 2098 jones
    // LOGIN & LOGOUT SECTION
926
    /**
927
     * Handle the login request. Create a new session object. Do user
928
     * authentication through the session.
929
     */
930
    private void handleLoginAction(PrintWriter out, Hashtable params,
931
            HttpServletRequest request, HttpServletResponse response)
932 943 tao
    {
933 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
934 2098 jones
        AuthSession sess = null;
935 2252 sgarg
936
        if(params.get("username") == null){
937
            response.setContentType("text/xml");
938
            out.println("<?xml version=\"1.0\"?>");
939
            out.println("<error>");
940
            out.println("Username not specified");
941
            out.println("</error>");
942
            return;
943
        }
944
945 2912 harris
        //}
946
947 2252 sgarg
        if(params.get("password") == null){
948
            response.setContentType("text/xml");
949
            out.println("<?xml version=\"1.0\"?>");
950
            out.println("<error>");
951
            out.println("Password not specified");
952
            out.println("</error>");
953
            return;
954
        }
955
956 2098 jones
        String un = ((String[]) params.get("username"))[0];
957 2753 jones
        logMetacat.info("user " + un + " is trying to login");
958 2098 jones
        String pw = ((String[]) params.get("password"))[0];
959 943 tao
960 2252 sgarg
        String qformat = "xml";
961
        if(params.get("qformat") != null){
962
            qformat = ((String[]) params.get("qformat"))[0];
963
        }
964
965 2098 jones
        try {
966
            sess = new AuthSession();
967
        } catch (Exception e) {
968
            System.out.println("error in MetacatServlet.handleLoginAction: "
969
                    + e.getMessage());
970
            out.println(e.getMessage());
971
            return;
972
        }
973
        boolean isValid = sess.authenticate(request, un, pw);
974 1360 tao
975 2098 jones
        //if it is authernticate is true, store the session
976
        if (isValid) {
977
            HttpSession session = sess.getSessions();
978
            String id = session.getId();
979 2663 sgarg
            logMetacat.info("Store session id " + id
980 2098 jones
                    + "which has username" + session.getAttribute("username")
981 2663 sgarg
                    + " into hash in login method");
982 2098 jones
            sessionHash.put(id, session);
983
        }
984 1360 tao
985 2098 jones
        // format and transform the output
986
        if (qformat.equals("xml")) {
987
            response.setContentType("text/xml");
988
            out.println(sess.getMessage());
989
        } else {
990
            try {
991
                DBTransform trans = new DBTransform();
992
                response.setContentType("text/html");
993
                trans.transformXMLDocument(sess.getMessage(),
994
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
995
                        out, null);
996
            } catch (Exception e) {
997 1360 tao
998 2663 sgarg
                logMetacat.error(
999 2098 jones
                        "Error in MetaCatServlet.handleLoginAction: "
1000 2663 sgarg
                                + e.getMessage());
1001 2098 jones
            }
1002
        }
1003
    }
1004 1716 berkley
1005 2098 jones
    /**
1006
     * Handle the logout request. Close the connection.
1007
     */
1008
    private void handleLogoutAction(PrintWriter out, Hashtable params,
1009
            HttpServletRequest request, HttpServletResponse response)
1010 1483 tao
    {
1011 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1012 2252 sgarg
        String qformat = "xml";
1013
        if(params.get("qformat") != null){
1014
            qformat = ((String[]) params.get("qformat"))[0];
1015
        }
1016 1716 berkley
1017 2098 jones
        // close the connection
1018
        HttpSession sess = request.getSession(false);
1019 2663 sgarg
        logMetacat.info("After get session in logout request");
1020 2098 jones
        if (sess != null) {
1021 2663 sgarg
            logMetacat.info("The session id " + sess.getId()
1022
                    + " will be invalidate in logout action");
1023 2753 jones
            logMetacat.info("The session contains user "
1024 2098 jones
                    + sess.getAttribute("username")
1025 2663 sgarg
                    + " will be invalidate in logout action");
1026 2098 jones
            sess.invalidate();
1027
        }
1028 1716 berkley
1029 2098 jones
        // produce output
1030
        StringBuffer output = new StringBuffer();
1031
        output.append("<?xml version=\"1.0\"?>");
1032
        output.append("<logout>");
1033
        output.append("User logged out");
1034
        output.append("</logout>");
1035 1483 tao
1036 2098 jones
        //format and transform the output
1037
        if (qformat.equals("xml")) {
1038
            response.setContentType("text/xml");
1039
            out.println(output.toString());
1040
        } else {
1041
            try {
1042
                DBTransform trans = new DBTransform();
1043
                response.setContentType("text/html");
1044
                trans.transformXMLDocument(output.toString(),
1045
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1046
                        out, null);
1047
            } catch (Exception e) {
1048 2663 sgarg
                logMetacat.error(
1049 2098 jones
                        "Error in MetaCatServlet.handleLogoutAction"
1050 2663 sgarg
                                + e.getMessage());
1051 2098 jones
            }
1052 1716 berkley
        }
1053 2098 jones
    }
1054 1483 tao
1055 2098 jones
    // END OF LOGIN & LOGOUT SECTION
1056 1716 berkley
1057 2098 jones
    // SQUERY & QUERY SECTION
1058
    /**
1059
     * Retreive the squery xml, execute it and display it
1060 2169 sgarg
     *
1061 2098 jones
     * @param out the output stream to the client
1062
     * @param params the Hashtable of parameters that should be included in the
1063
     *            squery.
1064
     * @param response the response object linked to the client
1065
     * @param conn the database connection
1066
     */
1067 2570 jones
    private void handleSQuery(PrintWriter out, Hashtable params,
1068 2098 jones
            HttpServletResponse response, String user, String[] groups,
1069
            String sessionid)
1070
    {
1071
        double startTime = System.currentTimeMillis() / 1000;
1072 2752 jones
        DBQuery queryobj = new DBQuery();
1073 2098 jones
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1074
        double outPutTime = System.currentTimeMillis() / 1000;
1075 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1076
        logMetacat.info("Total search time for action 'squery': "
1077 2663 sgarg
                + (outPutTime - startTime));
1078 2098 jones
    }
1079 1716 berkley
1080 2098 jones
    /**
1081
     * Create the xml query, execute it and display the results.
1082 2169 sgarg
     *
1083 2098 jones
     * @param out the output stream to the client
1084
     * @param params the Hashtable of parameters that should be included in the
1085
     *            squery.
1086
     * @param response the response object linked to the client
1087
     */
1088 2570 jones
    private void handleQuery(PrintWriter out, Hashtable params,
1089 2098 jones
            HttpServletResponse response, String user, String[] groups,
1090
            String sessionid)
1091 1490 tao
    {
1092 2098 jones
        //create the query and run it
1093
        String xmlquery = DBQuery.createSQuery(params);
1094
        String[] queryArray = new String[1];
1095
        queryArray[0] = xmlquery;
1096
        params.put("query", queryArray);
1097
        double startTime = System.currentTimeMillis() / 1000;
1098 2752 jones
        DBQuery queryobj = new DBQuery();
1099 2098 jones
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1100
        double outPutTime = System.currentTimeMillis() / 1000;
1101 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1102
        logMetacat.info("Total search time for action 'query': "
1103 2663 sgarg
                + (outPutTime - startTime));
1104 1716 berkley
1105 2098 jones
        //handleSQuery(out, params, response,user, groups, sessionid);
1106 1490 tao
    }
1107 1716 berkley
1108 2098 jones
    // END OF SQUERY & QUERY SECTION
1109 1716 berkley
1110 2098 jones
    //Exoport section
1111
    /**
1112
     * Handle the "export" request of data package from Metacat in zip format
1113 2169 sgarg
     *
1114 2098 jones
     * @param params the Hashtable of HTTP request parameters
1115
     * @param response the HTTP response object linked to the client
1116
     * @param user the username sent the request
1117
     * @param groups the user's groupnames
1118
     */
1119 2169 sgarg
    private void handleExportAction(Hashtable params,
1120
            HttpServletResponse response,
1121 2102 jones
            String user, String[] groups, String passWord)
1122 2098 jones
    {
1123 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1124 2098 jones
        // Output stream
1125
        ServletOutputStream out = null;
1126
        // Zip output stream
1127
        ZipOutputStream zOut = null;
1128
        DBQuery queryObj = null;
1129 1716 berkley
1130 2098 jones
        String[] docs = new String[10];
1131
        String docId = "";
1132 1360 tao
1133 731 bojilova
        try {
1134 2098 jones
            // read the params
1135
            if (params.containsKey("docid")) {
1136
                docs = (String[]) params.get("docid");
1137 731 bojilova
            }
1138 2098 jones
            // Create a DBuery to handle export
1139 2752 jones
            queryObj = new DBQuery();
1140 2098 jones
            // Get the docid
1141
            docId = docs[0];
1142
            // Make sure the client specify docid
1143
            if (docId == null || docId.equals("")) {
1144
                response.setContentType("text/xml"); //MIME type
1145
                // Get a printwriter
1146
                PrintWriter pw = response.getWriter();
1147
                // Send back message
1148
                pw.println("<?xml version=\"1.0\"?>");
1149
                pw.println("<error>");
1150
                pw.println("You didn't specify requested docid");
1151
                pw.println("</error>");
1152
                // Close printwriter
1153
                pw.close();
1154
                return;
1155
            }
1156
            // Get output stream
1157
            out = response.getOutputStream();
1158
            response.setContentType("application/zip"); //MIME type
1159 2556 sgarg
            response.setHeader("Content-Disposition",
1160
            		"attachment; filename="
1161
            		+ docId + ".zip"); // Set the name of the zip file
1162
1163 2098 jones
            zOut = new ZipOutputStream(out);
1164
            zOut = queryObj
1165
                    .getZippedPackage(docId, out, user, groups, passWord);
1166
            zOut.finish(); //terminate the zip file
1167
            zOut.close(); //close the zip stream
1168 731 bojilova
1169 2098 jones
        } catch (Exception e) {
1170
            try {
1171
                response.setContentType("text/xml"); //MIME type
1172
                // Send error message back
1173
                if (out != null) {
1174
                    PrintWriter pw = new PrintWriter(out);
1175
                    pw.println("<?xml version=\"1.0\"?>");
1176
                    pw.println("<error>");
1177
                    pw.println(e.getMessage());
1178
                    pw.println("</error>");
1179
                    // Close printwriter
1180
                    pw.close();
1181
                    // Close output stream
1182
                    out.close();
1183
                }
1184
                // Close zip output stream
1185
                if (zOut != null) {
1186
                    zOut.close();
1187
                }
1188
            } catch (IOException ioe) {
1189 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1190 2098 jones
                        + "in MetacatServlet.handleExportAction: "
1191 2663 sgarg
                        + ioe.getMessage());
1192 731 bojilova
            }
1193
1194 2663 sgarg
            logMetacat.error(
1195 2098 jones
                    "Error in MetacatServlet.handleExportAction: "
1196 2663 sgarg
                            + e.getMessage());
1197 2098 jones
            e.printStackTrace(System.out);
1198
1199 731 bojilova
        }
1200 1360 tao
1201 2098 jones
    }
1202 1360 tao
1203 2098 jones
    /**
1204
     * In eml2 document, the xml can have inline data and data was stripped off
1205
     * and store in file system. This action can be used to read inline data
1206
     * only
1207 2169 sgarg
     *
1208 2098 jones
     * @param params the Hashtable of HTTP request parameters
1209
     * @param response the HTTP response object linked to the client
1210
     * @param user the username sent the request
1211
     * @param groups the user's groupnames
1212
     */
1213
    private void handleReadInlineDataAction(Hashtable params,
1214 2169 sgarg
            HttpServletRequest request, HttpServletResponse response,
1215 2102 jones
            String user, String passWord, String[] groups)
1216 2098 jones
    {
1217 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1218 2098 jones
        String[] docs = new String[10];
1219
        String inlineDataId = null;
1220
        String docId = "";
1221
        ServletOutputStream out = null;
1222 1360 tao
1223 2098 jones
        try {
1224
            // read the params
1225
            if (params.containsKey("inlinedataid")) {
1226
                docs = (String[]) params.get("inlinedataid");
1227
            }
1228
            // Get the docid
1229
            inlineDataId = docs[0];
1230
            // Make sure the client specify docid
1231 2169 sgarg
            if (inlineDataId == null || inlineDataId.equals("")) {
1232 2098 jones
                throw new Exception("You didn't specify requested inlinedataid"); }
1233 1360 tao
1234 2098 jones
            // check for permission
1235
            docId = MetaCatUtil
1236
                    .getDocIdWithoutRevFromInlineDataID(inlineDataId);
1237
            PermissionController controller = new PermissionController(docId);
1238
            // check top level read permission
1239
            if (!controller.hasPermission(user, groups,
1240 2245 sgarg
                    AccessControlInterface.READSTRING))
1241
            {
1242 2098 jones
                throw new Exception("User " + user
1243
                        + " doesn't have permission " + " to read document "
1244
                        + docId);
1245
            }
1246 2245 sgarg
            else
1247
            {
1248
              //check data access level
1249
              try
1250
              {
1251
                Hashtable unReadableInlineDataList =
1252 2292 sgarg
                    PermissionController.getUnReadableInlineDataIdList(docId,
1253
                    user, groups, false);
1254
                if (unReadableInlineDataList.containsValue(
1255
                          MetaCatUtil.getInlineDataIdWithoutRev(inlineDataId)))
1256 2245 sgarg
                {
1257
                  throw new Exception("User " + user
1258
                       + " doesn't have permission " + " to read inlinedata "
1259
                       + inlineDataId);
1260 2098 jones
1261 2245 sgarg
                }//if
1262
              }//try
1263
              catch (Exception e)
1264
              {
1265
                throw e;
1266
              }//catch
1267
            }//else
1268
1269 2098 jones
            // Get output stream
1270
            out = response.getOutputStream();
1271
            // read the inline data from the file
1272
            String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
1273
            File lineData = new File(inlinePath, inlineDataId);
1274
            FileInputStream input = new FileInputStream(lineData);
1275
            byte[] buffer = new byte[4 * 1024];
1276
            int bytes = input.read(buffer);
1277
            while (bytes != -1) {
1278
                out.write(buffer, 0, bytes);
1279
                bytes = input.read(buffer);
1280
            }
1281 1292 tao
            out.close();
1282 1360 tao
1283 2169 sgarg
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1284 2102 jones
                    inlineDataId, "readinlinedata");
1285 2098 jones
        } catch (Exception e) {
1286
            try {
1287
                PrintWriter pw = null;
1288
                // Send error message back
1289
                if (out != null) {
1290
                    pw = new PrintWriter(out);
1291
                } else {
1292
                    pw = response.getWriter();
1293
                }
1294
                pw.println("<?xml version=\"1.0\"?>");
1295
                pw.println("<error>");
1296
                pw.println(e.getMessage());
1297
                pw.println("</error>");
1298
                // Close printwriter
1299
                pw.close();
1300
                // Close output stream if out is not null
1301
                if (out != null) {
1302
                    out.close();
1303
                }
1304
            } catch (IOException ioe) {
1305 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1306 2098 jones
                        + "in MetacatServlet.handleExportAction: "
1307 2663 sgarg
                        + ioe.getMessage());
1308 2098 jones
            }
1309 2663 sgarg
            logMetacat.error(
1310 2098 jones
                    "Error in MetacatServlet.handleReadInlineDataAction: "
1311 2663 sgarg
                            + e.getMessage());
1312 1292 tao
        }
1313 2098 jones
    }
1314
1315
    /*
1316
     * Get the nodeid from xml_nodes for the inlinedataid
1317
     */
1318
    private long getInlineDataNodeId(String inLineDataId, String docId)
1319
            throws SQLException
1320 1292 tao
    {
1321 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1322 2098 jones
        long nodeId = 0;
1323
        String INLINE = "inline";
1324
        boolean hasRow;
1325
        PreparedStatement pStmt = null;
1326
        DBConnection conn = null;
1327
        int serialNumber = -1;
1328
        String sql = "SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? "
1329
                + "AND nodetype='TEXT' AND parentnodeid IN "
1330
                + "(SELECT nodeid FROM xml_nodes WHERE docid=? AND "
1331
                + "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
1332 1360 tao
1333 2098 jones
        try {
1334
            //check out DBConnection
1335
            conn = DBConnectionPool
1336
                    .getDBConnection("AccessControlList.isAllowFirst");
1337
            serialNumber = conn.getCheckOutSerialNumber();
1338 1360 tao
1339 2098 jones
            pStmt = conn.prepareStatement(sql);
1340
            //bind value
1341
            pStmt.setString(1, docId);//docid
1342
            pStmt.setString(2, inLineDataId);//inlinedataid
1343
            pStmt.setString(3, docId);
1344
            // excute query
1345
            pStmt.execute();
1346
            ResultSet rs = pStmt.getResultSet();
1347
            hasRow = rs.next();
1348
            // get result
1349
            if (hasRow) {
1350
                nodeId = rs.getLong(1);
1351
            }//if
1352
1353
        } catch (SQLException e) {
1354
            throw e;
1355
        } finally {
1356
            try {
1357
                pStmt.close();
1358
            } finally {
1359
                DBConnectionPool.returnDBConnection(conn, serialNumber);
1360
            }
1361 1292 tao
        }
1362 2753 jones
        logMetacat.debug("The nodeid for inlinedataid " + inLineDataId
1363 2663 sgarg
                + " is: " + nodeId);
1364 2098 jones
        return nodeId;
1365
    }
1366 1360 tao
1367 2098 jones
    /**
1368
     * Handle the "read" request of metadata/data files from Metacat or any
1369
     * files from Internet; transformed metadata XML document into HTML
1370
     * presentation if requested; zip files when more than one were requested.
1371 2169 sgarg
     *
1372 2098 jones
     * @param params the Hashtable of HTTP request parameters
1373 2102 jones
     * @param request the HTTP request object linked to the client
1374 2098 jones
     * @param response the HTTP response object linked to the client
1375
     * @param user the username sent the request
1376
     * @param groups the user's groupnames
1377
     */
1378 2102 jones
    private void handleReadAction(Hashtable params, HttpServletRequest request,
1379 2098 jones
            HttpServletResponse response, String user, String passWord,
1380
            String[] groups)
1381
    {
1382 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1383 2098 jones
        ServletOutputStream out = null;
1384
        ZipOutputStream zout = null;
1385
        PrintWriter pw = null;
1386
        boolean zip = false;
1387
        boolean withInlineData = true;
1388 1360 tao
1389 2098 jones
        try {
1390
            String[] docs = new String[0];
1391
            String docid = "";
1392
            String qformat = "";
1393
            String abstrpath = null;
1394 731 bojilova
1395 2098 jones
            // read the params
1396
            if (params.containsKey("docid")) {
1397
                docs = (String[]) params.get("docid");
1398
            }
1399
            if (params.containsKey("qformat")) {
1400
                qformat = ((String[]) params.get("qformat"))[0];
1401
            }
1402
            // the param for only metadata (eml)
1403 2245 sgarg
            // we don't support read a eml document without inline data now.
1404
            /*if (params.containsKey("inlinedata")) {
1405 1360 tao
1406 2098 jones
                String inlineData = ((String[]) params.get("inlinedata"))[0];
1407
                if (inlineData.equalsIgnoreCase("false")) {
1408
                    withInlineData = false;
1409
                }
1410 2245 sgarg
            }*/
1411 2098 jones
            if ((docs.length > 1) || qformat.equals("zip")) {
1412
                zip = true;
1413
                out = response.getOutputStream();
1414
                response.setContentType("application/zip"); //MIME type
1415
                zout = new ZipOutputStream(out);
1416
            }
1417
            // go through the list of docs to read
1418
            for (int i = 0; i < docs.length; i++) {
1419
                try {
1420 1360 tao
1421 2098 jones
                    URL murl = new URL(docs[i]);
1422 2099 jones
                    Hashtable murlQueryStr = MetaCatUtil.parseQuery(
1423
                            murl.getQuery());
1424 2098 jones
                    // case docid="http://.../?docid=aaa"
1425
                    // or docid="metacat://.../?docid=bbb"
1426
                    if (murlQueryStr.containsKey("docid")) {
1427
                        // get only docid, eliminate the rest
1428
                        docid = (String) murlQueryStr.get("docid");
1429
                        if (zip) {
1430 2102 jones
                            addDocToZip(request, docid, zout, user, groups);
1431 2098 jones
                        } else {
1432 2102 jones
                            readFromMetacat(request, response, docid, qformat,
1433 2098 jones
                                    abstrpath, user, groups, zip, zout,
1434
                                    withInlineData, params);
1435
                        }
1436 1360 tao
1437 2098 jones
                        // case docid="http://.../filename"
1438
                    } else {
1439
                        docid = docs[i];
1440
                        if (zip) {
1441 2102 jones
                            addDocToZip(request, docid, zout, user, groups);
1442 2098 jones
                        } else {
1443
                            readFromURLConnection(response, docid);
1444
                        }
1445
                    }
1446 2169 sgarg
1447 2098 jones
                } catch (MalformedURLException mue) {
1448
                    docid = docs[i];
1449
                    if (zip) {
1450 2102 jones
                        addDocToZip(request, docid, zout, user, groups);
1451 2098 jones
                    } else {
1452 2169 sgarg
                        readFromMetacat(request, response, docid, qformat,
1453
                                abstrpath, user, groups, zip, zout,
1454 2102 jones
                                withInlineData, params);
1455 2098 jones
                    }
1456
                }
1457 2099 jones
            }
1458 1360 tao
1459 2098 jones
            if (zip) {
1460
                zout.finish(); //terminate the zip file
1461
                zout.close(); //close the zip stream
1462
            }
1463 1360 tao
1464 2098 jones
        } catch (McdbDocNotFoundException notFoundE) {
1465
            // To handle doc not found exception
1466
            // the docid which didn't be found
1467
            String notFoundDocId = notFoundE.getUnfoundDocId();
1468
            String notFoundRevision = notFoundE.getUnfoundRevision();
1469 2663 sgarg
            logMetacat.warn("Missed id: " + notFoundDocId);
1470
            logMetacat.warn("Missed rev: " + notFoundRevision);
1471 2098 jones
            try {
1472
                // read docid from remote server
1473
                readFromRemoteMetaCat(response, notFoundDocId,
1474
                        notFoundRevision, user, passWord, out, zip, zout);
1475
                // Close zout outputstream
1476
                if (zout != null) {
1477
                    zout.close();
1478
                }
1479
                // close output stream
1480
                if (out != null) {
1481
                    out.close();
1482
                }
1483 1360 tao
1484 2098 jones
            } catch (Exception exc) {
1485 2663 sgarg
                logMetacat.error(
1486 2098 jones
                        "Erorr in MetacatServlet.hanldReadAction: "
1487 2663 sgarg
                                + exc.getMessage());
1488 2098 jones
                try {
1489
                    if (out != null) {
1490
                        response.setContentType("text/xml");
1491
                        // Send back error message by printWriter
1492
                        pw = new PrintWriter(out);
1493
                        pw.println("<?xml version=\"1.0\"?>");
1494
                        pw.println("<error>");
1495
                        pw.println(notFoundE.getMessage());
1496
                        pw.println("</error>");
1497
                        pw.close();
1498
                        out.close();
1499 1360 tao
1500 2098 jones
                    } else {
1501
                        response.setContentType("text/xml"); //MIME type
1502
                        // Send back error message if out = null
1503
                        if (pw == null) {
1504
                            // If pw is null, open the respnose
1505
                            pw = response.getWriter();
1506
                        }
1507
                        pw.println("<?xml version=\"1.0\"?>");
1508
                        pw.println("<error>");
1509
                        pw.println(notFoundE.getMessage());
1510
                        pw.println("</error>");
1511
                        pw.close();
1512
                    }
1513
                    // close zout
1514
                    if (zout != null) {
1515
                        zout.close();
1516
                    }
1517
                } catch (IOException ie) {
1518 2663 sgarg
                    logMetacat.error("Problem with the servlet output "
1519 2098 jones
                            + "in MetacatServlet.handleReadAction: "
1520 2663 sgarg
                            + ie.getMessage());
1521 2098 jones
                }
1522
            }
1523
        } catch (Exception e) {
1524
            try {
1525 1716 berkley
1526 2098 jones
                if (out != null) {
1527
                    response.setContentType("text/xml"); //MIME type
1528
                    pw = new PrintWriter(out);
1529
                    pw.println("<?xml version=\"1.0\"?>");
1530
                    pw.println("<error>");
1531
                    pw.println(e.getMessage());
1532
                    pw.println("</error>");
1533
                    pw.close();
1534
                    out.close();
1535
                } else {
1536
                    response.setContentType("text/xml"); //MIME type
1537
                    // Send back error message if out = null
1538
                    if (pw == null) {
1539
                        pw = response.getWriter();
1540
                    }
1541
                    pw.println("<?xml version=\"1.0\"?>");
1542
                    pw.println("<error>");
1543
                    pw.println(e.getMessage());
1544
                    pw.println("</error>");
1545
                    pw.close();
1546 1360 tao
1547 2098 jones
                }
1548
                // Close zip output stream
1549
                if (zout != null) {
1550
                    zout.close();
1551
                }
1552 1360 tao
1553 2098 jones
            } catch (IOException ioe) {
1554 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1555 2098 jones
                        + "in MetacatServlet.handleReadAction: "
1556 2663 sgarg
                        + ioe.getMessage());
1557 2098 jones
                ioe.printStackTrace(System.out);
1558 731 bojilova
1559 2098 jones
            }
1560 1360 tao
1561 2663 sgarg
            logMetacat.error(
1562 2098 jones
                    "Error in MetacatServlet.handleReadAction: "
1563 2663 sgarg
                            + e.getMessage());
1564 2098 jones
            //e.printStackTrace(System.out);
1565 731 bojilova
        }
1566 2098 jones
    }
1567 1360 tao
1568 2169 sgarg
    /** read metadata or data from Metacat
1569 2098 jones
     */
1570 2169 sgarg
    private void readFromMetacat(HttpServletRequest request,
1571 2102 jones
            HttpServletResponse response, String docid, String qformat,
1572
            String abstrpath, String user, String[] groups, boolean zip,
1573
            ZipOutputStream zout, boolean withInlineData, Hashtable params)
1574
            throws ClassNotFoundException, IOException, SQLException,
1575
            McdbException, Exception
1576 1292 tao
    {
1577 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1578 2098 jones
        try {
1579 2648 tao
1580
            // here is hack for handle docid=john.10(in order to tell mike.jim.10.1
1581
            // mike.jim.10, we require to provide entire docid with rev). But
1582
            // some old client they only provide docid without rev, so we need
1583
            // to handle this suituation. First we will check how many
1584
            // seperator here, if only one, we will append the rev in xml_documents
1585
            // to the id.
1586
            docid = appendRev(docid);
1587
1588 2098 jones
            DocumentImpl doc = new DocumentImpl(docid);
1589 1360 tao
1590 2098 jones
            //check the permission for read
1591 2113 jones
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1592 2098 jones
                Exception e = new Exception("User " + user
1593
                        + " does not have permission"
1594
                        + " to read the document with the docid " + docid);
1595 731 bojilova
1596 2098 jones
                throw e;
1597
            }
1598 1360 tao
1599 2098 jones
            if (doc.getRootNodeID() == 0) {
1600
                // this is data file
1601
                String filepath = MetaCatUtil.getOption("datafilepath");
1602
                if (!filepath.endsWith("/")) {
1603
                    filepath += "/";
1604
                }
1605
                String filename = filepath + docid;
1606
                FileInputStream fin = null;
1607
                fin = new FileInputStream(filename);
1608 1360 tao
1609 2098 jones
                //MIME type
1610
                String contentType = getServletContext().getMimeType(filename);
1611
                if (contentType == null) {
1612
                    ContentTypeProvider provider = new ContentTypeProvider(
1613
                            docid);
1614
                    contentType = provider.getContentType();
1615 2753 jones
                    logMetacat.info("Final contenttype is: "
1616 2663 sgarg
                            + contentType);
1617 2098 jones
                }
1618 731 bojilova
1619 2098 jones
                response.setContentType(contentType);
1620
                // if we decide to use "application/octet-stream" for all data
1621
                // returns
1622
                // response.setContentType("application/octet-stream");
1623 731 bojilova
1624 2098 jones
                try {
1625 731 bojilova
1626 2098 jones
                    ServletOutputStream out = response.getOutputStream();
1627
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
1628
                    int b = fin.read(buf);
1629
                    while (b != -1) {
1630
                        out.write(buf, 0, b);
1631
                        b = fin.read(buf);
1632
                    }
1633
                } finally {
1634
                    if (fin != null) fin.close();
1635
                }
1636 2169 sgarg
1637 2098 jones
            } else {
1638
                // this is metadata doc
1639 2273 sgarg
                if (qformat.equals("xml") || qformat.equals("")) {
1640
                    // if equals "", that means no qformat is specified. hence
1641
                    // by default the document should be returned in xml format
1642 2098 jones
                    // set content type first
1643
                    response.setContentType("text/xml"); //MIME type
1644
                    PrintWriter out = response.getWriter();
1645
                    doc.toXml(out, user, groups, withInlineData);
1646
                } else {
1647
                    response.setContentType("text/html"); //MIME type
1648
                    PrintWriter out = response.getWriter();
1649 1360 tao
1650 2098 jones
                    // Look up the document type
1651
                    String doctype = doc.getDoctype();
1652
                    // Transform the document to the new doctype
1653
                    DBTransform dbt = new DBTransform();
1654
                    dbt.transformXMLDocument(doc.toString(user, groups,
1655
                            withInlineData), doctype, "-//W3C//HTML//EN",
1656
                            qformat, out, params);
1657
                }
1658 1360 tao
1659 2098 jones
            }
1660 2169 sgarg
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1661 2101 jones
                    docid, "read");
1662 2098 jones
        } catch (Exception except) {
1663
            throw except;
1664
        }
1665
    }
1666 1360 tao
1667 2169 sgarg
    /**
1668
     * read data from URLConnection
1669 2098 jones
     */
1670
    private void readFromURLConnection(HttpServletResponse response,
1671
            String docid) throws IOException, MalformedURLException
1672
    {
1673
        ServletOutputStream out = response.getOutputStream();
1674
        String contentType = getServletContext().getMimeType(docid); //MIME
1675
                                                                     // type
1676
        if (contentType == null) {
1677
            if (docid.endsWith(".xml")) {
1678
                contentType = "text/xml";
1679
            } else if (docid.endsWith(".css")) {
1680
                contentType = "text/css";
1681
            } else if (docid.endsWith(".dtd")) {
1682
                contentType = "text/plain";
1683
            } else if (docid.endsWith(".xsd")) {
1684
                contentType = "text/xml";
1685
            } else if (docid.endsWith("/")) {
1686
                contentType = "text/html";
1687
            } else {
1688
                File f = new File(docid);
1689
                if (f.isDirectory()) {
1690
                    contentType = "text/html";
1691
                } else {
1692
                    contentType = "application/octet-stream";
1693
                }
1694
            }
1695 1360 tao
        }
1696 2098 jones
        response.setContentType(contentType);
1697
        // if we decide to use "application/octet-stream" for all data returns
1698
        // response.setContentType("application/octet-stream");
1699 1360 tao
1700 2098 jones
        // this is http url
1701
        URL url = new URL(docid);
1702
        BufferedInputStream bis = null;
1703
        try {
1704
            bis = new BufferedInputStream(url.openStream());
1705 731 bojilova
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1706 2098 jones
            int b = bis.read(buf);
1707 731 bojilova
            while (b != -1) {
1708 2098 jones
                out.write(buf, 0, b);
1709
                b = bis.read(buf);
1710 731 bojilova
            }
1711 2098 jones
        } finally {
1712
            if (bis != null) bis.close();
1713 636 berkley
        }
1714 1360 tao
1715 636 berkley
    }
1716 1360 tao
1717 2169 sgarg
    /**
1718 2098 jones
     * read file/doc and write to ZipOutputStream
1719 2169 sgarg
     *
1720 2098 jones
     * @param docid
1721
     * @param zout
1722
     * @param user
1723
     * @param groups
1724
     * @throws ClassNotFoundException
1725
     * @throws IOException
1726
     * @throws SQLException
1727
     * @throws McdbException
1728
     * @throws Exception
1729
     */
1730 2169 sgarg
    private void addDocToZip(HttpServletRequest request, String docid,
1731 2102 jones
            ZipOutputStream zout, String user, String[] groups) throws
1732
            ClassNotFoundException, IOException, SQLException, McdbException,
1733
            Exception
1734 1293 tao
    {
1735 2098 jones
        byte[] bytestring = null;
1736
        ZipEntry zentry = null;
1737 1360 tao
1738 598 bojilova
        try {
1739 2098 jones
            URL url = new URL(docid);
1740 1360 tao
1741 2098 jones
            // this http url; read from URLConnection; add to zip
1742
            zentry = new ZipEntry(docid);
1743
            zout.putNextEntry(zentry);
1744
            BufferedInputStream bis = null;
1745
            try {
1746
                bis = new BufferedInputStream(url.openStream());
1747
                byte[] buf = new byte[4 * 1024]; // 4K buffer
1748
                int b = bis.read(buf);
1749
                while (b != -1) {
1750
                    zout.write(buf, 0, b);
1751
                    b = bis.read(buf);
1752
                }
1753
            } finally {
1754
                if (bis != null) bis.close();
1755
            }
1756
            zout.closeEntry();
1757 1716 berkley
1758 2098 jones
        } catch (MalformedURLException mue) {
1759 203 jones
1760 2098 jones
            // this is metacat doc (data file or metadata doc)
1761
            try {
1762
                DocumentImpl doc = new DocumentImpl(docid);
1763 1360 tao
1764 2098 jones
                //check the permission for read
1765 2113 jones
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1766 2098 jones
                    Exception e = new Exception("User " + user
1767
                            + " does not have "
1768
                            + "permission to read the document with the docid "
1769
                            + docid);
1770
                    throw e;
1771
                }
1772 1360 tao
1773 2098 jones
                if (doc.getRootNodeID() == 0) {
1774
                    // this is data file; add file to zip
1775
                    String filepath = MetaCatUtil.getOption("datafilepath");
1776
                    if (!filepath.endsWith("/")) {
1777
                        filepath += "/";
1778
                    }
1779
                    String filename = filepath + docid;
1780
                    FileInputStream fin = null;
1781
                    fin = new FileInputStream(filename);
1782
                    try {
1783 1360 tao
1784 2098 jones
                        zentry = new ZipEntry(docid);
1785
                        zout.putNextEntry(zentry);
1786
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
1787
                        int b = fin.read(buf);
1788
                        while (b != -1) {
1789
                            zout.write(buf, 0, b);
1790
                            b = fin.read(buf);
1791
                        }
1792
                    } finally {
1793
                        if (fin != null) fin.close();
1794
                    }
1795
                    zout.closeEntry();
1796 1716 berkley
1797 2098 jones
                } else {
1798
                    // this is metadata doc; add doc to zip
1799
                    bytestring = doc.toString().getBytes();
1800
                    zentry = new ZipEntry(docid + ".xml");
1801
                    zentry.setSize(bytestring.length);
1802
                    zout.putNextEntry(zentry);
1803
                    zout.write(bytestring, 0, bytestring.length);
1804
                    zout.closeEntry();
1805
                }
1806 2169 sgarg
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1807 2101 jones
                        docid, "read");
1808 2098 jones
            } catch (Exception except) {
1809
                throw except;
1810
            }
1811 1360 tao
        }
1812 2098 jones
    }
1813 309 bojilova
1814 2098 jones
    /**
1815
     * If metacat couldn't find a data file or document locally, it will read
1816
     * this docid from its home server. This is for the replication feature
1817
     */
1818
    private void readFromRemoteMetaCat(HttpServletResponse response,
1819
            String docid, String rev, String user, String password,
1820
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
1821
            throws Exception
1822 1466 tao
    {
1823 2098 jones
        // Create a object of RemoteDocument, "" is for zipEntryPath
1824
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
1825
                password, "");
1826
        String docType = remoteDoc.getDocType();
1827
        // Only read data file
1828
        if (docType.equals("BIN")) {
1829
            // If it is zip format
1830
            if (zip) {
1831
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
1832
            } else {
1833
                if (out == null) {
1834
                    out = response.getOutputStream();
1835
                }
1836
                response.setContentType("application/octet-stream");
1837
                remoteDoc.readDocumentFromRemoteServer(out);
1838
            }
1839
        } else {
1840
            throw new Exception("Docid: " + docid + "." + rev
1841
                    + " couldn't find");
1842
        }
1843 203 jones
    }
1844
1845 2098 jones
    /**
1846
     * Handle the database putdocument request and write an XML document to the
1847
     * database connection
1848
     */
1849 2102 jones
    private void handleInsertOrUpdateAction(HttpServletRequest request,
1850
            HttpServletResponse response, PrintWriter out, Hashtable params,
1851 2098 jones
            String user, String[] groups)
1852
    {
1853 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1854 2098 jones
        DBConnection dbConn = null;
1855
        int serialNumber = -1;
1856 1360 tao
1857 2252 sgarg
        if(params.get("docid") == null){
1858
            out.println("<?xml version=\"1.0\"?>");
1859
            out.println("<error>");
1860
            out.println("Docid not specified");
1861
            out.println("</error>");
1862 2663 sgarg
            logMetacat.error("Docid not specified");
1863 2252 sgarg
            return;
1864
        }
1865 2576 sgarg
1866
        if(!MetaCatUtil.canInsertOrUpdate(user, groups)){
1867
        	out.println("<?xml version=\"1.0\"?>");
1868
            out.println("<error>");
1869
            out.println("User '" + user + "' not allowed to insert and update");
1870
            out.println("</error>");
1871 2663 sgarg
            logMetacat.error("User '" + user + "' not allowed to insert and update");
1872 2576 sgarg
            return;
1873
        }
1874 2252 sgarg
1875 2098 jones
        try {
1876
            // Get the document indicated
1877
            String[] doctext = (String[]) params.get("doctext");
1878
            String pub = null;
1879
            if (params.containsKey("public")) {
1880
                pub = ((String[]) params.get("public"))[0];
1881
            }
1882 1360 tao
1883 2098 jones
            StringReader dtd = null;
1884
            if (params.containsKey("dtdtext")) {
1885
                String[] dtdtext = (String[]) params.get("dtdtext");
1886
                try {
1887
                    if (!dtdtext[0].equals("")) {
1888
                        dtd = new StringReader(dtdtext[0]);
1889
                    }
1890
                } catch (NullPointerException npe) {
1891
                }
1892
            }
1893 2347 sgarg
1894
            if(doctext == null){
1895
                out.println("<?xml version=\"1.0\"?>");
1896
                out.println("<error>");
1897
                out.println("Document text not submitted");
1898
                out.println("</error>");
1899
                return;
1900
            }
1901
1902 2098 jones
            StringReader xml = new StringReader(doctext[0]);
1903
            boolean validate = false;
1904
            DocumentImplWrapper documentWrapper = null;
1905
            try {
1906
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1907
                // >
1908
                // in order to decide whether to use validation parser
1909
                validate = needDTDValidation(xml);
1910
                if (validate) {
1911
                    // set a dtd base validation parser
1912
                    String rule = DocumentImpl.DTD;
1913
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1914 2711 sgarg
                } else {
1915
1916 2169 sgarg
                    String namespace = findNamespace(xml);
1917 2711 sgarg
1918
                	if (namespace != null) {
1919
                		if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1920
                				|| namespace.compareTo(
1921
                				DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1922
                			// set eml2 base	 validation parser
1923
                			String rule = DocumentImpl.EML200;
1924
                			// using emlparser to check id validation
1925
                			EMLParser parser = new EMLParser(doctext[0]);
1926
                			documentWrapper = new DocumentImplWrapper(rule, true);
1927
                		} else if (namespace.compareTo(
1928 2169 sgarg
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1929 2711 sgarg
                			// set eml2 base validation parser
1930
                			String rule = DocumentImpl.EML210;
1931
                			// using emlparser to check id validation
1932
                			EMLParser parser = new EMLParser(doctext[0]);
1933
                			documentWrapper = new DocumentImplWrapper(rule, true);
1934
                		} else {
1935
                			// set schema base validation parser
1936
                			String rule = DocumentImpl.SCHEMA;
1937
                			documentWrapper = new DocumentImplWrapper(rule, true);
1938
                		}
1939
                	} else {
1940
                		documentWrapper = new DocumentImplWrapper("", false);
1941
                	}
1942 2098 jones
                }
1943 695 bojilova
1944 2098 jones
                String[] action = (String[]) params.get("action");
1945
                String[] docid = (String[]) params.get("docid");
1946
                String newdocid = null;
1947 695 bojilova
1948 2098 jones
                String doAction = null;
1949
                if (action[0].equals("insert")) {
1950
                    doAction = "INSERT";
1951
                } else if (action[0].equals("update")) {
1952
                    doAction = "UPDATE";
1953
                }
1954 695 bojilova
1955 2098 jones
                try {
1956
                    // get a connection from the pool
1957
                    dbConn = DBConnectionPool
1958
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1959
                    serialNumber = dbConn.getCheckOutSerialNumber();
1960 1716 berkley
1961 2098 jones
                    // write the document to the database
1962
                    try {
1963
                        String accNumber = docid[0];
1964 2753 jones
                        logMetacat.debug("" + doAction + " "
1965 2663 sgarg
                                + accNumber + "...");
1966 2098 jones
                        if (accNumber.equals("")) {
1967
                            accNumber = null;
1968 2102 jones
                        }
1969 2098 jones
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1970
                                doAction, accNumber, user, groups);
1971 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
1972 2102 jones
                                user, accNumber, action[0]);
1973
                    } catch (NullPointerException npe) {
1974 2098 jones
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1975
                                doAction, null, user, groups);
1976 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
1977 2102 jones
                                user, "", action[0]);
1978
                    }
1979
                }
1980 2098 jones
                finally {
1981
                    // Return db connection
1982
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1983
                }
1984 1716 berkley
1985 2098 jones
                // set content type and other response header fields first
1986
                //response.setContentType("text/xml");
1987
                out.println("<?xml version=\"1.0\"?>");
1988
                out.println("<success>");
1989
                out.println("<docid>" + newdocid + "</docid>");
1990
                out.println("</success>");
1991 1716 berkley
1992 2098 jones
            } catch (NullPointerException npe) {
1993
                //response.setContentType("text/xml");
1994
                out.println("<?xml version=\"1.0\"?>");
1995
                out.println("<error>");
1996
                out.println(npe.getMessage());
1997
                out.println("</error>");
1998 2690 sgarg
                logMetacat.warn("Error in writing eml document to the database" + npe.getMessage());
1999 2729 sgarg
                npe.printStackTrace();
2000 2098 jones
            }
2001
        } catch (Exception e) {
2002
            //response.setContentType("text/xml");
2003
            out.println("<?xml version=\"1.0\"?>");
2004
            out.println("<error>");
2005
            out.println(e.getMessage());
2006
            out.println("</error>");
2007 2690 sgarg
            logMetacat.warn("Error in writing eml document to the database" + e.getMessage());
2008 2729 sgarg
            e.printStackTrace();
2009 1760 tao
        }
2010 1409 tao
    }
2011 1716 berkley
2012 2098 jones
    /**
2013
     * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > in
2014
     * order to decide whether to use validation parser
2015
     */
2016
    private static boolean needDTDValidation(StringReader xmlreader)
2017
            throws IOException
2018 1629 tao
    {
2019 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2020 2098 jones
        StringBuffer cbuff = new StringBuffer();
2021
        java.util.Stack st = new java.util.Stack();
2022
        boolean validate = false;
2023
        int c;
2024
        int inx;
2025 2089 tao
2026 2098 jones
        // read from the stream until find the keywords
2027
        while ((st.empty() || st.size() < 4) && ((c = xmlreader.read()) != -1)) {
2028
            cbuff.append((char) c);
2029 1716 berkley
2030 2098 jones
            // "<!DOCTYPE" keyword is found; put it in the stack
2031
            if ((inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1) {
2032
                cbuff = new StringBuffer();
2033
                st.push("<!DOCTYPE");
2034
            }
2035
            // "PUBLIC" keyword is found; put it in the stack
2036
            if ((inx = cbuff.toString().indexOf("PUBLIC")) != -1) {
2037
                cbuff = new StringBuffer();
2038
                st.push("PUBLIC");
2039
            }
2040
            // "SYSTEM" keyword is found; put it in the stack
2041
            if ((inx = cbuff.toString().indexOf("SYSTEM")) != -1) {
2042
                cbuff = new StringBuffer();
2043
                st.push("SYSTEM");
2044
            }
2045
            // ">" character is found; put it in the stack
2046
            // ">" is found twice: fisrt from <?xml ...?>
2047
            // and second from <!DOCTYPE ... >
2048
            if ((inx = cbuff.toString().indexOf(">")) != -1) {
2049
                cbuff = new StringBuffer();
2050
                st.push(">");
2051
            }
2052
        }
2053 203 jones
2054 2098 jones
        // close the stream
2055
        xmlreader.reset();
2056 1360 tao
2057 2098 jones
        // check the stack whether it contains the keywords:
2058
        // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
2059
        if (st.size() == 4) {
2060
            if (((String) st.pop()).equals(">")
2061
                    && (((String) st.peek()).equals("PUBLIC") | ((String) st
2062
                            .pop()).equals("SYSTEM"))
2063
                    && ((String) st.pop()).equals("<!DOCTYPE")) {
2064
                validate = true;
2065
            }
2066
        }
2067 1360 tao
2068 2753 jones
        logMetacat.info("Validation for dtd is " + validate);
2069 2098 jones
        return validate;
2070 1360 tao
    }
2071
2072 2098 jones
    // END OF INSERT/UPDATE SECTION
2073 68 higgins
2074 2098 jones
    /* check if the xml string contains key words to specify schema loocation */
2075 2169 sgarg
    private String findNamespace(StringReader xml) throws IOException
2076 2098 jones
    {
2077 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2078 2169 sgarg
        String namespace = null;
2079
2080
        String eml2_0_0NameSpace = DocumentImpl.EML2_0_0NAMESPACE;
2081 2224 sgarg
        String eml2_0_1NameSpace = DocumentImpl.EML2_0_1NAMESPACE;
2082 2169 sgarg
        String eml2_1_0NameSpace = DocumentImpl.EML2_1_0NAMESPACE;
2083
2084 2098 jones
        if (xml == null) {
2085 2753 jones
            logMetacat.debug("Validation for schema is "
2086 2663 sgarg
                    + namespace);
2087 2169 sgarg
            return namespace;
2088 2098 jones
        }
2089
        String targetLine = getSchemaLine(xml);
2090 2918 sgarg
2091 2098 jones
        if (targetLine != null) {
2092 1360 tao
2093 2711 sgarg
        	// find if the root element has prefix
2094
        	String prefix = getPrefix(targetLine);
2095 2729 sgarg
        	logMetacat.info("prefix is:" + prefix);
2096 2711 sgarg
        	int startIndex = 0;
2097
2098 2729 sgarg
2099 2711 sgarg
        	if(prefix != null)
2100
        	{
2101
        		// if prefix found then look for xmlns:prefix
2102
        		// element to find the ns
2103 2712 sgarg
        		String namespaceWithPrefix = NAMESPACEKEYWORD
2104
        					+ ":" + prefix;
2105 2711 sgarg
        		startIndex = targetLine.indexOf(namespaceWithPrefix);
2106 2753 jones
            	logMetacat.debug("namespaceWithPrefix is:" + namespaceWithPrefix+":");
2107
            	logMetacat.debug("startIndex is:" + startIndex);
2108 2712 sgarg
2109 2711 sgarg
        	} else {
2110
        		// if prefix not found then look for xmlns
2111
        		// attribute to find the ns
2112
        		startIndex = targetLine.indexOf(NAMESPACEKEYWORD);
2113 2753 jones
            	logMetacat.debug("startIndex is:" + startIndex);
2114 2711 sgarg
        	}
2115
2116 2098 jones
            int start = 1;
2117
            int end = 1;
2118 2711 sgarg
            String namespaceString = null;
2119 2098 jones
            int count = 0;
2120
            if (startIndex != -1) {
2121
                for (int i = startIndex; i < targetLine.length(); i++) {
2122
                    if (targetLine.charAt(i) == '"') {
2123
                        count++;
2124
                    }
2125
                    if (targetLine.charAt(i) == '"' && count == 1) {
2126
                        start = i;
2127
                    }
2128
                    if (targetLine.charAt(i) == '"' && count == 2) {
2129
                        end = i;
2130
                        break;
2131
                    }
2132
                }
2133 2711 sgarg
            }
2134
            // else: xmlns not found. namespace = null will be returned
2135
2136 2753 jones
         	logMetacat.debug("targetLine is " + targetLine);
2137 2729 sgarg
         	logMetacat.debug("start is " + end);
2138
         	logMetacat.debug("end is " + end);
2139
2140 2711 sgarg
            if(start < end){
2141
            	namespaceString = targetLine.substring(start + 1, end);
2142 2753 jones
            	logMetacat.debug("namespaceString is " + namespaceString);
2143 2098 jones
            }
2144 2753 jones
            logMetacat.debug("namespace in xml is: "
2145 2711 sgarg
                    + namespaceString);
2146 2729 sgarg
            if(namespaceString != null){
2147
            	if (namespaceString.indexOf(eml2_0_0NameSpace) != -1) {
2148
            		namespace = eml2_0_0NameSpace;
2149
            	} else if (namespaceString.indexOf(eml2_0_1NameSpace) != -1) {
2150
            		namespace = eml2_0_1NameSpace;
2151
            	} else if (namespaceString.indexOf(eml2_1_0NameSpace) != -1) {
2152
            		namespace = eml2_1_0NameSpace;
2153
            	} else {
2154
            		namespace = namespaceString;
2155
            	}
2156 2098 jones
            }
2157
        }
2158 185 jones
2159 2753 jones
        logMetacat.debug("Validation for eml is " + namespace);
2160 2224 sgarg
2161 2169 sgarg
        return namespace;
2162 1360 tao
2163 103 jones
    }
2164 68 higgins
2165 2098 jones
    private String getSchemaLine(StringReader xml) throws IOException
2166
    {
2167 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2168 2098 jones
        // find the line
2169
        String secondLine = null;
2170
        int count = 0;
2171
        int endIndex = 0;
2172
        int startIndex = 0;
2173
        final int TARGETNUM = 2;
2174
        StringBuffer buffer = new StringBuffer();
2175
        boolean comment = false;
2176
        char thirdPreviousCharacter = '?';
2177
        char secondPreviousCharacter = '?';
2178
        char previousCharacter = '?';
2179
        char currentCharacter = '?';
2180 2268 sgarg
        int tmp = xml.read();
2181
        while (tmp != -1) {
2182
            currentCharacter = (char)tmp;
2183 2098 jones
            //in a comment
2184
            if (currentCharacter == '-' && previousCharacter == '-'
2185
                    && secondPreviousCharacter == '!'
2186
                    && thirdPreviousCharacter == '<') {
2187
                comment = true;
2188
            }
2189
            //out of comment
2190
            if (comment && currentCharacter == '>' && previousCharacter == '-'
2191
                    && secondPreviousCharacter == '-') {
2192
                comment = false;
2193
            }
2194 68 higgins
2195 2098 jones
            //this is not comment
2196
            if (currentCharacter != '!' && previousCharacter == '<' && !comment) {
2197
                count++;
2198
            }
2199
            // get target line
2200
            if (count == TARGETNUM && currentCharacter != '>') {
2201
                buffer.append(currentCharacter);
2202
            }
2203
            if (count == TARGETNUM && currentCharacter == '>') {
2204
                break;
2205
            }
2206
            thirdPreviousCharacter = secondPreviousCharacter;
2207
            secondPreviousCharacter = previousCharacter;
2208
            previousCharacter = currentCharacter;
2209 2268 sgarg
            tmp = xml.read();
2210 2098 jones
        }
2211
        secondLine = buffer.toString();
2212 2753 jones
        logMetacat.debug("the second line string is: " + secondLine);
2213 2663 sgarg
2214 2098 jones
        xml.reset();
2215
        return secondLine;
2216
    }
2217 253 jones
2218 2711 sgarg
    private String getPrefix(String schemaLine)
2219
    {
2220 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2221 2922 jones
        String prefix = null;
2222
        if(schemaLine.indexOf(" ") > 0){
2223
            String rootElement = "";
2224
            try {
2225
                rootElement = schemaLine.substring(0, schemaLine.indexOf(" "));
2226
            } catch (StringIndexOutOfBoundsException sioobe) {
2227
                rootElement = schemaLine;
2228
            }
2229
2230
            logMetacat.debug("rootElement:" + rootElement);
2231 2711 sgarg
2232 2922 jones
            if(rootElement.indexOf(":") > 0){
2233
                prefix = rootElement.substring(rootElement.indexOf(":") + 1,
2234
                    rootElement.length());
2235
            }
2236 2845 sgarg
2237 2922 jones
            if(prefix != null){
2238
                return prefix.trim();
2239
            }
2240
        }
2241
        return null;
2242 2711 sgarg
    }
2243
2244 2098 jones
    /**
2245
     * Handle the database delete request and delete an XML document from the
2246
     * database connection
2247
     */
2248
    private void handleDeleteAction(PrintWriter out, Hashtable params,
2249 2169 sgarg
            HttpServletRequest request, HttpServletResponse response,
2250 2102 jones
            String user, String[] groups)
2251 2098 jones
    {
2252 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2253 2098 jones
        String[] docid = (String[]) params.get("docid");
2254 1360 tao
2255 2251 sgarg
        if(docid == null){
2256
          response.setContentType("text/xml");
2257
          out.println("<?xml version=\"1.0\"?>");
2258
          out.println("<error>");
2259 2252 sgarg
          out.println("Docid not specified.");
2260 2251 sgarg
          out.println("</error>");
2261 2668 sgarg
          logMetacat.error("Docid not specified for the document to be deleted.");
2262 2251 sgarg
        } else {
2263 1360 tao
2264 2251 sgarg
            // delete the document from the database
2265 2098 jones
            try {
2266 2251 sgarg
2267
                try {
2268 2298 tao
                    // null means notify server is null
2269
                    DocumentImpl.delete(docid[0], user, groups, null);
2270 2251 sgarg
                    EventLog.getInstance().log(request.getRemoteAddr(),
2271
                                               user, docid[0], "delete");
2272
                    response.setContentType("text/xml");
2273
                    out.println("<?xml version=\"1.0\"?>");
2274
                    out.println("<success>");
2275
                    out.println("Document deleted.");
2276
                    out.println("</success>");
2277 2753 jones
                    logMetacat.info("Document deleted.");
2278 2251 sgarg
                }
2279
                catch (AccessionNumberException ane) {
2280
                    response.setContentType("text/xml");
2281
                    out.println("<?xml version=\"1.0\"?>");
2282
                    out.println("<error>");
2283 2253 sgarg
                    //out.println("Error deleting document!!!");
2284 2251 sgarg
                    out.println(ane.getMessage());
2285
                    out.println("</error>");
2286 2668 sgarg
                    logMetacat.error("Document could not be deleted: "
2287
                    		+ ane.getMessage());
2288 2251 sgarg
                }
2289
            }
2290
            catch (Exception e) {
2291 2098 jones
                response.setContentType("text/xml");
2292
                out.println("<?xml version=\"1.0\"?>");
2293
                out.println("<error>");
2294 2251 sgarg
                out.println(e.getMessage());
2295 2098 jones
                out.println("</error>");
2296 2668 sgarg
                logMetacat.error("Document could not be deleted: "
2297
                		+ e.getMessage());
2298 2098 jones
            }
2299
        }
2300 1292 tao
    }
2301 1360 tao
2302 2098 jones
    /**
2303
     * Handle the validation request and return the results to the requestor
2304
     */
2305
    private void handleValidateAction(PrintWriter out, Hashtable params)
2306 1292 tao
    {
2307 1360 tao
2308 2098 jones
        // Get the document indicated
2309
        String valtext = null;
2310
        DBConnection dbConn = null;
2311
        int serialNumber = -1;
2312 1292 tao
2313 2098 jones
        try {
2314
            valtext = ((String[]) params.get("valtext"))[0];
2315
        } catch (Exception nullpe) {
2316 1360 tao
2317 2098 jones
            String docid = null;
2318
            try {
2319
                // Find the document id number
2320
                docid = ((String[]) params.get("docid"))[0];
2321 1360 tao
2322 2098 jones
                // Get the document indicated from the db
2323
                DocumentImpl xmldoc = new DocumentImpl(docid);
2324
                valtext = xmldoc.toString();
2325 688 bojilova
2326 2098 jones
            } catch (NullPointerException npe) {
2327 1360 tao
2328 2098 jones
                out.println("<error>Error getting document ID: " + docid
2329
                        + "</error>");
2330
                //if ( conn != null ) { util.returnConnection(conn); }
2331
                return;
2332
            } catch (Exception e) {
2333 688 bojilova
2334 2098 jones
                out.println(e.getMessage());
2335
            }
2336
        }
2337 688 bojilova
2338 2098 jones
        try {
2339
            // get a connection from the pool
2340
            dbConn = DBConnectionPool
2341
                    .getDBConnection("MetaCatServlet.handleValidateAction");
2342
            serialNumber = dbConn.getCheckOutSerialNumber();
2343 2752 jones
            DBValidate valobj = new DBValidate(dbConn);
2344 2098 jones
            boolean valid = valobj.validateString(valtext);
2345 1360 tao
2346 2098 jones
            // set content type and other response header fields first
2347 688 bojilova
2348 2098 jones
            out.println(valobj.returnErrors());
2349 731 bojilova
2350 2098 jones
        } catch (NullPointerException npe2) {
2351
            // set content type and other response header fields first
2352 1360 tao
2353 2098 jones
            out.println("<error>Error validating document.</error>");
2354
        } catch (Exception e) {
2355 731 bojilova
2356 2098 jones
            out.println(e.getMessage());
2357
        } finally {
2358
            // Return db connection
2359
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2360
        }
2361
    }
2362 1360 tao
2363 2098 jones
    /**
2364
     * Handle "getrevsionanddoctype" action Given a docid, return it's current
2365
     * revision and doctype from data base The output is String look like
2366
     * "rev;doctype"
2367
     */
2368
    private void handleGetRevisionAndDocTypeAction(PrintWriter out,
2369
            Hashtable params)
2370
    {
2371
        // To store doc parameter
2372
        String[] docs = new String[10];
2373
        // Store a single doc id
2374
        String givenDocId = null;
2375
        // Get docid from parameters
2376
        if (params.containsKey("docid")) {
2377
            docs = (String[]) params.get("docid");
2378
        }
2379
        // Get first docid form string array
2380
        givenDocId = docs[0];
2381 731 bojilova
2382 2098 jones
        try {
2383
            // Make sure there is a docid
2384
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
2385
                    "User didn't specify docid!"); }//if
2386 1360 tao
2387 2098 jones
            // Create a DBUtil object
2388
            DBUtil dbutil = new DBUtil();
2389
            // Get a rev and doctype
2390
            String revAndDocType = dbutil
2391
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
2392
            out.println(revAndDocType);
2393 731 bojilova
2394 2098 jones
        } catch (Exception e) {
2395
            // Handle exception
2396
            out.println("<?xml version=\"1.0\"?>");
2397
            out.println("<error>");
2398
            out.println(e.getMessage());
2399
            out.println("</error>");
2400
        }
2401 302 bojilova
2402 2098 jones
    }
2403 1360 tao
2404 2098 jones
    /**
2405
     * Handle "getaccesscontrol" action. Read Access Control List from db
2406
     * connection in XML format
2407
     */
2408
    private void handleGetAccessControlAction(PrintWriter out,
2409
            Hashtable params, HttpServletResponse response, String username,
2410
            String[] groupnames)
2411
    {
2412
        DBConnection dbConn = null;
2413
        int serialNumber = -1;
2414
        String docid = ((String[]) params.get("docid"))[0];
2415 302 bojilova
2416 2098 jones
        try {
2417 1360 tao
2418 2098 jones
            // get connection from the pool
2419
            dbConn = DBConnectionPool
2420
                    .getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2421
            serialNumber = dbConn.getCheckOutSerialNumber();
2422
            AccessControlList aclobj = new AccessControlList(dbConn);
2423
            String acltext = aclobj.getACL(docid, username, groupnames);
2424
            out.println(acltext);
2425 302 bojilova
2426 2098 jones
        } catch (Exception e) {
2427
            out.println("<?xml version=\"1.0\"?>");
2428
            out.println("<error>");
2429
            out.println(e.getMessage());
2430
            out.println("</error>");
2431
        } finally {
2432
            // Retrun db connection to pool
2433
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2434
        }
2435 1360 tao
    }
2436
2437 2098 jones
    /**
2438
     * Handle the "getprincipals" action. Read all principals from
2439
     * authentication scheme in XML format
2440
     */
2441
    private void handleGetPrincipalsAction(PrintWriter out, String user,
2442
            String password)
2443
    {
2444
        try {
2445
            AuthSession auth = new AuthSession();
2446
            String principals = auth.getPrincipals(user, password);
2447
            out.println(principals);
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
        }
2455
    }
2456 699 bojilova
2457 2098 jones
    /**
2458
     * Handle "getdoctypes" action. Read all doctypes from db connection in XML
2459
     * format
2460
     */
2461
    private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
2462
            HttpServletResponse response)
2463
    {
2464
        try {
2465
            DBUtil dbutil = new DBUtil();
2466
            String doctypes = dbutil.readDoctypes();
2467
            out.println(doctypes);
2468
        } catch (Exception e) {
2469
            out.println("<?xml version=\"1.0\"?>");
2470
            out.println("<error>");
2471
            out.println(e.getMessage());
2472
            out.println("</error>");
2473
        }
2474
    }
2475 1360 tao
2476 2098 jones
    /**
2477
     * Handle the "getdtdschema" action. Read DTD or Schema file for a given
2478
     * doctype from Metacat catalog system
2479
     */
2480
    private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2481
            HttpServletResponse response)
2482
    {
2483 699 bojilova
2484 2098 jones
        String doctype = null;
2485
        String[] doctypeArr = (String[]) params.get("doctype");
2486 699 bojilova
2487 2098 jones
        // get only the first doctype specified in the list of doctypes
2488
        // it could be done for all doctypes in that list
2489
        if (doctypeArr != null) {
2490
            doctype = ((String[]) params.get("doctype"))[0];
2491
        }
2492 699 bojilova
2493 2098 jones
        try {
2494
            DBUtil dbutil = new DBUtil();
2495
            String dtdschema = dbutil.readDTDSchema(doctype);
2496
            out.println(dtdschema);
2497 1360 tao
2498 2098 jones
        } catch (Exception e) {
2499
            out.println("<?xml version=\"1.0\"?>");
2500
            out.println("<error>");
2501
            out.println(e.getMessage());
2502
            out.println("</error>");
2503
        }
2504 699 bojilova
2505 1360 tao
    }
2506
2507 2098 jones
    /**
2508
     * Handle the "getlastdocid" action. Get the latest docid with rev number
2509
     * from db connection in XML format
2510
     */
2511
    private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2512
            HttpServletResponse response)
2513
    {
2514 699 bojilova
2515 2098 jones
        String scope = ((String[]) params.get("scope"))[0];
2516
        if (scope == null) {
2517
            scope = ((String[]) params.get("username"))[0];
2518
        }
2519 793 bojilova
2520 2098 jones
        try {
2521 1217 tao
2522 2098 jones
            DBUtil dbutil = new DBUtil();
2523
            String lastDocid = dbutil.getMaxDocid(scope);
2524
            out.println("<?xml version=\"1.0\"?>");
2525
            out.println("<lastDocid>");
2526
            out.println("  <scope>" + scope + "</scope>");
2527
            out.println("  <docid>" + lastDocid + "</docid>");
2528
            out.println("</lastDocid>");
2529 793 bojilova
2530 2098 jones
        } catch (Exception e) {
2531
            out.println("<?xml version=\"1.0\"?>");
2532
            out.println("<error>");
2533
            out.println(e.getMessage());
2534
            out.println("</error>");
2535
        }
2536 1217 tao
    }
2537 1360 tao
2538 2098 jones
    /**
2539 2113 jones
     * Print a report from the event log based on filter parameters passed in
2540
     * from the web.
2541 2169 sgarg
     *
2542 2113 jones
     * @param params the parameters from the web request
2543
     * @param request the http request object for getting request details
2544
     * @param response the http response object for writing output
2545
     */
2546
    private void handleGetLogAction(Hashtable params, HttpServletRequest request,
2547 2558 sgarg
            HttpServletResponse response, String username, String[] groups)
2548 2113 jones
    {
2549 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2550 2113 jones
        try {
2551 2312 jones
            response.setContentType("text/xml");
2552
            PrintWriter out = response.getWriter();
2553 2347 sgarg
2554 2312 jones
            // Check that the user is authenticated as an administrator account
2555 2558 sgarg
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2556 2312 jones
                out.print("<error>");
2557 2347 sgarg
                out.print("The user \"" + username +
2558 2312 jones
                        "\" is not authorized for this action.");
2559
                out.print("</error>");
2560
                return;
2561 2113 jones
            }
2562 2347 sgarg
2563 2312 jones
            // Get all of the parameters in the correct formats
2564
            String[] ipAddress = (String[])params.get("ipaddress");
2565
            String[] principal = (String[])params.get("principal");
2566
            String[] docid = (String[])params.get("docid");
2567
            String[] event = (String[])params.get("event");
2568
            String[] startArray = (String[]) params.get("start");
2569
            String[] endArray = (String[]) params.get("end");
2570
            String start = null;
2571
            String end = null;
2572
            if (startArray != null) {
2573
                start = startArray[0];
2574
            }
2575
            if (endArray != null) {
2576
                end = endArray[0];
2577
            }
2578
            Timestamp startDate = null;
2579
            Timestamp endDate = null;
2580
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2581
            try {
2582
                if (start != null) {
2583
                    startDate = new Timestamp((format.parse(start)).getTime());
2584
                }
2585
                if (end != null) {
2586
                    endDate = new Timestamp((format.parse(end)).getTime());
2587
                }
2588
            } catch (ParseException e) {
2589
                System.out.println("Failed to created Timestamp from input.");
2590
            }
2591 2347 sgarg
2592 2312 jones
            // Request the report by passing the filter parameters
2593
            out.println(EventLog.getInstance().getReport(ipAddress, principal,
2594
                    docid, event, startDate, endDate));
2595
            out.close();
2596
        } catch (IOException e) {
2597 2663 sgarg
            logMetacat.error(
2598
                    "Could not open http response for writing: " + e.getMessage());
2599 2113 jones
        }
2600 2312 jones
    }
2601 2169 sgarg
2602 2312 jones
    /**
2603
     * Rebuild the index for one or more documents. If the docid parameter is
2604
     * provided, rebuild for just that one document or list of documents. If
2605
     * not, then rebuild the index for all documents in the xml_documents
2606
     * table.
2607
     *
2608
     * @param params the parameters from the web request
2609
     * @param request the http request object for getting request details
2610
     * @param response the http response object for writing output
2611
     * @param username the username of the authenticated user
2612
     */
2613 2347 sgarg
    private void handleBuildIndexAction(Hashtable params,
2614 2312 jones
            HttpServletRequest request, HttpServletResponse response,
2615 2558 sgarg
            String username, String[] groups)
2616 2312 jones
    {
2617 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2618
2619 2312 jones
        // Get all of the parameters in the correct formats
2620
        String[] docid = (String[])params.get("docid");
2621
2622
        // Rebuild the indices for appropriate documents
2623 2113 jones
        try {
2624
            response.setContentType("text/xml");
2625
            PrintWriter out = response.getWriter();
2626 2347 sgarg
2627 2312 jones
            // Check that the user is authenticated as an administrator account
2628 2558 sgarg
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2629 2312 jones
                out.print("<error>");
2630 2347 sgarg
                out.print("The user \"" + username +
2631 2312 jones
                        "\" is not authorized for this action.");
2632
                out.print("</error>");
2633
                return;
2634
            }
2635
2636
            // Process the documents
2637
            out.println("<success>");
2638
            if (docid == null || docid.length == 0) {
2639
                // Process all of the documents
2640
                try {
2641
                    Vector documents = getDocumentList();
2642
                    Iterator it = documents.iterator();
2643
                    while (it.hasNext()) {
2644
                        String id = (String) it.next();
2645
                        buildDocumentIndex(id, out);
2646
                    }
2647
                } catch (SQLException se) {
2648
                    out.print("<error>");
2649
                    out.print(se.getMessage());
2650
                    out.println("</error>");
2651
                }
2652
            } else {
2653
                // Only process the requested documents
2654
                for (int i = 0; i < docid.length; i++) {
2655
                    buildDocumentIndex(docid[i], out);
2656
                }
2657
            }
2658
            out.println("</success>");
2659 2113 jones
            out.close();
2660
        } catch (IOException e) {
2661 2663 sgarg
            logMetacat.error(
2662 2169 sgarg
                    "Could not open http response for writing: "
2663 2663 sgarg
                    + e.getMessage());
2664 2113 jones
        }
2665
    }
2666 2169 sgarg
2667 2113 jones
    /**
2668 2347 sgarg
     * Build the index for one document by reading the document and
2669 2312 jones
     * calling its buildIndex() method.
2670
     *
2671
     * @param docid the document (with revision) to rebuild
2672
     * @param out the PrintWriter to which output is printed
2673
     */
2674
    private void buildDocumentIndex(String docid, PrintWriter out)
2675
    {
2676
        try {
2677
            DocumentImpl doc = new DocumentImpl(docid, false);
2678
            doc.buildIndex();
2679
            out.print("<docid>" + docid);
2680
            out.println("</docid>");
2681
        } catch (McdbException me) {
2682
            out.print("<error>");
2683
            out.print(me.getMessage());
2684
            out.println("</error>");
2685
        }
2686
    }
2687
2688
    /**
2689 2098 jones
     * Handle documents passed to metacat that are encoded using the
2690
     * "multipart/form-data" mime type. This is typically used for uploading
2691
     * data files which may be binary and large.
2692
     */
2693
    private void handleMultipartForm(HttpServletRequest request,
2694
            HttpServletResponse response)
2695
    {
2696 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2697 2098 jones
        PrintWriter out = null;
2698
        String action = null;
2699 793 bojilova
2700 2098 jones
        // Parse the multipart form, and save the parameters in a Hashtable and
2701
        // save the FileParts in a hashtable
2702 798 jones
2703 2098 jones
        Hashtable params = new Hashtable();
2704
        Hashtable fileList = new Hashtable();
2705
        int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2706
                .intValue();
2707 2663 sgarg
        logMetacat.info(
2708 2753 jones
                "The size limit of uploaded data files is: " + sizeLimit);
2709 798 jones
2710 2098 jones
        try {
2711
            MultipartParser mp = new MultipartParser(request,
2712
                    sizeLimit * 1024 * 1024);
2713
            Part part;
2714
            while ((part = mp.readNextPart()) != null) {
2715
                String name = part.getName();
2716 798 jones
2717 2098 jones
                if (part.isParam()) {
2718
                    // it's a parameter part
2719
                    ParamPart paramPart = (ParamPart) part;
2720
                    String value = paramPart.getStringValue();
2721
                    params.put(name, value);
2722
                    if (name.equals("action")) {
2723
                        action = value;
2724
                    }
2725
                } else if (part.isFile()) {
2726
                    // it's a file part
2727
                    FilePart filePart = (FilePart) part;
2728
                    fileList.put(name, filePart);
2729 798 jones
2730 2098 jones
                    // Stop once the first file part is found, otherwise going
2731
                    // onto the
2732
                    // next part prevents access to the file contents. So...for
2733
                    // upload
2734
                    // to work, the datafile must be the last part
2735
                    break;
2736
                }
2737
            }
2738
        } catch (IOException ioe) {
2739
            try {
2740
                out = response.getWriter();
2741
            } catch (IOException ioe2) {
2742 2663 sgarg
                logMetacat.fatal("Fatal Error: couldn't get response output stream.");
2743 2098 jones
            }
2744
            out.println("<?xml version=\"1.0\"?>");
2745
            out.println("<error>");
2746
            out.println("Error: problem reading multipart data.");
2747
            out.println("</error>");
2748 798 jones
        }
2749
2750 2098 jones
        // Get the session information
2751
        String username = null;
2752
        String password = null;
2753
        String[] groupnames = null;
2754
        String sess_id = null;
2755 798 jones
2756 2098 jones
        // be aware of session expiration on every request
2757
        HttpSession sess = request.getSession(true);
2758
        if (sess.isNew()) {
2759
            // session expired or has not been stored b/w user requests
2760
            username = "public";
2761
            sess.setAttribute("username", username);
2762
        } else {
2763
            username = (String) sess.getAttribute("username");
2764
            password = (String) sess.getAttribute("password");
2765
            groupnames = (String[]) sess.getAttribute("groupnames");
2766
            try {
2767
                sess_id = (String) sess.getId();
2768
            } catch (IllegalStateException ise) {
2769
                System.out
2770
                        .println("error in  handleMultipartForm: this shouldn't "
2771
                                + "happen: the session should be valid: "
2772
                                + ise.getMessage());
2773
            }
2774
        }
2775 1360 tao
2776 2098 jones
        // Get the out stream
2777
        try {
2778
            out = response.getWriter();
2779 798 jones
        } catch (IOException ioe2) {
2780 2663 sgarg
            logMetacat.error("Fatal Error: couldn't get response "
2781
                    + "output stream.");
2782 798 jones
        }
2783 1360 tao
2784 2098 jones
        if (action.equals("upload")) {
2785
            if (username != null && !username.equals("public")) {
2786
                handleUploadAction(request, out, params, fileList, username,
2787
                        groupnames);
2788
            } else {
2789 1360 tao
2790 2098 jones
                out.println("<?xml version=\"1.0\"?>");
2791
                out.println("<error>");
2792
                out.println("Permission denied for " + action);
2793
                out.println("</error>");
2794
            }
2795
        } else {
2796
            /*
2797
             * try { out = response.getWriter(); } catch (IOException ioe2) {
2798
             * System.err.println("Fatal Error: couldn't get response output
2799
             * stream.");
2800
             */
2801
            out.println("<?xml version=\"1.0\"?>");
2802
            out.println("<error>");
2803
            out.println(
2804
                    "Error: action not registered.  Please report this error.");
2805
            out.println("</error>");
2806
        }
2807
        out.close();
2808 798 jones
    }
2809
2810 2098 jones
    /**
2811
     * Handle the upload action by saving the attached file to disk and
2812
     * registering it in the Metacat db
2813
     */
2814
    private void handleUploadAction(HttpServletRequest request,
2815
            PrintWriter out, Hashtable params, Hashtable fileList,
2816
            String username, String[] groupnames)
2817 1041 tao
    {
2818 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2819 2098 jones
        //PrintWriter out = null;
2820
        //Connection conn = null;
2821
        String action = null;
2822
        String docid = null;
2823 798 jones
2824 2098 jones
        /*
2825
         * response.setContentType("text/xml"); try { out =
2826
         * response.getWriter(); } catch (IOException ioe2) {
2827
         * System.err.println("Fatal Error: couldn't get response output
2828
         * stream.");
2829
         */
2830 798 jones
2831 2098 jones
        if (params.containsKey("docid")) {
2832
            docid = (String) params.get("docid");
2833
        }
2834 798 jones
2835 2098 jones
        // Make sure we have a docid and datafile
2836
        if (docid != null && fileList.containsKey("datafile")) {
2837 2753 jones
            logMetacat.info("Uploading data docid: " + docid);
2838 2098 jones
            // Get a reference to the file part of the form
2839
            FilePart filePart = (FilePart) fileList.get("datafile");
2840
            String fileName = filePart.getFileName();
2841 2753 jones
            logMetacat.info("Uploading filename: " + fileName);
2842 2098 jones
            // Check if the right file existed in the uploaded data
2843
            if (fileName != null) {
2844 1360 tao
2845 2098 jones
                try {
2846 2663 sgarg
                    //logMetacat.info("Upload datafile " + docid
2847 2098 jones
                    // +"...", 10);
2848
                    //If document get lock data file grant
2849
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2850
                        // Save the data file to disk using "docid" as the name
2851 2752 jones
                        String datafilepath = MetaCatUtil.getOption("datafilepath");
2852
                        File dataDirectory = new File(datafilepath);
2853 2098 jones
                        dataDirectory.mkdirs();
2854 2749 tao
                        File newFile = null;
2855
                        long size = 0;
2856
                        try
2857
                        {
2858
                          newFile = new File(dataDirectory, docid);
2859
                          size = filePart.writeTo(newFile);
2860
2861
//                        register the file in the database (which generates
2862
                          // an exception
2863
                          //if the docid is not acceptable or other untoward
2864
                          // things happen
2865
                          DocumentImpl.registerDocument(fileName, "BIN", docid,
2866
                                username, groupnames);
2867
                        }
2868
                        catch (Exception ee)
2869
                        {
2870
                           //detelte the file to create
2871
                            newFile.delete();
2872
                            throw ee;
2873
                        }
2874 1360 tao
2875 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
2876 2102 jones
                                username, docid, "upload");
2877 2098 jones
                        // Force replication this data file
2878
                        // To data file, "insert" and update is same
2879
                        // The fourth parameter is null. Because it is
2880
                        // notification server
2881
                        // and this method is in MetaCatServerlet. It is
2882
                        // original command,
2883
                        // not get force replication info from another metacat
2884
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2885
                                docid, "insert", false, null);
2886 1360 tao
2887 2098 jones
                        // set content type and other response header fields
2888
                        // first
2889
                        out.println("<?xml version=\"1.0\"?>");
2890
                        out.println("<success>");
2891
                        out.println("<docid>" + docid + "</docid>");
2892
                        out.println("<size>" + size + "</size>");
2893
                        out.println("</success>");
2894
                    }
2895
2896
                } catch (Exception e) {
2897 2749 tao
2898 2098 jones
                    out.println("<?xml version=\"1.0\"?>");
2899
                    out.println("<error>");
2900
                    out.println(e.getMessage());
2901
                    out.println("</error>");
2902
                }
2903
            } else {
2904
                // the field did not contain a file
2905
                out.println("<?xml version=\"1.0\"?>");
2906
                out.println("<error>");
2907
                out.println("The uploaded data did not contain a valid file.");
2908
                out.println("</error>");
2909
            }
2910
        } else {
2911
            // Error bcse docid missing or file missing
2912
            out.println("<?xml version=\"1.0\"?>");
2913
            out.println("<error>");
2914
            out.println("The uploaded data did not contain a valid docid "
2915
                    + "or valid file.");
2916
            out.println("</error>");
2917 798 jones
        }
2918 2098 jones
    }
2919 1360 tao
2920 2098 jones
    /*
2921
     * A method to handle set access action
2922
     */
2923
    private void handleSetAccessAction(PrintWriter out, Hashtable params,
2924
            String username)
2925 1041 tao
    {
2926 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2927 2098 jones
        String[] docList = null;
2928
        String[] principalList = null;
2929
        String[] permissionList = null;
2930
        String[] permTypeList = null;
2931
        String[] permOrderList = null;
2932
        String permission = null;
2933
        String permType = null;
2934
        String permOrder = null;
2935
        Vector errorList = new Vector();
2936
        String error = null;
2937
        Vector successList = new Vector();
2938
        String success = null;
2939 1716 berkley
2940 2098 jones
        // Get parameters
2941
        if (params.containsKey("docid")) {
2942
            docList = (String[]) params.get("docid");
2943
        }
2944
        if (params.containsKey("principal")) {
2945
            principalList = (String[]) params.get("principal");
2946
        }
2947
        if (params.containsKey("permission")) {
2948
            permissionList = (String[]) params.get("permission");
2949 1716 berkley
2950 2098 jones
        }
2951
        if (params.containsKey("permType")) {
2952
            permTypeList = (String[]) params.get("permType");
2953 1716 berkley
2954 2098 jones
        }
2955
        if (params.containsKey("permOrder")) {
2956
            permOrderList = (String[]) params.get("permOrder");
2957 1716 berkley
2958 2098 jones
        }
2959 1716 berkley
2960 2098 jones
        // Make sure the parameter is not null
2961
        if (docList == null || principalList == null || permTypeList == null
2962
                || permissionList == null) {
2963
            error = "Please check your parameter list, it should look like: "
2964
                    + "?action=setaccess&docid=pipeline.1.1&principal=public"
2965
                    + "&permission=read&permType=allow&permOrder=allowFirst";
2966
            errorList.addElement(error);
2967
            outputResponse(successList, errorList, out);
2968
            return;
2969
        }
2970 1716 berkley
2971 2098 jones
        // Only select first element for permission, type and order
2972
        permission = permissionList[0];
2973
        permType = permTypeList[0];
2974
        if (permOrderList != null) {
2975
            permOrder = permOrderList[0];
2976
        }
2977 1716 berkley
2978 2098 jones
        // Get package doctype set
2979
        Vector packageSet = MetaCatUtil.getOptionList(MetaCatUtil
2980
                .getOption("packagedoctypeset"));
2981
        //debug
2982
        if (packageSet != null) {
2983
            for (int i = 0; i < packageSet.size(); i++) {
2984 2753 jones
                logMetacat.debug("doctype in package set: "
2985 2663 sgarg
                        + (String) packageSet.elementAt(i));
2986 2098 jones
            }
2987
        }
2988 1716 berkley
2989 2098 jones
        // handle every accessionNumber
2990
        for (int i = 0; i < docList.length; i++) {
2991
            String accessionNumber = docList[i];
2992
            String owner = null;
2993
            String publicId = null;
2994
            // Get document owner and public id
2995
            try {
2996
                owner = getFieldValueForDoc(accessionNumber, "user_owner");
2997
                publicId = getFieldValueForDoc(accessionNumber, "doctype");
2998
            } catch (Exception e) {
2999 2663 sgarg
                logMetacat.error("Error in handleSetAccessAction: "
3000
                        + e.getMessage());
3001 2098 jones
                error = "Error in set access control for document - "
3002
                        + accessionNumber + e.getMessage();
3003
                errorList.addElement(error);
3004
                continue;
3005
            }
3006
            //check if user is the owner. Only owner can do owner
3007
            if (username == null || owner == null || !username.equals(owner)) {
3008
                error = "User - " + username
3009
                        + " does not have permission to set "
3010
                        + "access control for docid - " + accessionNumber;
3011
                errorList.addElement(error);
3012
                continue;
3013
            }
3014 1716 berkley
3015 2098 jones
            // If docid publicid is BIN data file or other beta4, 6 package
3016
            // document
3017
            // we could not do set access control. Because we don't want
3018
            // inconsistent
3019
            // to its access docuemnt
3020
            if (publicId != null && packageSet != null
3021
                    && packageSet.contains(publicId)) {
3022
                error = "Could not set access control to document "
3023
                        + accessionNumber
3024
                        + "because it is in a pakcage and it has a access file for it";
3025
                errorList.addElement(error);
3026
                continue;
3027
            }
3028 1716 berkley
3029 2098 jones
            // for every principle
3030
            for (int j = 0; j < principalList.length; j++) {
3031
                String principal = principalList[j];
3032
                try {
3033
                    //insert permission
3034
                    AccessControlForSingleFile accessControl = new AccessControlForSingleFile(
3035
                            accessionNumber, principal, permission, permType,
3036
                            permOrder);
3037
                    accessControl.insertPermissions();
3038
                    success = "Set access control to document "
3039
                            + accessionNumber + " successfully";
3040
                    successList.addElement(success);
3041
                } catch (Exception ee) {
3042 2663 sgarg
                    logMetacat.error(
3043 2098 jones
                            "Erorr in handleSetAccessAction2: "
3044 2663 sgarg
                                    + ee.getMessage());
3045 2098 jones
                    error = "Faild to set access control for document "
3046
                            + accessionNumber + " because " + ee.getMessage();
3047
                    errorList.addElement(error);
3048
                    continue;
3049
                }
3050
            }
3051 1369 tao
        }
3052 2098 jones
        outputResponse(successList, errorList, out);
3053
    }
3054 1716 berkley
3055 2098 jones
    /*
3056
     * A method try to determin a docid's public id, if couldn't find null will
3057
     * be returned.
3058
     */
3059
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
3060
            throws Exception
3061 1369 tao
    {
3062 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3063 2098 jones
        if (accessionNumber == null || accessionNumber.equals("")
3064
                || fieldName == null || fieldName.equals("")) { throw new Exception(
3065
                "Docid or field name was not specified"); }
3066 1716 berkley
3067 2098 jones
        PreparedStatement pstmt = null;
3068
        ResultSet rs = null;
3069
        String fieldValue = null;
3070
        String docId = null;
3071
        DBConnection conn = null;
3072
        int serialNumber = -1;
3073 1716 berkley
3074 2098 jones
        // get rid of revision if access number has
3075
        docId = MetaCatUtil.getDocIdFromString(accessionNumber);
3076
        try {
3077
            //check out DBConnection
3078
            conn = DBConnectionPool
3079
                    .getDBConnection("MetaCatServlet.getPublicIdForDoc");
3080
            serialNumber = conn.getCheckOutSerialNumber();
3081
            pstmt = conn.prepareStatement("SELECT " + fieldName
3082
                    + " FROM xml_documents " + "WHERE docid = ? ");
3083 1716 berkley
3084 2098 jones
            pstmt.setString(1, docId);
3085
            pstmt.execute();
3086
            rs = pstmt.getResultSet();
3087
            boolean hasRow = rs.next();
3088
            int perm = 0;
3089
            if (hasRow) {
3090
                fieldValue = rs.getString(1);
3091
            } else {
3092
                throw new Exception("Could not find document: "
3093
                        + accessionNumber);
3094
            }
3095
        } catch (Exception e) {
3096 2663 sgarg
            logMetacat.error(
3097 2098 jones
                    "Exception in MetacatServlet.getPublicIdForDoc: "
3098 2663 sgarg
                            + e.getMessage());
3099 2098 jones
            throw e;
3100
        } finally {
3101
            try {
3102
                rs.close();
3103
                pstmt.close();
3104 1716 berkley
3105 2098 jones
            } finally {
3106
                DBConnectionPool.returnDBConnection(conn, serialNumber);
3107
            }
3108
        }
3109
        return fieldValue;
3110 1369 tao
    }
3111 1716 berkley
3112 2098 jones
    /*
3113 2312 jones
     * Get the list of documents from the database and return the list in an
3114
     * Vector of identifiers.
3115
     *
3116
     * @ returns the array of identifiers
3117
     */
3118
    private Vector getDocumentList() throws SQLException
3119
    {
3120 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3121 2312 jones
        Vector docList = new Vector();
3122
        PreparedStatement pstmt = null;
3123
        ResultSet rs = null;
3124
        DBConnection conn = null;
3125
        int serialNumber = -1;
3126
3127
        try {
3128
            //check out DBConnection
3129
            conn = DBConnectionPool
3130
                    .getDBConnection("MetaCatServlet.getDocumentList");
3131
            serialNumber = conn.getCheckOutSerialNumber();
3132
            pstmt = conn.prepareStatement("SELECT docid, rev"
3133
                    + " FROM xml_documents ");
3134
            pstmt.execute();
3135
            rs = pstmt.getResultSet();
3136
            while (rs.next()) {
3137
                String docid = rs.getString(1);
3138
                String rev = rs.getString(2);
3139
                docList.add(docid + "." + rev);
3140
            }
3141
        } catch (SQLException e) {
3142 2663 sgarg
            logMetacat.error(
3143 2312 jones
                    "Exception in MetacatServlet.getDocumentList: "
3144 2663 sgarg
                            + e.getMessage());
3145 2312 jones
            throw e;
3146
        } finally {
3147
            try {
3148
                rs.close();
3149
                pstmt.close();
3150
3151
            } catch (SQLException se) {
3152 2663 sgarg
                logMetacat.error(
3153 2312 jones
                    "Exception in MetacatServlet.getDocumentList: "
3154 2663 sgarg
                            + se.getMessage());
3155 2312 jones
                throw se;
3156
            } finally {
3157
                DBConnectionPool.returnDBConnection(conn, serialNumber);
3158
            }
3159
        }
3160
        return docList;
3161
    }
3162
3163
    /*
3164 2098 jones
     * A method to output setAccess action result
3165
     */
3166
    private void outputResponse(Vector successList, Vector errorList,
3167
            PrintWriter out)
3168 1369 tao
    {
3169 2098 jones
        boolean error = false;
3170
        boolean success = false;
3171
        // Output prolog
3172
        out.println(PROLOG);
3173
        // output success message
3174
        if (successList != null) {
3175
            for (int i = 0; i < successList.size(); i++) {
3176
                out.println(SUCCESS);
3177
                out.println((String) successList.elementAt(i));
3178
                out.println(SUCCESSCLOSE);
3179
                success = true;
3180
            }
3181
        }
3182
        // output error message
3183
        if (errorList != null) {
3184
            for (int i = 0; i < errorList.size(); i++) {
3185
                out.println(ERROR);
3186
                out.println((String) errorList.elementAt(i));
3187
                out.println(ERRORCLOSE);
3188
                error = true;
3189
            }
3190
        }
3191 1716 berkley
3192 2098 jones
        // if no error and no success info, send a error that nothing happened
3193
        if (!error && !success) {
3194
            out.println(ERROR);
3195
            out.println("Nothing happend for setaccess action");
3196
            out.println(ERRORCLOSE);
3197
        }
3198 1369 tao
    }
3199 2582 tao
3200
    /**
3201
     * Method to get session table which store the session info
3202
     * @return
3203
     */
3204
    public static Hashtable getSessionHash()
3205
    {
3206
        return sessionHash;
3207
    }
3208 2648 tao
3209
    /*
3210
     * If the given docid only have one seperter, we need
3211
     * append rev for it. The rev come from xml_documents
3212
     */
3213
    private static String appendRev(String docid) throws Exception
3214
    {
3215 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3216 2648 tao
        String newAccNum = null;
3217
        String separator = MetaCatUtil.getOption("accNumSeparator");
3218
        int firstIndex = docid.indexOf(separator);
3219
        int lastIndex = docid.lastIndexOf(separator);
3220
        if (firstIndex == lastIndex)
3221
        {
3222
3223
           //only one seperater
3224
            int rev = DBUtil.getLatestRevisionInDocumentTable(docid);
3225
            if (rev == -1)
3226
            {
3227 2776 tao
                throw new Exception("the requested docid '"
3228
                        + docid+ "' does not exist");
3229 2648 tao
            }
3230
            else
3231
            {
3232
                newAccNum = docid+ separator+ rev;
3233
            }
3234
        }
3235
        else
3236
        {
3237
            // in other suituation we don't change the docid
3238
            newAccNum = docid;
3239
        }
3240 2776 tao
        //logMetacat.debug("The docid will be read is "+newAccNum);
3241 2648 tao
        return newAccNum;
3242 2912 harris
  }
3243 46 jones
}