Project

General

Profile

1 51 jones
/**
2 203 jones
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6 3028 perry
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley, Matthew Perry
7 348 jones
 *    Release: @release@
8 154 jones
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 51 jones
 */
27
28
package edu.ucsb.nceas.metacat;
29
30 2098 jones
import java.io.BufferedInputStream;
31 733 bojilova
import java.io.File;
32 2098 jones
import java.io.FileInputStream;
33
import java.io.IOException;
34 46 jones
import java.io.PrintWriter;
35 50 jones
import java.io.StringReader;
36 2098 jones
import java.net.MalformedURLException;
37
import java.net.URL;
38
import java.sql.PreparedStatement;
39
import java.sql.ResultSet;
40
import java.sql.SQLException;
41 2113 jones
import java.sql.Timestamp;
42
import java.text.ParseException;
43
import java.text.SimpleDateFormat;
44 46 jones
import java.util.Enumeration;
45 2893 sgarg
import java.util.HashMap;
46 46 jones
import java.util.Hashtable;
47 2312 jones
import java.util.Iterator;
48 2896 sgarg
import java.util.Properties;
49 2752 jones
import java.util.Timer;
50 1369 tao
import java.util.Vector;
51 2098 jones
import java.util.zip.ZipEntry;
52
import java.util.zip.ZipOutputStream;
53 46 jones
54
import javax.servlet.ServletConfig;
55
import javax.servlet.ServletContext;
56
import javax.servlet.ServletException;
57 2098 jones
import javax.servlet.ServletOutputStream;
58 46 jones
import javax.servlet.http.HttpServlet;
59
import javax.servlet.http.HttpServletRequest;
60
import javax.servlet.http.HttpServletResponse;
61 210 bojilova
import javax.servlet.http.HttpSession;
62 46 jones
63 2752 jones
import org.apache.log4j.Logger;
64
import org.apache.log4j.PropertyConfigurator;
65 2098 jones
import org.ecoinformatics.eml.EMLParser;
66 204 jones
67 2098 jones
import com.oreilly.servlet.multipart.FilePart;
68
import com.oreilly.servlet.multipart.MultipartParser;
69
import com.oreilly.servlet.multipart.ParamPart;
70
import com.oreilly.servlet.multipart.Part;
71
72 2570 jones
import edu.ucsb.nceas.utilities.Options;
73 3034 perry
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
74 2570 jones
75 46 jones
/**
76
 * A metadata catalog server implemented as a Java Servlet
77 2169 sgarg
 *
78 205 jones
 * <p>
79 2098 jones
 * Valid parameters are: <br>
80
 * action=query -- query the values of all elements and attributes and return a
81
 * result set of nodes <br>
82
 * action=squery -- structured query (see pathquery.dtd) <br>
83
 * action= -- export a zip format for data packadge <br>
84
 * action=read -- read any metadata/data file from Metacat and from Internet
85
 * <br>
86
 * action=insert -- insert an XML document into the database store <br>
87
 * action=update -- update an XML document that is in the database store <br>
88
 * action=delete -- delete an XML document from the database store <br>
89
 * action=validate -- vallidate the xml contained in valtext <br>
90
 * doctype -- document type list returned by the query (publicID) <br>
91
 * qformat=xml -- display resultset from query in XML <br>
92
 * qformat=html -- display resultset from query in HTML <br>
93
 * qformat=zip -- zip resultset from query <br>
94
 * docid=34 -- display the document with the document ID number 34 <br>
95
 * doctext -- XML text of the document to load into the database <br>
96
 * acltext -- XML access text for a document to load into the database <br>
97
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog <br>
98
 * query -- actual query text (to go with 'action=query' or 'action=squery')
99
 * <br>
100
 * valtext -- XML text to be validated <br>
101
 * action=getaccesscontrol -- retrieve acl info for Metacat document <br>
102
 * action=getdoctypes -- retrieve all doctypes (publicID) <br>
103
 * action=getdtdschema -- retrieve a DTD or Schema file <br>
104
 * action=getdataguide -- retrieve a Data Guide <br>
105
 * action=getprincipals -- retrieve a list of principals in XML <br>
106
 * datadoc -- data document name (id) <br>
107 2113 jones
 * action=getlog -- get a report of events that have occurred in the system<br>
108
 * ipAddress --  filter on one or more IP addresses<br>
109
 * principal -- filter on one or more principals (LDAP DN syntax)<br>
110
 * docid -- filter on one or more document identifiers (with revision)<br>
111
 * event -- filter on event type (e.g., read, insert, update, delete)<br>
112
 * start -- filter out events before the start date-time<br>
113
 * end -- filter out events before the end date-time<br>
114 2098 jones
 * <p>
115
 * The particular combination of parameters that are valid for each particular
116
 * action value is quite specific. This documentation will be reorganized to
117
 * reflect this information.
118 46 jones
 */
119 2098 jones
public class MetaCatServlet extends HttpServlet
120
{
121 2582 tao
    private static Hashtable sessionHash = new Hashtable();
122 2752 jones
    private Timer timer = null;
123
124
    // Constants -- these should be final in a servlet
125 2098 jones
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
126
    private static final String SUCCESS = "<success>";
127
    private static final String SUCCESSCLOSE = "</success>";
128
    private static final String ERROR = "<error>";
129
    private static final String ERRORCLOSE = "</error>";
130
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
131
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
132 2711 sgarg
    public static final String NAMESPACEKEYWORD = "xmlns";
133 2098 jones
    public static final String EML2KEYWORD = ":eml";
134
    public static final String XMLFORMAT = "xml";
135
    private static final String CONFIG_DIR = "WEB-INF";
136 2752 jones
    private static final String CONFIG_NAME = "metacat.properties";
137 2663 sgarg
138 2098 jones
    /**
139
     * Initialize the servlet by creating appropriate database connections
140
     */
141
    public void init(ServletConfig config) throws ServletException
142
    {
143
        try {
144
            super.init(config);
145 2752 jones
            ServletContext context = config.getServletContext();
146 1360 tao
147 2098 jones
            // Initialize the properties file for our options
148
            String dirPath = context.getRealPath(CONFIG_DIR);
149
            File propertyFile = new File(dirPath, CONFIG_NAME);
150 2594 sgarg
151 2663 sgarg
            String LOG_CONFIG_NAME = dirPath + "/log4j.properties";
152
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
153
154 2098 jones
            Options options = null;
155
            try {
156
                options = Options.initialize(propertyFile);
157 2663 sgarg
                MetaCatUtil.printMessage("Options configured: "
158
                        + options.getOption("configured"));
159 2098 jones
            } catch (IOException ioe) {
160 2753 jones
                Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
161 2663 sgarg
                logMetacat.error("Error in loading options: "
162
                        + ioe.getMessage());
163 2098 jones
            }
164 1716 berkley
165 2752 jones
            MetaCatUtil util = new MetaCatUtil();
166 2893 sgarg
167 2752 jones
            //initialize DBConnection pool
168
            DBConnectionPool connPool = DBConnectionPool.getInstance();
169
170 2521 sgarg
            // Index the paths specified in the metacat.properties
171
            checkIndexPaths();
172
173 2729 sgarg
            // initiate the indexing Queue
174
            IndexingQueue.getInstance();
175
176
            // start the IndexingThread if indexingTimerTaskTime more than 0.
177
            // It will index all the documents not yet indexed in the database
178
            int indexingTimerTaskTime = Integer.parseInt(MetaCatUtil.getOption("indexingTimerTaskTime"));
179
            if(indexingTimerTaskTime > 0){
180
            	timer = new Timer();
181
            	timer.schedule(new IndexingTimerTask(), 0, indexingTimerTaskTime);
182
            }
183
184 2893 sgarg
            // read the config files:
185
            Vector skins = MetaCatUtil.getOptionList(MetaCatUtil.getOption("skinconfigfiles"));
186
            String skinName, skinDirPath = null;
187
            File skinPropertyFile = null;
188
189
            for (int i = 0; i < skins.size(); i++) {
190
            	skinName = (String) skins.elementAt(i);
191
                skinDirPath = context.getRealPath(CONFIG_DIR + "/skin.configs/" + skinName);
192 2897 sgarg
                skinPropertyFile = new File(skinDirPath, skinName + ".properties");
193 2896 sgarg
                Properties skinOption = null;
194 2893 sgarg
                try	{
195 2896 sgarg
                	skinOption = new Properties();
196
                    FileInputStream fis = new FileInputStream(skinPropertyFile);
197
                    skinOption.load(fis);
198
                    fis.close();
199 2893 sgarg
                } catch (IOException ioe) {
200
                    Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
201
                    logMetacat.error("Error in loading options for skin " + "skinName" +" : "
202
                            + ioe.getMessage());
203 2896 sgarg
                }
204 2893 sgarg
                MetaCatUtil.skinconfigs.put(skinName, skinOption);
205
            }
206 2946 sgarg
207 3034 perry
            /*
208
             *  If spatial option is turned on and set to regenerate the
209
             *  spatial cache on restart, trigger the harvester
210
             */
211
            if ( MetaCatUtil.getOption("runSpatialOption").equals("true") &&
212
                 MetaCatUtil.getOption("regenerateCacheOnRestart").equals("true") ) {
213 2946 sgarg
214 3034 perry
                // Begin timer
215
                long before = System.currentTimeMillis();
216
217
                // regenerate the entire spatial cache
218
                // may be expensive with many documents
219
                SpatialHarvester sh = new SpatialHarvester();
220
                sh.regenerate();
221
                sh.destroy();
222
223
                // End timer
224
                long after = System.currentTimeMillis();
225
                MetaCatUtil.printMessage(" ------ Spatial Harvester Time  " + (after - before) + "ms");
226
227
	    } else {
228
                MetaCatUtil.printMessage(" \n **** Spatial cache is not set to regenerate on restart");
229
            }
230 2913 harris
231
232 2663 sgarg
            MetaCatUtil.printMessage("Metacat (" + Version.getVersion()
233 2521 sgarg
                               + ") initialized.");
234
235 2098 jones
        } catch (ServletException ex) {
236
            throw ex;
237
        } catch (SQLException e) {
238 2753 jones
            Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
239 2663 sgarg
            logMetacat.error("Error in MetacatServlet.init: "
240
                    + e.getMessage());
241 1221 tao
        }
242 2098 jones
    }
243 1360 tao
244 2570 jones
    /**
245
     * Close all db connections from the pool
246
     */
247
    public void destroy()
248
    {
249
        // Close all db connection
250
        System.out.println("Destroying MetacatServlet");
251 2759 sgarg
        timer.cancel();
252 2901 sgarg
        IndexingQueue.getInstance().setMetacatRunning(false);
253 2570 jones
        DBConnectionPool.release();
254
    }
255 2521 sgarg
256 2570 jones
    /** Handle "GET" method requests from HTTP clients */
257
    public void doGet(HttpServletRequest request, HttpServletResponse response)
258
            throws ServletException, IOException
259
    {
260
261
        // Process the data and send back the response
262
        handleGetOrPost(request, response);
263
    }
264
265
    /** Handle "POST" method requests from HTTP clients */
266
    public void doPost(HttpServletRequest request, HttpServletResponse response)
267
            throws ServletException, IOException
268
    {
269
270
        // Process the data and send back the response
271
        handleGetOrPost(request, response);
272
    }
273
274 2098 jones
    /**
275 2521 sgarg
     * Index the paths specified in the metacat.properties
276
     */
277 2753 jones
    private void checkIndexPaths() {
278
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
279 2521 sgarg
        MetaCatUtil.pathsForIndexing
280 2758 sgarg
            = MetaCatUtil.getOptionList(MetaCatUtil.getOption("indexPaths"));
281 2570 jones
282 2521 sgarg
        if (MetaCatUtil.pathsForIndexing != null) {
283 2570 jones
284 2663 sgarg
            MetaCatUtil.printMessage("Indexing paths specified in metacat.properties....");
285 2570 jones
286 2521 sgarg
            DBConnection conn = null;
287
            int serialNumber = -1;
288
            PreparedStatement pstmt = null;
289
            PreparedStatement pstmt1 = null;
290
            ResultSet rs = null;
291 2570 jones
292 2521 sgarg
            for (int i = 0; i < MetaCatUtil.pathsForIndexing.size(); i++) {
293 2753 jones
                logMetacat.debug("Checking if '"
294 2521 sgarg
                           + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
295 2663 sgarg
                           + "' is indexed.... ");
296 2570 jones
297 2521 sgarg
                try {
298
                    //check out DBConnection
299
                    conn = DBConnectionPool.
300
                        getDBConnection("MetaCatServlet.checkIndexPaths");
301
                    serialNumber = conn.getCheckOutSerialNumber();
302 2570 jones
303 2521 sgarg
                    pstmt = conn.prepareStatement(
304
                        "SELECT * FROM xml_path_index " + "WHERE path = ?");
305
                    pstmt.setString(1, (String) MetaCatUtil.pathsForIndexing
306
                                    .elementAt(i));
307 2570 jones
308 2521 sgarg
                    pstmt.execute();
309
                    rs = pstmt.getResultSet();
310 2570 jones
311 2521 sgarg
                    if (!rs.next()) {
312 2753 jones
                        logMetacat.debug(".....not indexed yet.");
313 2521 sgarg
                        rs.close();
314
                        pstmt.close();
315
                        conn.increaseUsageCount(1);
316 2570 jones
317 2663 sgarg
                        logMetacat.debug(
318 2521 sgarg
                              "Inserting following path in xml_path_index: "
319
                              + (String)MetaCatUtil.pathsForIndexing
320 2663 sgarg
                                                   .elementAt(i));
321 2836 sgarg
   			if(((String)MetaCatUtil.pathsForIndexing.elementAt(i)).indexOf("@")<0){
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.parentnodeid=i.nodeid and"
326
                              		+ " n.nodetype LIKE 'TEXT' order by n.parentnodeid");
327
			} else {
328
                        	pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
329
                              		+ "n.nodedata, n.nodedatanumerical, n.parentnodeid"
330
                              		+ " FROM xml_nodes n, xml_index i WHERE"
331
                              		+ " i.path = ? and n.nodeid=i.nodeid and"
332
                              		+ " n.nodetype LIKE 'ATTRIBUTE' order by n.parentnodeid");
333
			}
334 2521 sgarg
                        pstmt.setString(1, (String) MetaCatUtil.
335
                                        pathsForIndexing.elementAt(i));
336
                        pstmt.execute();
337
                        rs = pstmt.getResultSet();
338 2570 jones
339 2521 sgarg
                        int count = 0;
340 2663 sgarg
                        logMetacat.debug(
341 2521 sgarg
                                       "Executed the select statement for: "
342
                                       + (String) MetaCatUtil.pathsForIndexing
343 2663 sgarg
                                         .elementAt(i));
344 2570 jones
345 2521 sgarg
                        try {
346
                            while (rs.next()) {
347 2570 jones
348 2521 sgarg
                                String docid = rs.getString(1);
349
                                String nodedata = rs.getString(2);
350
                                float nodedatanumerical = rs.getFloat(3);
351
                                int parentnodeid = rs.getInt(4);
352 2570 jones
353 2521 sgarg
                                if (!nodedata.trim().equals("")) {
354
                                    pstmt1 = conn.prepareStatement(
355
                                        "INSERT INTO xml_path_index"
356
                                        + " (docid, path, nodedata, "
357
                                        + "nodedatanumerical, parentnodeid)"
358
                                        + " VALUES (?, ?, ?, ?, ?)");
359 2570 jones
360 2521 sgarg
                                    pstmt1.setString(1, docid);
361
                                    pstmt1.setString(2, (String) MetaCatUtil.
362
                                                pathsForIndexing.elementAt(i));
363
                                    pstmt1.setString(3, nodedata);
364
                                    pstmt1.setFloat(4, nodedatanumerical);
365 2701 sgarg
                                    pstmt1.setInt(5, parentnodeid);
366 2570 jones
367 2521 sgarg
                                    pstmt1.execute();
368
                                    pstmt1.close();
369 2570 jones
370 2521 sgarg
                                    count++;
371 2570 jones
372 2521 sgarg
                                }
373
                            }
374
                        }
375
                        catch (Exception e) {
376
                            System.out.println("Exception:" + e.getMessage());
377
                            e.printStackTrace();
378
                        }
379 2570 jones
380 2521 sgarg
                        rs.close();
381
                        pstmt.close();
382
                        conn.increaseUsageCount(1);
383 2570 jones
384 2753 jones
                        logMetacat.info("Indexed " + count
385 2521 sgarg
                                + " records from xml_nodes for '"
386
                                + (String) MetaCatUtil.pathsForIndexing.elementAt(i)
387 2663 sgarg
                                + "'");
388 2570 jones
389 2521 sgarg
                    } else {
390 2753 jones
                    	logMetacat.debug(".....already indexed.");
391 2521 sgarg
                    }
392 2570 jones
393 2521 sgarg
                    rs.close();
394
                    pstmt.close();
395
                    conn.increaseUsageCount(1);
396 2570 jones
397 2521 sgarg
                } catch (Exception e) {
398 2663 sgarg
                    logMetacat.error("Error in MetaCatServlet.checkIndexPaths: "
399
                                             + e.getMessage());
400 2521 sgarg
                }finally {
401
                    //check in DBonnection
402
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
403
                }
404 2570 jones
405
406 2521 sgarg
            }
407 2570 jones
408 2663 sgarg
            MetaCatUtil.printMessage("Path Indexing Completed");
409 2521 sgarg
        }
410 2682 sgarg
    }
411 1723 berkley
412 2098 jones
    /**
413
     * Control servlet response depending on the action parameter specified
414
     */
415
    private void handleGetOrPost(HttpServletRequest request,
416
            HttpServletResponse response) throws ServletException, IOException
417 2045 tao
    {
418 2752 jones
        MetaCatUtil util = new MetaCatUtil();
419 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
420
421 2098 jones
        /*
422 2753 jones
         * logMetacat.debug("Connection pool size: "
423 2098 jones
         * +connPool.getSizeOfDBConnectionPool(),10);
424 2753 jones
         * logMetacat.debug("Free DBConnection number: "
425 2098 jones
         */
426
        //If all DBConnection in the pool are free and DBConnection pool
427
        //size is greater than initial value, shrink the connection pool
428
        //size to initial value
429
        DBConnectionPool.shrinkDBConnectionPoolSize();
430 1360 tao
431 2098 jones
        //Debug message to print out the method which have a busy DBConnection
432 2752 jones
        try {
433
            DBConnectionPool pool = DBConnectionPool.getInstance();
434
            pool.printMethodNameHavingBusyDBConnection();
435
        } catch (SQLException e) {
436
            logMetacat.error("Error in MetacatServlet.handleGetOrPost: "
437
                    + e.getMessage());
438
            e.printStackTrace();
439
        }
440 1360 tao
441 2098 jones
        String ctype = request.getContentType();
442
        if (ctype != null && ctype.startsWith("multipart/form-data")) {
443
            handleMultipartForm(request, response);
444
        } else {
445 1360 tao
446 2098 jones
            String name = null;
447
            String[] value = null;
448
            String[] docid = new String[3];
449
            Hashtable params = new Hashtable();
450
            Enumeration paramlist = request.getParameterNames();
451 1360 tao
452 2098 jones
            while (paramlist.hasMoreElements()) {
453 1360 tao
454 2098 jones
                name = (String) paramlist.nextElement();
455
                value = request.getParameterValues(name);
456 509 bojilova
457 2098 jones
                // Decode the docid and mouse click information
458
                if (name.endsWith(".y")) {
459
                    docid[0] = name.substring(0, name.length() - 2);
460
                    params.put("docid", docid);
461
                    name = "ypos";
462
                }
463
                if (name.endsWith(".x")) {
464
                    name = "xpos";
465
                }
466 509 bojilova
467 2098 jones
                params.put(name, value);
468
            }
469 509 bojilova
470 2098 jones
            //handle param is emptpy
471
            if (params.isEmpty() || params == null) { return; }
472 509 bojilova
473 2098 jones
            //if the user clicked on the input images, decode which image
474
            //was clicked then set the action.
475 2252 sgarg
            if(params.get("action") == null){
476
                PrintWriter out = response.getWriter();
477
                response.setContentType("text/xml");
478
                out.println("<?xml version=\"1.0\"?>");
479
                out.println("<error>");
480
                out.println("Action not specified");
481
                out.println("</error>");
482
                out.close();
483
                return;
484
            }
485
486 2098 jones
            String action = ((String[]) params.get("action"))[0];
487 2753 jones
            logMetacat.info("Action is: " + action);
488 509 bojilova
489 2098 jones
            // This block handles session management for the servlet
490
            // by looking up the current session information for all actions
491
            // other than "login" and "logout"
492
            String username = null;
493
            String password = null;
494
            String[] groupnames = null;
495
            String sess_id = null;
496 2682 sgarg
            name = null;
497
498 2098 jones
            // handle login action
499
            if (action.equals("login")) {
500
                PrintWriter out = response.getWriter();
501
                handleLoginAction(out, params, request, response);
502
                out.close();
503 2912 harris
504 2098 jones
                // handle logout action
505 2919 harris
            }   else if (action.equals("logout")) {
506 2098 jones
                PrintWriter out = response.getWriter();
507
                handleLogoutAction(out, params, request, response);
508
                out.close();
509 1360 tao
510 2098 jones
                // handle shrink DBConnection request
511
            } else if (action.equals("shrink")) {
512
                PrintWriter out = response.getWriter();
513
                boolean success = false;
514
                //If all DBConnection in the pool are free and DBConnection
515
                // pool
516
                //size is greater than initial value, shrink the connection
517
                // pool
518
                //size to initial value
519
                success = DBConnectionPool.shrinkConnectionPoolSize();
520
                if (success) {
521
                    //if successfully shrink the pool size to initial value
522
                    out.println("DBConnection Pool shrunk successfully.");
523
                }//if
524
                else {
525
                    out.println("DBConnection pool not shrunk successfully.");
526
                }
527
                //close out put
528
                out.close();
529 1360 tao
530 2098 jones
                // aware of session expiration on every request
531
            } else {
532
                HttpSession sess = request.getSession(true);
533
                if (sess.isNew() && !params.containsKey("sessionid")) {
534
                    // session expired or has not been stored b/w user requests
535 2753 jones
                    logMetacat.info(
536 2663 sgarg
                            "The session is new or no sessionid is assigned. The user is public");
537 2098 jones
                    username = "public";
538
                    sess.setAttribute("username", username);
539
                } else {
540 2753 jones
                    logMetacat.info("The session is either old or "
541 2668 sgarg
                            + "has sessionid parameter");
542 2098 jones
                    try {
543
                        if (params.containsKey("sessionid")) {
544
                            sess_id = ((String[]) params.get("sessionid"))[0];
545 2663 sgarg
                            logMetacat.info("in has sessionid "
546
                                    + sess_id);
547 2098 jones
                            if (sessionHash.containsKey(sess_id)) {
548 2663 sgarg
                                logMetacat.info("find the id "
549
                                        + sess_id + " in hash table");
550 2098 jones
                                sess = (HttpSession) sessionHash.get(sess_id);
551
                            }
552
                        } else {
553
                            // we already store the session in login, so we
554
                            // don't need here
555
                            /*
556 2663 sgarg
                             * logMetacat.info("in no sessionid
557 2098 jones
                             * parameter ", 40); sess_id =
558
                             * (String)sess.getId();
559 2663 sgarg
                             * logMetacat.info("storing the session id "
560 2098 jones
                             * + sess_id + " which has username " +
561
                             * sess.getAttribute("username") + " into session
562
                             * hash in handleGetOrPost method", 35);
563
                             */
564
                        }
565
                    } catch (IllegalStateException ise) {
566 2663 sgarg
                        logMetacat.error(
567
                                "Error in handleGetOrPost: this shouldn't "
568 2098 jones
                                + "happen: the session should be valid: "
569
                                + ise.getMessage());
570
                    }
571 1360 tao
572 2098 jones
                    username = (String) sess.getAttribute("username");
573 2668 sgarg
                    logMetacat.info("The user name from session is: "
574 2663 sgarg
                            + username);
575 2098 jones
                    password = (String) sess.getAttribute("password");
576
                    groupnames = (String[]) sess.getAttribute("groupnames");
577 2682 sgarg
                    name = (String) sess.getAttribute("name");
578 2098 jones
                }
579 1360 tao
580 2098 jones
                //make user user username should be public
581
                if (username == null || (username.trim().equals(""))) {
582
                    username = "public";
583
                }
584 2753 jones
                logMetacat.info("The user is : " + username);
585 2098 jones
            }
586
            // Now that we know the session is valid, we can delegate the
587
            // request
588
            // to a particular action handler
589
            if (action.equals("query")) {
590
                PrintWriter out = response.getWriter();
591
                handleQuery(out, params, response, username, groupnames,
592
                        sess_id);
593
                out.close();
594
            } else if (action.equals("squery")) {
595
                PrintWriter out = response.getWriter();
596
                if (params.containsKey("query")) {
597
                    handleSQuery(out, params, response, username, groupnames,
598
                            sess_id);
599
                    out.close();
600
                } else {
601
                    out.println(
602
                            "Illegal action squery without \"query\" parameter");
603
                    out.close();
604
                }
605 2919 harris
            } else if ( action.trim().equals("spatial_query")) {
606
607 2970 sgarg
              logMetacat.debug("******************* SPATIAL QUERY ********************");
608 2919 harris
              PrintWriter out = response.getWriter();
609
              handleSpatialQuery(out, params, response, username, groupnames, sess_id);
610
              out.close();
611
612 2098 jones
            } else if (action.equals("export")) {
613 1298 tao
614 2169 sgarg
                handleExportAction(params, response, username,
615 2102 jones
                        groupnames, password);
616 2098 jones
            } else if (action.equals("read")) {
617 2102 jones
                handleReadAction(params, request, response, username, password,
618 2098 jones
                        groupnames);
619
            } else if (action.equals("readinlinedata")) {
620 2102 jones
                handleReadInlineDataAction(params, request, response, username,
621 2098 jones
                        password, groupnames);
622
            } else if (action.equals("insert") || action.equals("update")) {
623
                PrintWriter out = response.getWriter();
624
                if ((username != null) && !username.equals("public")) {
625 2102 jones
                    handleInsertOrUpdateAction(request, response,
626
                            out, params, username, groupnames);
627 2098 jones
                } else {
628 2252 sgarg
                    response.setContentType("text/xml");
629
                    out.println("<?xml version=\"1.0\"?>");
630
                    out.println("<error>");
631 2098 jones
                    out.println("Permission denied for user " + username + " "
632
                            + action);
633 2252 sgarg
                    out.println("</error>");
634 2098 jones
                }
635
                out.close();
636
            } else if (action.equals("delete")) {
637
                PrintWriter out = response.getWriter();
638
                if ((username != null) && !username.equals("public")) {
639 2102 jones
                    handleDeleteAction(out, params, request, response, username,
640 2098 jones
                            groupnames);
641
                } else {
642 2252 sgarg
                    response.setContentType("text/xml");
643
                    out.println("<?xml version=\"1.0\"?>");
644
                    out.println("<error>");
645 2098 jones
                    out.println("Permission denied for " + action);
646 2252 sgarg
                    out.println("</error>");
647 2098 jones
                }
648
                out.close();
649
            } else if (action.equals("validate")) {
650
                PrintWriter out = response.getWriter();
651
                handleValidateAction(out, params);
652
                out.close();
653
            } else if (action.equals("setaccess")) {
654
                PrintWriter out = response.getWriter();
655
                handleSetAccessAction(out, params, username);
656
                out.close();
657
            } else if (action.equals("getaccesscontrol")) {
658
                PrintWriter out = response.getWriter();
659
                handleGetAccessControlAction(out, params, response, username,
660
                        groupnames);
661
                out.close();
662
            } else if (action.equals("getprincipals")) {
663
                PrintWriter out = response.getWriter();
664
                handleGetPrincipalsAction(out, username, password);
665
                out.close();
666
            } else if (action.equals("getdoctypes")) {
667
                PrintWriter out = response.getWriter();
668
                handleGetDoctypesAction(out, params, response);
669
                out.close();
670
            } else if (action.equals("getdtdschema")) {
671
                PrintWriter out = response.getWriter();
672
                handleGetDTDSchemaAction(out, params, response);
673
                out.close();
674
            } else if (action.equals("getlastdocid")) {
675
                PrintWriter out = response.getWriter();
676
                handleGetMaxDocidAction(out, params, response);
677
                out.close();
678
            } else if (action.equals("getrevisionanddoctype")) {
679
                PrintWriter out = response.getWriter();
680
                handleGetRevisionAndDocTypeAction(out, params);
681
                out.close();
682
            } else if (action.equals("getversion")) {
683
                response.setContentType("text/xml");
684
                PrintWriter out = response.getWriter();
685
                out.println(Version.getVersionAsXml());
686
                out.close();
687 2113 jones
            } else if (action.equals("getlog")) {
688 2558 sgarg
                handleGetLogAction(params, request, response, username, groupnames);
689 2682 sgarg
            } else if (action.equals("getloggedinuserinfo")) {
690
                PrintWriter out = response.getWriter();
691
                response.setContentType("text/xml");
692
                out.println("<?xml version=\"1.0\"?>");
693
                out.println("\n<user>\n");
694
                out.println("\n<username>\n");
695
                out.println(username);
696
                out.println("\n</username>\n");
697
                if(name!=null){
698
                	out.println("\n<name>\n");
699
                	out.println(name);
700
                	out.println("\n</name>\n");
701
                }
702
                if(MetaCatUtil.isAdministrator(username, groupnames)){
703
                	out.println("<isAdministrator></isAdministrator>\n");
704
                }
705
                if(MetaCatUtil.isModerator(username, groupnames)){
706
                	out.println("<isModerator></isModerator>\n");
707
                }
708
                out.println("\n</user>\n");
709
                out.close();
710 2312 jones
            } else if (action.equals("buildindex")) {
711 2558 sgarg
                handleBuildIndexAction(params, request, response, username, groupnames);
712 2098 jones
            } else if (action.equals("login") || action.equals("logout")) {
713 2312 jones
                /*
714 2098 jones
            } else if (action.equals("protocoltest")) {
715
                String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
716
                try {
717
                    testURL = ((String[]) params.get("url"))[0];
718
                } catch (Throwable t) {
719
                }
720
                String phandler = System
721
                        .getProperty("java.protocol.handler.pkgs");
722
                response.setContentType("text/html");
723
                PrintWriter out = response.getWriter();
724
                out.println("<body bgcolor=\"white\">");
725
                out.println("<p>Handler property: <code>" + phandler
726
                        + "</code></p>");
727
                out.println("<p>Starting test for:<br>");
728
                out.println("    " + testURL + "</p>");
729
                try {
730
                    URL u = new URL(testURL);
731
                    out.println("<pre>");
732
                    out.println("Protocol: " + u.getProtocol());
733
                    out.println("    Host: " + u.getHost());
734
                    out.println("    Port: " + u.getPort());
735
                    out.println("    Path: " + u.getPath());
736
                    out.println("     Ref: " + u.getRef());
737
                    String pquery = u.getQuery();
738
                    out.println("   Query: " + pquery);
739
                    out.println("  Params: ");
740
                    if (pquery != null) {
741 2099 jones
                        Hashtable qparams = MetaCatUtil.parseQuery(u.getQuery());
742 2098 jones
                        for (Enumeration en = qparams.keys(); en
743
                                .hasMoreElements();) {
744
                            String pname = (String) en.nextElement();
745
                            String pvalue = (String) qparams.get(pname);
746
                            out.println("    " + pname + ": " + pvalue);
747
                        }
748
                    }
749
                    out.println("</pre>");
750
                    out.println("</body>");
751
                    out.close();
752
                } catch (MalformedURLException mue) {
753
                    System.out.println(
754
                            "bad url from MetacatServlet.handleGetOrPost");
755
                    out.println(mue.getMessage());
756
                    mue.printStackTrace(out);
757
                    out.close();
758
                }
759 2312 jones
                */
760 2098 jones
            } else {
761
                PrintWriter out = response.getWriter();
762
                out.println("<?xml version=\"1.0\"?>");
763
                out.println("<error>");
764
                out.println(
765
                     "Error: action not registered.  Please report this error.");
766
                out.println("</error>");
767
                out.close();
768
            }
769 1360 tao
770 2098 jones
            //util.closeConnections();
771
            // Close the stream to the client
772
            //out.close();
773
        }
774
    }
775 425 bojilova
776 2912 harris
    /////////////////////////////// METACAT SPATIAL ///////////////////////////
777
778
    /**
779
     * handles all spatial queries -- these queries may include any of the
780
     * queries supported by the WFS / WMS standards
781 2938 harris
     *
782
     * handleSQuery(out, params, response, username, groupnames,
783
     *                        sess_id);
784 2912 harris
     */
785 2919 harris
    private void handleSpatialQuery(PrintWriter out, Hashtable params,
786
                                    HttpServletResponse response,
787
                                    String username, String[] groupnames,
788
                                    String sess_id) {
789
790 2912 harris
      Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
791 2946 sgarg
792 3034 perry
	if ( !MetaCatUtil.getOption("runSpatialOption").equals("true") ) {
793 2946 sgarg
        	response.setContentType("text/html");
794
        	out.println("<html> Metacat Spatial Option is turned off <html>");
795
        	out.close();
796
		return ;
797
	}
798
799 3034 perry
      //MetacatSpatialQuery _spatialQuery = new MetacatSpatialQuery();
800 2912 harris
801
802
      // switch -- html/xml print
803 2970 sgarg
      //MBJDELETED boolean printXML = false;
804 2912 harris
805
      // get the spatial parameters
806 2970 sgarg
      logMetacat.debug("params: " +  params);
807 2912 harris
      //String _xmax =  (String)params.get("XMAX");
808
      float _xmax = Float.parseFloat( ((String[]) params.get("XMAX"))[0] );
809
      float _ymax = Float.parseFloat( ((String[]) params.get("YMAX"))[0] );
810
      float _xmin = Float.parseFloat( ((String[]) params.get("XMIN"))[0] );
811
      float _ymin = Float.parseFloat( ((String[]) params.get("YMIN"))[0] );
812 2970 sgarg
      logMetacat.debug("\nxmax: " + _xmax + " \nymax:" + _ymax +
813 2912 harris
                      "\nxmin: " + _xmin + "\nymin: " + _ymin);
814
815 3028 perry
      // create an s-query
816
      String spatialQuery = createSpatialQuery(_xmin, _ymin, _xmax, _ymax);
817
      String[] queryArray = new String[1];
818
      queryArray[0] = spatialQuery;
819
      params.put("query", queryArray);
820 2912 harris
821 3028 perry
      // qformat
822
      String[] qformatArray = new String[1];
823
      try {
824
          String _skin = ((String[]) params.get("SKIN"))[0];
825
          qformatArray[0] = _skin;
826
      } catch (java.lang.NullPointerException e) {
827
          // should be "default" but keep this for backwards compatibility with knp site
828
          logMetacat.warn("No SKIN specified for metacat actions=spatial_query... defaulting to 'knp' skin !\n");
829
          qformatArray[0] = "knp";
830
      }
831
      params.put("qformat", qformatArray);
832 2912 harris
833 3028 perry
      // change the action
834
      String[] actionArray = new String[1];
835
      actionArray[0] = "squery";
836
      params.put("action", actionArray);
837
838
      handleSQuery(out, params, response, username, groupnames, sess_id);
839
840
841
/* MBJ DELETED -- using Metacat query instead
842 2938 harris
      // issue the Spatial query
843 2970 sgarg
      //MBJ DELETED MetacatSpatialDataset _data =
844
        //MBJ DELETED _spatialQuery.queryDatasetByCartesianBounds(_xmin, _ymin, _xmax, _ymax);
845 2912 harris
846 2938 harris
      // report the number of documents returned:
847 2970 sgarg
      //MBJ DELETED logMetacat.warn("\nThe number of documents in the BBOX query: "
848
              //MBJ DELETED + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
849
850
if (  _data.size() > 0) {
851 2938 harris
      logMetacat.warn("\nThe number of documents in the BBOX query: "
852
              + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
853 2946 sgarg
854 2938 harris
855 2919 harris
      // create an s-query
856
      String[] queryArray = new String[1];
857
      queryArray[0] = DocumentIdQuery.createDocidQuery(_data.getDocidList());
858
      params.put("query", queryArray);
859 2938 harris
860
      // qformat
861 2919 harris
      String[] qformatArray = new String[1];
862
      qformatArray[0] = "knp";
863
      params.put("qformat", qformatArray);
864
865
      // change the action
866
      String[] actionArray = new String[1];
867
      actionArray[0] = "squery";
868
      params.put("action", actionArray);
869
870 2912 harris
      // return the list of docs and point at the spatial theme
871
      if ( printXML) {
872
        response.setContentType("text/xml");
873 2915 harris
        out.println(_data.toXML() ); // write the data as xml
874 2912 harris
        out.close();
875
      } else {
876 2919 harris
        logMetacat.warn("username: " + username+"\nsession: "+sess_id);
877
        handleSQuery(out, params, response, username, groupnames, sess_id);
878 2912 harris
      }
879 2946 sgarg
} else {
880
        response.setContentType("text/html");
881
        out.println("<html>No Datasets Selected <html>");
882
        out.close();
883
}
884 2970 sgarg
*/
885 2946 sgarg
886 2912 harris
    }
887
888 2970 sgarg
    /**
889
     * Create a metacat squery for spatial data coordinates.
890
     */
891
    private String createSpatialQuery(float _xmin, float _ymin, float _xmax, float _ymax) {
892
	StringBuffer sb = new StringBuffer();
893
894
	sb.append("<pathquery version=\"1.2\">");
895
	sb.append("<querytitle>Untitled-Search-3</querytitle>");
896
	sb.append("<returndoctype>-//ecoinformatics.org//eml-dataset-2.0.0beta4//EN</returndoctype>");
897
	sb.append("<returndoctype>-//ecoinformatics.org//eml-dataset-2.0.0beta6//EN</returndoctype>");
898
	sb.append("<returndoctype>-//NCEAS//eml-dataset-2.0//EN</returndoctype>");
899
	sb.append("<returndoctype>-//NCEAS//resource//EN</returndoctype>");
900
	sb.append("<returndoctype>eml://ecoinformatics.org/eml-2.0.0</returndoctype>");
901
	sb.append("<returndoctype>eml://ecoinformatics.org/eml-2.0.1</returndoctype>");
902
	sb.append("<returndoctype>metadata</returndoctype>");
903
	sb.append("<returnfield>dataset/title</returnfield>");
904
	sb.append("<returnfield>originator/individualName/surName</returnfield>");
905
	sb.append("<returnfield>originator/individualName/givenName</returnfield>");
906
	sb.append("<returnfield>originator/organizationName</returnfield>");
907
	sb.append("<returnfield>creator/individualName/surName</returnfield>");
908
	sb.append("<returnfield>creator/individualName/givenName</returnfield>");
909
	sb.append("<returnfield>creator/organizationName</returnfield>");
910
	sb.append("<returnfield>keyword</returnfield>");
911
	sb.append("<returnfield>entityName</returnfield>");
912
	sb.append("<returnfield>idinfo/citation/citeinfo/title</returnfield>");
913
	sb.append("<returnfield>idinfo/citation/citeinfo/origin</returnfield>");
914
	sb.append("<returnfield>idinfo/keywords/theme/themekey</returnfield>");
915
	sb.append("<querygroup operator=\"INTERSECT\">");
916 3028 perry
	sb.append("<queryterm searchmode=\"greater-than\" casesensitive=\"false\">");
917 2970 sgarg
	sb.append("<value>" + _ymin + "</value>");
918
	sb.append("<pathexpr>northBoundingCoordinate</pathexpr>");
919
	sb.append("</queryterm>");
920 3028 perry
	sb.append("<queryterm searchmode=\"less-than\" casesensitive=\"false\">");
921 2970 sgarg
	sb.append("<value>" + _ymax + "</value>");
922 3028 perry
	sb.append("<pathexpr>southBoundingCoordinate</pathexpr>");
923 2970 sgarg
	sb.append("</queryterm>");
924 3028 perry
	sb.append("<queryterm searchmode=\"greater-than\" casesensitive=\"false\">");
925 2970 sgarg
	sb.append("<value>" + _xmin + "</value>");
926 3028 perry
	sb.append("<pathexpr>eastBoundingCoordinate</pathexpr>");
927 2970 sgarg
	sb.append("</queryterm>");
928 3028 perry
 	sb.append("<queryterm searchmode=\"less-than\" casesensitive=\"false\">");
929 2970 sgarg
	sb.append("<value>" + _xmax + "</value>");
930
	sb.append("<pathexpr>westBoundingCoordinate</pathexpr>");
931
	sb.append("</queryterm>");
932
	sb.append("</querygroup>");
933
	sb.append("</pathquery>");
934 2912 harris
935 2970 sgarg
	return sb.toString();
936
    }
937
938 2098 jones
    // LOGIN & LOGOUT SECTION
939
    /**
940
     * Handle the login request. Create a new session object. Do user
941
     * authentication through the session.
942
     */
943
    private void handleLoginAction(PrintWriter out, Hashtable params,
944
            HttpServletRequest request, HttpServletResponse response)
945 943 tao
    {
946 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
947 2098 jones
        AuthSession sess = null;
948 2252 sgarg
949
        if(params.get("username") == null){
950
            response.setContentType("text/xml");
951
            out.println("<?xml version=\"1.0\"?>");
952
            out.println("<error>");
953
            out.println("Username not specified");
954
            out.println("</error>");
955
            return;
956
        }
957
958 2912 harris
        //}
959
960 2252 sgarg
        if(params.get("password") == null){
961
            response.setContentType("text/xml");
962
            out.println("<?xml version=\"1.0\"?>");
963
            out.println("<error>");
964
            out.println("Password not specified");
965
            out.println("</error>");
966
            return;
967
        }
968
969 2098 jones
        String un = ((String[]) params.get("username"))[0];
970 2753 jones
        logMetacat.info("user " + un + " is trying to login");
971 2098 jones
        String pw = ((String[]) params.get("password"))[0];
972 943 tao
973 2252 sgarg
        String qformat = "xml";
974
        if(params.get("qformat") != null){
975
            qformat = ((String[]) params.get("qformat"))[0];
976
        }
977
978 2098 jones
        try {
979
            sess = new AuthSession();
980
        } catch (Exception e) {
981
            System.out.println("error in MetacatServlet.handleLoginAction: "
982
                    + e.getMessage());
983
            out.println(e.getMessage());
984
            return;
985
        }
986
        boolean isValid = sess.authenticate(request, un, pw);
987 1360 tao
988 2098 jones
        //if it is authernticate is true, store the session
989
        if (isValid) {
990
            HttpSession session = sess.getSessions();
991
            String id = session.getId();
992 2663 sgarg
            logMetacat.info("Store session id " + id
993 2098 jones
                    + "which has username" + session.getAttribute("username")
994 2663 sgarg
                    + " into hash in login method");
995 2098 jones
            sessionHash.put(id, session);
996
        }
997 1360 tao
998 2098 jones
        // format and transform the output
999
        if (qformat.equals("xml")) {
1000
            response.setContentType("text/xml");
1001
            out.println(sess.getMessage());
1002
        } else {
1003
            try {
1004
                DBTransform trans = new DBTransform();
1005
                response.setContentType("text/html");
1006
                trans.transformXMLDocument(sess.getMessage(),
1007
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1008
                        out, null);
1009
            } catch (Exception e) {
1010 1360 tao
1011 2663 sgarg
                logMetacat.error(
1012 2098 jones
                        "Error in MetaCatServlet.handleLoginAction: "
1013 2663 sgarg
                                + e.getMessage());
1014 2098 jones
            }
1015
        }
1016
    }
1017 1716 berkley
1018 2098 jones
    /**
1019
     * Handle the logout request. Close the connection.
1020
     */
1021
    private void handleLogoutAction(PrintWriter out, Hashtable params,
1022
            HttpServletRequest request, HttpServletResponse response)
1023 1483 tao
    {
1024 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1025 2252 sgarg
        String qformat = "xml";
1026
        if(params.get("qformat") != null){
1027
            qformat = ((String[]) params.get("qformat"))[0];
1028
        }
1029 1716 berkley
1030 2098 jones
        // close the connection
1031
        HttpSession sess = request.getSession(false);
1032 2663 sgarg
        logMetacat.info("After get session in logout request");
1033 2098 jones
        if (sess != null) {
1034 2663 sgarg
            logMetacat.info("The session id " + sess.getId()
1035
                    + " will be invalidate in logout action");
1036 2753 jones
            logMetacat.info("The session contains user "
1037 2098 jones
                    + sess.getAttribute("username")
1038 2663 sgarg
                    + " will be invalidate in logout action");
1039 2098 jones
            sess.invalidate();
1040
        }
1041 1716 berkley
1042 2098 jones
        // produce output
1043
        StringBuffer output = new StringBuffer();
1044
        output.append("<?xml version=\"1.0\"?>");
1045
        output.append("<logout>");
1046
        output.append("User logged out");
1047
        output.append("</logout>");
1048 1483 tao
1049 2098 jones
        //format and transform the output
1050
        if (qformat.equals("xml")) {
1051
            response.setContentType("text/xml");
1052
            out.println(output.toString());
1053
        } else {
1054
            try {
1055
                DBTransform trans = new DBTransform();
1056
                response.setContentType("text/html");
1057
                trans.transformXMLDocument(output.toString(),
1058
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1059
                        out, null);
1060
            } catch (Exception e) {
1061 2663 sgarg
                logMetacat.error(
1062 2098 jones
                        "Error in MetaCatServlet.handleLogoutAction"
1063 2663 sgarg
                                + e.getMessage());
1064 2098 jones
            }
1065 1716 berkley
        }
1066 2098 jones
    }
1067 1483 tao
1068 2098 jones
    // END OF LOGIN & LOGOUT SECTION
1069 1716 berkley
1070 2098 jones
    // SQUERY & QUERY SECTION
1071
    /**
1072
     * Retreive the squery xml, execute it and display it
1073 2169 sgarg
     *
1074 2098 jones
     * @param out the output stream to the client
1075
     * @param params the Hashtable of parameters that should be included in the
1076
     *            squery.
1077
     * @param response the response object linked to the client
1078
     * @param conn the database connection
1079
     */
1080 2570 jones
    private void handleSQuery(PrintWriter out, Hashtable params,
1081 2098 jones
            HttpServletResponse response, String user, String[] groups,
1082
            String sessionid)
1083
    {
1084
        double startTime = System.currentTimeMillis() / 1000;
1085 2752 jones
        DBQuery queryobj = new DBQuery();
1086 2098 jones
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1087
        double outPutTime = System.currentTimeMillis() / 1000;
1088 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1089
        logMetacat.info("Total search time for action 'squery': "
1090 2663 sgarg
                + (outPutTime - startTime));
1091 2098 jones
    }
1092 1716 berkley
1093 2098 jones
    /**
1094
     * Create the xml query, execute it and display the results.
1095 2169 sgarg
     *
1096 2098 jones
     * @param out the output stream to the client
1097
     * @param params the Hashtable of parameters that should be included in the
1098
     *            squery.
1099
     * @param response the response object linked to the client
1100
     */
1101 2570 jones
    private void handleQuery(PrintWriter out, Hashtable params,
1102 2098 jones
            HttpServletResponse response, String user, String[] groups,
1103
            String sessionid)
1104 1490 tao
    {
1105 2098 jones
        //create the query and run it
1106
        String xmlquery = DBQuery.createSQuery(params);
1107
        String[] queryArray = new String[1];
1108
        queryArray[0] = xmlquery;
1109
        params.put("query", queryArray);
1110
        double startTime = System.currentTimeMillis() / 1000;
1111 2752 jones
        DBQuery queryobj = new DBQuery();
1112 2098 jones
        queryobj.findDocuments(response, out, params, user, groups, sessionid);
1113
        double outPutTime = System.currentTimeMillis() / 1000;
1114 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1115
        logMetacat.info("Total search time for action 'query': "
1116 2663 sgarg
                + (outPutTime - startTime));
1117 1716 berkley
1118 2098 jones
        //handleSQuery(out, params, response,user, groups, sessionid);
1119 1490 tao
    }
1120 1716 berkley
1121 2098 jones
    // END OF SQUERY & QUERY SECTION
1122 1716 berkley
1123 2098 jones
    //Exoport section
1124
    /**
1125
     * Handle the "export" request of data package from Metacat in zip format
1126 2169 sgarg
     *
1127 2098 jones
     * @param params the Hashtable of HTTP request parameters
1128
     * @param response the HTTP response object linked to the client
1129
     * @param user the username sent the request
1130
     * @param groups the user's groupnames
1131
     */
1132 2169 sgarg
    private void handleExportAction(Hashtable params,
1133
            HttpServletResponse response,
1134 2102 jones
            String user, String[] groups, String passWord)
1135 2098 jones
    {
1136 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1137 2098 jones
        // Output stream
1138
        ServletOutputStream out = null;
1139
        // Zip output stream
1140
        ZipOutputStream zOut = null;
1141
        DBQuery queryObj = null;
1142 1716 berkley
1143 2098 jones
        String[] docs = new String[10];
1144
        String docId = "";
1145 1360 tao
1146 731 bojilova
        try {
1147 2098 jones
            // read the params
1148
            if (params.containsKey("docid")) {
1149
                docs = (String[]) params.get("docid");
1150 731 bojilova
            }
1151 2098 jones
            // Create a DBuery to handle export
1152 2752 jones
            queryObj = new DBQuery();
1153 2098 jones
            // Get the docid
1154
            docId = docs[0];
1155
            // Make sure the client specify docid
1156
            if (docId == null || docId.equals("")) {
1157
                response.setContentType("text/xml"); //MIME type
1158
                // Get a printwriter
1159
                PrintWriter pw = response.getWriter();
1160
                // Send back message
1161
                pw.println("<?xml version=\"1.0\"?>");
1162
                pw.println("<error>");
1163
                pw.println("You didn't specify requested docid");
1164
                pw.println("</error>");
1165
                // Close printwriter
1166
                pw.close();
1167
                return;
1168
            }
1169
            // Get output stream
1170
            out = response.getOutputStream();
1171
            response.setContentType("application/zip"); //MIME type
1172 2556 sgarg
            response.setHeader("Content-Disposition",
1173
            		"attachment; filename="
1174
            		+ docId + ".zip"); // Set the name of the zip file
1175
1176 2098 jones
            zOut = new ZipOutputStream(out);
1177
            zOut = queryObj
1178
                    .getZippedPackage(docId, out, user, groups, passWord);
1179
            zOut.finish(); //terminate the zip file
1180
            zOut.close(); //close the zip stream
1181 731 bojilova
1182 2098 jones
        } catch (Exception e) {
1183
            try {
1184
                response.setContentType("text/xml"); //MIME type
1185
                // Send error message back
1186
                if (out != null) {
1187
                    PrintWriter pw = new PrintWriter(out);
1188
                    pw.println("<?xml version=\"1.0\"?>");
1189
                    pw.println("<error>");
1190
                    pw.println(e.getMessage());
1191
                    pw.println("</error>");
1192
                    // Close printwriter
1193
                    pw.close();
1194
                    // Close output stream
1195
                    out.close();
1196
                }
1197
                // Close zip output stream
1198
                if (zOut != null) {
1199
                    zOut.close();
1200
                }
1201
            } catch (IOException ioe) {
1202 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1203 2098 jones
                        + "in MetacatServlet.handleExportAction: "
1204 2663 sgarg
                        + ioe.getMessage());
1205 731 bojilova
            }
1206
1207 2663 sgarg
            logMetacat.error(
1208 2098 jones
                    "Error in MetacatServlet.handleExportAction: "
1209 2663 sgarg
                            + e.getMessage());
1210 2098 jones
            e.printStackTrace(System.out);
1211
1212 731 bojilova
        }
1213 1360 tao
1214 2098 jones
    }
1215 1360 tao
1216 2098 jones
    /**
1217
     * In eml2 document, the xml can have inline data and data was stripped off
1218
     * and store in file system. This action can be used to read inline data
1219
     * only
1220 2169 sgarg
     *
1221 2098 jones
     * @param params the Hashtable of HTTP request parameters
1222
     * @param response the HTTP response object linked to the client
1223
     * @param user the username sent the request
1224
     * @param groups the user's groupnames
1225
     */
1226
    private void handleReadInlineDataAction(Hashtable params,
1227 2169 sgarg
            HttpServletRequest request, HttpServletResponse response,
1228 2102 jones
            String user, String passWord, String[] groups)
1229 2098 jones
    {
1230 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1231 2098 jones
        String[] docs = new String[10];
1232
        String inlineDataId = null;
1233
        String docId = "";
1234
        ServletOutputStream out = null;
1235 1360 tao
1236 2098 jones
        try {
1237
            // read the params
1238
            if (params.containsKey("inlinedataid")) {
1239
                docs = (String[]) params.get("inlinedataid");
1240
            }
1241
            // Get the docid
1242
            inlineDataId = docs[0];
1243
            // Make sure the client specify docid
1244 2169 sgarg
            if (inlineDataId == null || inlineDataId.equals("")) {
1245 2098 jones
                throw new Exception("You didn't specify requested inlinedataid"); }
1246 1360 tao
1247 2098 jones
            // check for permission
1248
            docId = MetaCatUtil
1249
                    .getDocIdWithoutRevFromInlineDataID(inlineDataId);
1250
            PermissionController controller = new PermissionController(docId);
1251
            // check top level read permission
1252
            if (!controller.hasPermission(user, groups,
1253 2245 sgarg
                    AccessControlInterface.READSTRING))
1254
            {
1255 2098 jones
                throw new Exception("User " + user
1256
                        + " doesn't have permission " + " to read document "
1257
                        + docId);
1258
            }
1259 2245 sgarg
            else
1260
            {
1261
              //check data access level
1262
              try
1263
              {
1264
                Hashtable unReadableInlineDataList =
1265 2292 sgarg
                    PermissionController.getUnReadableInlineDataIdList(docId,
1266
                    user, groups, false);
1267
                if (unReadableInlineDataList.containsValue(
1268
                          MetaCatUtil.getInlineDataIdWithoutRev(inlineDataId)))
1269 2245 sgarg
                {
1270
                  throw new Exception("User " + user
1271
                       + " doesn't have permission " + " to read inlinedata "
1272
                       + inlineDataId);
1273 2098 jones
1274 2245 sgarg
                }//if
1275
              }//try
1276
              catch (Exception e)
1277
              {
1278
                throw e;
1279
              }//catch
1280
            }//else
1281
1282 2098 jones
            // Get output stream
1283
            out = response.getOutputStream();
1284
            // read the inline data from the file
1285
            String inlinePath = MetaCatUtil.getOption("inlinedatafilepath");
1286
            File lineData = new File(inlinePath, inlineDataId);
1287
            FileInputStream input = new FileInputStream(lineData);
1288
            byte[] buffer = new byte[4 * 1024];
1289
            int bytes = input.read(buffer);
1290
            while (bytes != -1) {
1291
                out.write(buffer, 0, bytes);
1292
                bytes = input.read(buffer);
1293
            }
1294 1292 tao
            out.close();
1295 1360 tao
1296 2169 sgarg
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1297 2102 jones
                    inlineDataId, "readinlinedata");
1298 2098 jones
        } catch (Exception e) {
1299
            try {
1300
                PrintWriter pw = null;
1301
                // Send error message back
1302
                if (out != null) {
1303
                    pw = new PrintWriter(out);
1304
                } else {
1305
                    pw = response.getWriter();
1306
                }
1307
                pw.println("<?xml version=\"1.0\"?>");
1308
                pw.println("<error>");
1309
                pw.println(e.getMessage());
1310
                pw.println("</error>");
1311
                // Close printwriter
1312
                pw.close();
1313
                // Close output stream if out is not null
1314
                if (out != null) {
1315
                    out.close();
1316
                }
1317
            } catch (IOException ioe) {
1318 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1319 2098 jones
                        + "in MetacatServlet.handleExportAction: "
1320 2663 sgarg
                        + ioe.getMessage());
1321 2098 jones
            }
1322 2663 sgarg
            logMetacat.error(
1323 2098 jones
                    "Error in MetacatServlet.handleReadInlineDataAction: "
1324 2663 sgarg
                            + e.getMessage());
1325 1292 tao
        }
1326 2098 jones
    }
1327
1328
    /*
1329
     * Get the nodeid from xml_nodes for the inlinedataid
1330
     */
1331
    private long getInlineDataNodeId(String inLineDataId, String docId)
1332
            throws SQLException
1333 1292 tao
    {
1334 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1335 2098 jones
        long nodeId = 0;
1336
        String INLINE = "inline";
1337
        boolean hasRow;
1338
        PreparedStatement pStmt = null;
1339
        DBConnection conn = null;
1340
        int serialNumber = -1;
1341
        String sql = "SELECT nodeid FROM xml_nodes WHERE docid=? AND nodedata=? "
1342
                + "AND nodetype='TEXT' AND parentnodeid IN "
1343
                + "(SELECT nodeid FROM xml_nodes WHERE docid=? AND "
1344
                + "nodetype='ELEMENT' AND nodename='" + INLINE + "')";
1345 1360 tao
1346 2098 jones
        try {
1347
            //check out DBConnection
1348
            conn = DBConnectionPool
1349
                    .getDBConnection("AccessControlList.isAllowFirst");
1350
            serialNumber = conn.getCheckOutSerialNumber();
1351 1360 tao
1352 2098 jones
            pStmt = conn.prepareStatement(sql);
1353
            //bind value
1354
            pStmt.setString(1, docId);//docid
1355
            pStmt.setString(2, inLineDataId);//inlinedataid
1356
            pStmt.setString(3, docId);
1357
            // excute query
1358
            pStmt.execute();
1359
            ResultSet rs = pStmt.getResultSet();
1360
            hasRow = rs.next();
1361
            // get result
1362
            if (hasRow) {
1363
                nodeId = rs.getLong(1);
1364
            }//if
1365
1366
        } catch (SQLException e) {
1367
            throw e;
1368
        } finally {
1369
            try {
1370
                pStmt.close();
1371
            } finally {
1372
                DBConnectionPool.returnDBConnection(conn, serialNumber);
1373
            }
1374 1292 tao
        }
1375 2753 jones
        logMetacat.debug("The nodeid for inlinedataid " + inLineDataId
1376 2663 sgarg
                + " is: " + nodeId);
1377 2098 jones
        return nodeId;
1378
    }
1379 1360 tao
1380 2098 jones
    /**
1381
     * Handle the "read" request of metadata/data files from Metacat or any
1382
     * files from Internet; transformed metadata XML document into HTML
1383
     * presentation if requested; zip files when more than one were requested.
1384 2169 sgarg
     *
1385 2098 jones
     * @param params the Hashtable of HTTP request parameters
1386 2102 jones
     * @param request the HTTP request object linked to the client
1387 2098 jones
     * @param response the HTTP response object linked to the client
1388
     * @param user the username sent the request
1389
     * @param groups the user's groupnames
1390
     */
1391 2102 jones
    private void handleReadAction(Hashtable params, HttpServletRequest request,
1392 2098 jones
            HttpServletResponse response, String user, String passWord,
1393
            String[] groups)
1394
    {
1395 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1396 2098 jones
        ServletOutputStream out = null;
1397
        ZipOutputStream zout = null;
1398
        PrintWriter pw = null;
1399
        boolean zip = false;
1400
        boolean withInlineData = true;
1401 1360 tao
1402 2098 jones
        try {
1403
            String[] docs = new String[0];
1404
            String docid = "";
1405
            String qformat = "";
1406
            String abstrpath = null;
1407 731 bojilova
1408 2098 jones
            // read the params
1409
            if (params.containsKey("docid")) {
1410
                docs = (String[]) params.get("docid");
1411
            }
1412
            if (params.containsKey("qformat")) {
1413
                qformat = ((String[]) params.get("qformat"))[0];
1414
            }
1415
            // the param for only metadata (eml)
1416 2245 sgarg
            // we don't support read a eml document without inline data now.
1417
            /*if (params.containsKey("inlinedata")) {
1418 1360 tao
1419 2098 jones
                String inlineData = ((String[]) params.get("inlinedata"))[0];
1420
                if (inlineData.equalsIgnoreCase("false")) {
1421
                    withInlineData = false;
1422
                }
1423 2245 sgarg
            }*/
1424 2098 jones
            if ((docs.length > 1) || qformat.equals("zip")) {
1425
                zip = true;
1426
                out = response.getOutputStream();
1427
                response.setContentType("application/zip"); //MIME type
1428
                zout = new ZipOutputStream(out);
1429
            }
1430
            // go through the list of docs to read
1431
            for (int i = 0; i < docs.length; i++) {
1432
                try {
1433 1360 tao
1434 2098 jones
                    URL murl = new URL(docs[i]);
1435 2099 jones
                    Hashtable murlQueryStr = MetaCatUtil.parseQuery(
1436
                            murl.getQuery());
1437 2098 jones
                    // case docid="http://.../?docid=aaa"
1438
                    // or docid="metacat://.../?docid=bbb"
1439
                    if (murlQueryStr.containsKey("docid")) {
1440
                        // get only docid, eliminate the rest
1441
                        docid = (String) murlQueryStr.get("docid");
1442
                        if (zip) {
1443 2102 jones
                            addDocToZip(request, docid, zout, user, groups);
1444 2098 jones
                        } else {
1445 2102 jones
                            readFromMetacat(request, response, docid, qformat,
1446 2098 jones
                                    abstrpath, user, groups, zip, zout,
1447
                                    withInlineData, params);
1448
                        }
1449 1360 tao
1450 2098 jones
                        // case docid="http://.../filename"
1451
                    } else {
1452
                        docid = docs[i];
1453
                        if (zip) {
1454 2102 jones
                            addDocToZip(request, docid, zout, user, groups);
1455 2098 jones
                        } else {
1456
                            readFromURLConnection(response, docid);
1457
                        }
1458
                    }
1459 2169 sgarg
1460 2098 jones
                } catch (MalformedURLException mue) {
1461
                    docid = docs[i];
1462
                    if (zip) {
1463 2102 jones
                        addDocToZip(request, docid, zout, user, groups);
1464 2098 jones
                    } else {
1465 2169 sgarg
                        readFromMetacat(request, response, docid, qformat,
1466
                                abstrpath, user, groups, zip, zout,
1467 2102 jones
                                withInlineData, params);
1468 2098 jones
                    }
1469
                }
1470 2099 jones
            }
1471 1360 tao
1472 2098 jones
            if (zip) {
1473
                zout.finish(); //terminate the zip file
1474
                zout.close(); //close the zip stream
1475
            }
1476 1360 tao
1477 2098 jones
        } catch (McdbDocNotFoundException notFoundE) {
1478
            // To handle doc not found exception
1479
            // the docid which didn't be found
1480
            String notFoundDocId = notFoundE.getUnfoundDocId();
1481
            String notFoundRevision = notFoundE.getUnfoundRevision();
1482 2663 sgarg
            logMetacat.warn("Missed id: " + notFoundDocId);
1483
            logMetacat.warn("Missed rev: " + notFoundRevision);
1484 2098 jones
            try {
1485
                // read docid from remote server
1486
                readFromRemoteMetaCat(response, notFoundDocId,
1487
                        notFoundRevision, user, passWord, out, zip, zout);
1488
                // Close zout outputstream
1489
                if (zout != null) {
1490
                    zout.close();
1491
                }
1492
                // close output stream
1493
                if (out != null) {
1494
                    out.close();
1495
                }
1496 1360 tao
1497 2098 jones
            } catch (Exception exc) {
1498 2663 sgarg
                logMetacat.error(
1499 2098 jones
                        "Erorr in MetacatServlet.hanldReadAction: "
1500 2663 sgarg
                                + exc.getMessage());
1501 2098 jones
                try {
1502
                    if (out != null) {
1503
                        response.setContentType("text/xml");
1504
                        // Send back error message by printWriter
1505
                        pw = new PrintWriter(out);
1506
                        pw.println("<?xml version=\"1.0\"?>");
1507
                        pw.println("<error>");
1508
                        pw.println(notFoundE.getMessage());
1509
                        pw.println("</error>");
1510
                        pw.close();
1511
                        out.close();
1512 1360 tao
1513 2098 jones
                    } else {
1514
                        response.setContentType("text/xml"); //MIME type
1515
                        // Send back error message if out = null
1516
                        if (pw == null) {
1517
                            // If pw is null, open the respnose
1518
                            pw = response.getWriter();
1519
                        }
1520
                        pw.println("<?xml version=\"1.0\"?>");
1521
                        pw.println("<error>");
1522
                        pw.println(notFoundE.getMessage());
1523
                        pw.println("</error>");
1524
                        pw.close();
1525
                    }
1526
                    // close zout
1527
                    if (zout != null) {
1528
                        zout.close();
1529
                    }
1530
                } catch (IOException ie) {
1531 2663 sgarg
                    logMetacat.error("Problem with the servlet output "
1532 2098 jones
                            + "in MetacatServlet.handleReadAction: "
1533 2663 sgarg
                            + ie.getMessage());
1534 2098 jones
                }
1535
            }
1536
        } catch (Exception e) {
1537
            try {
1538 1716 berkley
1539 2098 jones
                if (out != null) {
1540
                    response.setContentType("text/xml"); //MIME type
1541
                    pw = new PrintWriter(out);
1542
                    pw.println("<?xml version=\"1.0\"?>");
1543
                    pw.println("<error>");
1544
                    pw.println(e.getMessage());
1545
                    pw.println("</error>");
1546
                    pw.close();
1547
                    out.close();
1548
                } else {
1549
                    response.setContentType("text/xml"); //MIME type
1550
                    // Send back error message if out = null
1551
                    if (pw == null) {
1552
                        pw = response.getWriter();
1553
                    }
1554
                    pw.println("<?xml version=\"1.0\"?>");
1555
                    pw.println("<error>");
1556
                    pw.println(e.getMessage());
1557
                    pw.println("</error>");
1558
                    pw.close();
1559 1360 tao
1560 2098 jones
                }
1561
                // Close zip output stream
1562
                if (zout != null) {
1563
                    zout.close();
1564
                }
1565 1360 tao
1566 2098 jones
            } catch (IOException ioe) {
1567 2663 sgarg
                logMetacat.error("Problem with the servlet output "
1568 2098 jones
                        + "in MetacatServlet.handleReadAction: "
1569 2663 sgarg
                        + ioe.getMessage());
1570 2098 jones
                ioe.printStackTrace(System.out);
1571 731 bojilova
1572 2098 jones
            }
1573 1360 tao
1574 2663 sgarg
            logMetacat.error(
1575 2098 jones
                    "Error in MetacatServlet.handleReadAction: "
1576 2663 sgarg
                            + e.getMessage());
1577 2098 jones
            //e.printStackTrace(System.out);
1578 731 bojilova
        }
1579 2098 jones
    }
1580 1360 tao
1581 2169 sgarg
    /** read metadata or data from Metacat
1582 2098 jones
     */
1583 2169 sgarg
    private void readFromMetacat(HttpServletRequest request,
1584 2102 jones
            HttpServletResponse response, String docid, String qformat,
1585
            String abstrpath, String user, String[] groups, boolean zip,
1586
            ZipOutputStream zout, boolean withInlineData, Hashtable params)
1587
            throws ClassNotFoundException, IOException, SQLException,
1588
            McdbException, Exception
1589 1292 tao
    {
1590 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1591 2098 jones
        try {
1592 2648 tao
1593
            // here is hack for handle docid=john.10(in order to tell mike.jim.10.1
1594
            // mike.jim.10, we require to provide entire docid with rev). But
1595
            // some old client they only provide docid without rev, so we need
1596
            // to handle this suituation. First we will check how many
1597
            // seperator here, if only one, we will append the rev in xml_documents
1598
            // to the id.
1599
            docid = appendRev(docid);
1600
1601 2098 jones
            DocumentImpl doc = new DocumentImpl(docid);
1602 1360 tao
1603 2098 jones
            //check the permission for read
1604 2113 jones
            if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1605 2098 jones
                Exception e = new Exception("User " + user
1606
                        + " does not have permission"
1607
                        + " to read the document with the docid " + docid);
1608 731 bojilova
1609 2098 jones
                throw e;
1610
            }
1611 1360 tao
1612 2098 jones
            if (doc.getRootNodeID() == 0) {
1613
                // this is data file
1614
                String filepath = MetaCatUtil.getOption("datafilepath");
1615
                if (!filepath.endsWith("/")) {
1616
                    filepath += "/";
1617
                }
1618
                String filename = filepath + docid;
1619
                FileInputStream fin = null;
1620
                fin = new FileInputStream(filename);
1621 1360 tao
1622 2098 jones
                //MIME type
1623
                String contentType = getServletContext().getMimeType(filename);
1624
                if (contentType == null) {
1625
                    ContentTypeProvider provider = new ContentTypeProvider(
1626
                            docid);
1627
                    contentType = provider.getContentType();
1628 2753 jones
                    logMetacat.info("Final contenttype is: "
1629 2663 sgarg
                            + contentType);
1630 2098 jones
                }
1631 731 bojilova
1632 2098 jones
                response.setContentType(contentType);
1633
                // if we decide to use "application/octet-stream" for all data
1634
                // returns
1635
                // response.setContentType("application/octet-stream");
1636 731 bojilova
1637 2098 jones
                try {
1638 731 bojilova
1639 2098 jones
                    ServletOutputStream out = response.getOutputStream();
1640
                    byte[] buf = new byte[4 * 1024]; // 4K buffer
1641
                    int b = fin.read(buf);
1642
                    while (b != -1) {
1643
                        out.write(buf, 0, b);
1644
                        b = fin.read(buf);
1645
                    }
1646
                } finally {
1647
                    if (fin != null) fin.close();
1648
                }
1649 2169 sgarg
1650 2098 jones
            } else {
1651
                // this is metadata doc
1652 2273 sgarg
                if (qformat.equals("xml") || qformat.equals("")) {
1653
                    // if equals "", that means no qformat is specified. hence
1654
                    // by default the document should be returned in xml format
1655 2098 jones
                    // set content type first
1656
                    response.setContentType("text/xml"); //MIME type
1657
                    PrintWriter out = response.getWriter();
1658
                    doc.toXml(out, user, groups, withInlineData);
1659
                } else {
1660
                    response.setContentType("text/html"); //MIME type
1661
                    PrintWriter out = response.getWriter();
1662 1360 tao
1663 2098 jones
                    // Look up the document type
1664
                    String doctype = doc.getDoctype();
1665
                    // Transform the document to the new doctype
1666
                    DBTransform dbt = new DBTransform();
1667
                    dbt.transformXMLDocument(doc.toString(user, groups,
1668
                            withInlineData), doctype, "-//W3C//HTML//EN",
1669
                            qformat, out, params);
1670
                }
1671 1360 tao
1672 2098 jones
            }
1673 2169 sgarg
            EventLog.getInstance().log(request.getRemoteAddr(), user,
1674 2101 jones
                    docid, "read");
1675 2098 jones
        } catch (Exception except) {
1676
            throw except;
1677
        }
1678
    }
1679 1360 tao
1680 2169 sgarg
    /**
1681
     * read data from URLConnection
1682 2098 jones
     */
1683
    private void readFromURLConnection(HttpServletResponse response,
1684
            String docid) throws IOException, MalformedURLException
1685
    {
1686
        ServletOutputStream out = response.getOutputStream();
1687
        String contentType = getServletContext().getMimeType(docid); //MIME
1688
                                                                     // type
1689
        if (contentType == null) {
1690
            if (docid.endsWith(".xml")) {
1691
                contentType = "text/xml";
1692
            } else if (docid.endsWith(".css")) {
1693
                contentType = "text/css";
1694
            } else if (docid.endsWith(".dtd")) {
1695
                contentType = "text/plain";
1696
            } else if (docid.endsWith(".xsd")) {
1697
                contentType = "text/xml";
1698
            } else if (docid.endsWith("/")) {
1699
                contentType = "text/html";
1700
            } else {
1701
                File f = new File(docid);
1702
                if (f.isDirectory()) {
1703
                    contentType = "text/html";
1704
                } else {
1705
                    contentType = "application/octet-stream";
1706
                }
1707
            }
1708 1360 tao
        }
1709 2098 jones
        response.setContentType(contentType);
1710
        // if we decide to use "application/octet-stream" for all data returns
1711
        // response.setContentType("application/octet-stream");
1712 1360 tao
1713 2098 jones
        // this is http url
1714
        URL url = new URL(docid);
1715
        BufferedInputStream bis = null;
1716
        try {
1717
            bis = new BufferedInputStream(url.openStream());
1718 731 bojilova
            byte[] buf = new byte[4 * 1024]; // 4K buffer
1719 2098 jones
            int b = bis.read(buf);
1720 731 bojilova
            while (b != -1) {
1721 2098 jones
                out.write(buf, 0, b);
1722
                b = bis.read(buf);
1723 731 bojilova
            }
1724 2098 jones
        } finally {
1725
            if (bis != null) bis.close();
1726 636 berkley
        }
1727 1360 tao
1728 636 berkley
    }
1729 1360 tao
1730 2169 sgarg
    /**
1731 2098 jones
     * read file/doc and write to ZipOutputStream
1732 2169 sgarg
     *
1733 2098 jones
     * @param docid
1734
     * @param zout
1735
     * @param user
1736
     * @param groups
1737
     * @throws ClassNotFoundException
1738
     * @throws IOException
1739
     * @throws SQLException
1740
     * @throws McdbException
1741
     * @throws Exception
1742
     */
1743 2169 sgarg
    private void addDocToZip(HttpServletRequest request, String docid,
1744 2102 jones
            ZipOutputStream zout, String user, String[] groups) throws
1745
            ClassNotFoundException, IOException, SQLException, McdbException,
1746
            Exception
1747 1293 tao
    {
1748 2098 jones
        byte[] bytestring = null;
1749
        ZipEntry zentry = null;
1750 1360 tao
1751 598 bojilova
        try {
1752 2098 jones
            URL url = new URL(docid);
1753 1360 tao
1754 2098 jones
            // this http url; read from URLConnection; add to zip
1755
            zentry = new ZipEntry(docid);
1756
            zout.putNextEntry(zentry);
1757
            BufferedInputStream bis = null;
1758
            try {
1759
                bis = new BufferedInputStream(url.openStream());
1760
                byte[] buf = new byte[4 * 1024]; // 4K buffer
1761
                int b = bis.read(buf);
1762
                while (b != -1) {
1763
                    zout.write(buf, 0, b);
1764
                    b = bis.read(buf);
1765
                }
1766
            } finally {
1767
                if (bis != null) bis.close();
1768
            }
1769
            zout.closeEntry();
1770 1716 berkley
1771 2098 jones
        } catch (MalformedURLException mue) {
1772 203 jones
1773 2098 jones
            // this is metacat doc (data file or metadata doc)
1774
            try {
1775
                DocumentImpl doc = new DocumentImpl(docid);
1776 1360 tao
1777 2098 jones
                //check the permission for read
1778 2113 jones
                if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
1779 2098 jones
                    Exception e = new Exception("User " + user
1780
                            + " does not have "
1781
                            + "permission to read the document with the docid "
1782
                            + docid);
1783
                    throw e;
1784
                }
1785 1360 tao
1786 2098 jones
                if (doc.getRootNodeID() == 0) {
1787
                    // this is data file; add file to zip
1788
                    String filepath = MetaCatUtil.getOption("datafilepath");
1789
                    if (!filepath.endsWith("/")) {
1790
                        filepath += "/";
1791
                    }
1792
                    String filename = filepath + docid;
1793
                    FileInputStream fin = null;
1794
                    fin = new FileInputStream(filename);
1795
                    try {
1796 1360 tao
1797 2098 jones
                        zentry = new ZipEntry(docid);
1798
                        zout.putNextEntry(zentry);
1799
                        byte[] buf = new byte[4 * 1024]; // 4K buffer
1800
                        int b = fin.read(buf);
1801
                        while (b != -1) {
1802
                            zout.write(buf, 0, b);
1803
                            b = fin.read(buf);
1804
                        }
1805
                    } finally {
1806
                        if (fin != null) fin.close();
1807
                    }
1808
                    zout.closeEntry();
1809 1716 berkley
1810 2098 jones
                } else {
1811
                    // this is metadata doc; add doc to zip
1812
                    bytestring = doc.toString().getBytes();
1813
                    zentry = new ZipEntry(docid + ".xml");
1814
                    zentry.setSize(bytestring.length);
1815
                    zout.putNextEntry(zentry);
1816
                    zout.write(bytestring, 0, bytestring.length);
1817
                    zout.closeEntry();
1818
                }
1819 2169 sgarg
                EventLog.getInstance().log(request.getRemoteAddr(), user,
1820 2101 jones
                        docid, "read");
1821 2098 jones
            } catch (Exception except) {
1822
                throw except;
1823
            }
1824 1360 tao
        }
1825 2098 jones
    }
1826 309 bojilova
1827 2098 jones
    /**
1828
     * If metacat couldn't find a data file or document locally, it will read
1829
     * this docid from its home server. This is for the replication feature
1830
     */
1831
    private void readFromRemoteMetaCat(HttpServletResponse response,
1832
            String docid, String rev, String user, String password,
1833
            ServletOutputStream out, boolean zip, ZipOutputStream zout)
1834
            throws Exception
1835 1466 tao
    {
1836 2098 jones
        // Create a object of RemoteDocument, "" is for zipEntryPath
1837
        RemoteDocument remoteDoc = new RemoteDocument(docid, rev, user,
1838
                password, "");
1839
        String docType = remoteDoc.getDocType();
1840
        // Only read data file
1841
        if (docType.equals("BIN")) {
1842
            // If it is zip format
1843
            if (zip) {
1844
                remoteDoc.readDocumentFromRemoteServerByZip(zout);
1845
            } else {
1846
                if (out == null) {
1847
                    out = response.getOutputStream();
1848
                }
1849
                response.setContentType("application/octet-stream");
1850
                remoteDoc.readDocumentFromRemoteServer(out);
1851
            }
1852
        } else {
1853
            throw new Exception("Docid: " + docid + "." + rev
1854
                    + " couldn't find");
1855
        }
1856 203 jones
    }
1857
1858 2098 jones
    /**
1859
     * Handle the database putdocument request and write an XML document to the
1860
     * database connection
1861
     */
1862 2102 jones
    private void handleInsertOrUpdateAction(HttpServletRequest request,
1863
            HttpServletResponse response, PrintWriter out, Hashtable params,
1864 2098 jones
            String user, String[] groups)
1865
    {
1866 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
1867 2098 jones
        DBConnection dbConn = null;
1868
        int serialNumber = -1;
1869 1360 tao
1870 2252 sgarg
        if(params.get("docid") == null){
1871
            out.println("<?xml version=\"1.0\"?>");
1872
            out.println("<error>");
1873
            out.println("Docid not specified");
1874
            out.println("</error>");
1875 2663 sgarg
            logMetacat.error("Docid not specified");
1876 2252 sgarg
            return;
1877
        }
1878 2576 sgarg
1879
        if(!MetaCatUtil.canInsertOrUpdate(user, groups)){
1880
        	out.println("<?xml version=\"1.0\"?>");
1881
            out.println("<error>");
1882
            out.println("User '" + user + "' not allowed to insert and update");
1883
            out.println("</error>");
1884 2663 sgarg
            logMetacat.error("User '" + user + "' not allowed to insert and update");
1885 2576 sgarg
            return;
1886
        }
1887 2252 sgarg
1888 2098 jones
        try {
1889
            // Get the document indicated
1890
            String[] doctext = (String[]) params.get("doctext");
1891
            String pub = null;
1892
            if (params.containsKey("public")) {
1893
                pub = ((String[]) params.get("public"))[0];
1894
            }
1895 1360 tao
1896 2098 jones
            StringReader dtd = null;
1897
            if (params.containsKey("dtdtext")) {
1898
                String[] dtdtext = (String[]) params.get("dtdtext");
1899
                try {
1900
                    if (!dtdtext[0].equals("")) {
1901
                        dtd = new StringReader(dtdtext[0]);
1902
                    }
1903
                } catch (NullPointerException npe) {
1904
                }
1905
            }
1906 2347 sgarg
1907
            if(doctext == null){
1908
                out.println("<?xml version=\"1.0\"?>");
1909
                out.println("<error>");
1910
                out.println("Document text not submitted");
1911
                out.println("</error>");
1912
                return;
1913
            }
1914
1915 2098 jones
            StringReader xml = new StringReader(doctext[0]);
1916
            boolean validate = false;
1917
            DocumentImplWrapper documentWrapper = null;
1918
            try {
1919
                // look inside XML Document for <!DOCTYPE ... PUBLIC/SYSTEM ...
1920
                // >
1921
                // in order to decide whether to use validation parser
1922
                validate = needDTDValidation(xml);
1923
                if (validate) {
1924
                    // set a dtd base validation parser
1925
                    String rule = DocumentImpl.DTD;
1926
                    documentWrapper = new DocumentImplWrapper(rule, validate);
1927 2711 sgarg
                } else {
1928
1929 2169 sgarg
                    String namespace = findNamespace(xml);
1930 2711 sgarg
1931
                	if (namespace != null) {
1932
                		if (namespace.compareTo(DocumentImpl.EML2_0_0NAMESPACE) == 0
1933
                				|| namespace.compareTo(
1934
                				DocumentImpl.EML2_0_1NAMESPACE) == 0) {
1935
                			// set eml2 base	 validation parser
1936
                			String rule = DocumentImpl.EML200;
1937
                			// using emlparser to check id validation
1938
                			EMLParser parser = new EMLParser(doctext[0]);
1939
                			documentWrapper = new DocumentImplWrapper(rule, true);
1940
                		} else if (namespace.compareTo(
1941 2169 sgarg
                                DocumentImpl.EML2_1_0NAMESPACE) == 0) {
1942 2711 sgarg
                			// set eml2 base validation parser
1943
                			String rule = DocumentImpl.EML210;
1944
                			// using emlparser to check id validation
1945
                			EMLParser parser = new EMLParser(doctext[0]);
1946
                			documentWrapper = new DocumentImplWrapper(rule, true);
1947
                		} else {
1948
                			// set schema base validation parser
1949
                			String rule = DocumentImpl.SCHEMA;
1950
                			documentWrapper = new DocumentImplWrapper(rule, true);
1951
                		}
1952
                	} else {
1953
                		documentWrapper = new DocumentImplWrapper("", false);
1954
                	}
1955 2098 jones
                }
1956 695 bojilova
1957 2098 jones
                String[] action = (String[]) params.get("action");
1958
                String[] docid = (String[]) params.get("docid");
1959
                String newdocid = null;
1960 695 bojilova
1961 2098 jones
                String doAction = null;
1962
                if (action[0].equals("insert")) {
1963
                    doAction = "INSERT";
1964
                } else if (action[0].equals("update")) {
1965
                    doAction = "UPDATE";
1966
                }
1967 695 bojilova
1968 2098 jones
                try {
1969
                    // get a connection from the pool
1970
                    dbConn = DBConnectionPool
1971
                            .getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
1972
                    serialNumber = dbConn.getCheckOutSerialNumber();
1973 1716 berkley
1974 2098 jones
                    // write the document to the database
1975
                    try {
1976
                        String accNumber = docid[0];
1977 2753 jones
                        logMetacat.debug("" + doAction + " "
1978 2663 sgarg
                                + accNumber + "...");
1979 2098 jones
                        if (accNumber.equals("")) {
1980
                            accNumber = null;
1981 2102 jones
                        }
1982 2098 jones
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1983
                                doAction, accNumber, user, groups);
1984 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
1985 2102 jones
                                user, accNumber, action[0]);
1986
                    } catch (NullPointerException npe) {
1987 2098 jones
                        newdocid = documentWrapper.write(dbConn, xml, pub, dtd,
1988
                                doAction, null, user, groups);
1989 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
1990 2102 jones
                                user, "", action[0]);
1991
                    }
1992
                }
1993 2098 jones
                finally {
1994
                    // Return db connection
1995
                    DBConnectionPool.returnDBConnection(dbConn, serialNumber);
1996
                }
1997 1716 berkley
1998 2098 jones
                // set content type and other response header fields first
1999
                //response.setContentType("text/xml");
2000
                out.println("<?xml version=\"1.0\"?>");
2001
                out.println("<success>");
2002
                out.println("<docid>" + newdocid + "</docid>");
2003
                out.println("</success>");
2004 1716 berkley
2005 2098 jones
            } catch (NullPointerException npe) {
2006
                //response.setContentType("text/xml");
2007
                out.println("<?xml version=\"1.0\"?>");
2008
                out.println("<error>");
2009
                out.println(npe.getMessage());
2010
                out.println("</error>");
2011 2690 sgarg
                logMetacat.warn("Error in writing eml document to the database" + npe.getMessage());
2012 2729 sgarg
                npe.printStackTrace();
2013 2098 jones
            }
2014
        } catch (Exception e) {
2015
            //response.setContentType("text/xml");
2016
            out.println("<?xml version=\"1.0\"?>");
2017
            out.println("<error>");
2018
            out.println(e.getMessage());
2019
            out.println("</error>");
2020 2690 sgarg
            logMetacat.warn("Error in writing eml document to the database" + e.getMessage());
2021 2729 sgarg
            e.printStackTrace();
2022 1760 tao
        }
2023 1409 tao
    }
2024 1716 berkley
2025 2098 jones
    /**
2026
     * Parse XML Document to look for <!DOCTYPE ... PUBLIC/SYSTEM ... > in
2027
     * order to decide whether to use validation parser
2028
     */
2029
    private static boolean needDTDValidation(StringReader xmlreader)
2030
            throws IOException
2031 1629 tao
    {
2032 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2033 2098 jones
        StringBuffer cbuff = new StringBuffer();
2034
        java.util.Stack st = new java.util.Stack();
2035
        boolean validate = false;
2036
        int c;
2037
        int inx;
2038 2089 tao
2039 2098 jones
        // read from the stream until find the keywords
2040
        while ((st.empty() || st.size() < 4) && ((c = xmlreader.read()) != -1)) {
2041
            cbuff.append((char) c);
2042 1716 berkley
2043 2098 jones
            // "<!DOCTYPE" keyword is found; put it in the stack
2044
            if ((inx = cbuff.toString().indexOf("<!DOCTYPE")) != -1) {
2045
                cbuff = new StringBuffer();
2046
                st.push("<!DOCTYPE");
2047
            }
2048
            // "PUBLIC" keyword is found; put it in the stack
2049
            if ((inx = cbuff.toString().indexOf("PUBLIC")) != -1) {
2050
                cbuff = new StringBuffer();
2051
                st.push("PUBLIC");
2052
            }
2053
            // "SYSTEM" keyword is found; put it in the stack
2054
            if ((inx = cbuff.toString().indexOf("SYSTEM")) != -1) {
2055
                cbuff = new StringBuffer();
2056
                st.push("SYSTEM");
2057
            }
2058
            // ">" character is found; put it in the stack
2059
            // ">" is found twice: fisrt from <?xml ...?>
2060
            // and second from <!DOCTYPE ... >
2061
            if ((inx = cbuff.toString().indexOf(">")) != -1) {
2062
                cbuff = new StringBuffer();
2063
                st.push(">");
2064
            }
2065
        }
2066 203 jones
2067 2098 jones
        // close the stream
2068
        xmlreader.reset();
2069 1360 tao
2070 2098 jones
        // check the stack whether it contains the keywords:
2071
        // "<!DOCTYPE", "PUBLIC" or "SYSTEM", and ">" in this order
2072
        if (st.size() == 4) {
2073
            if (((String) st.pop()).equals(">")
2074
                    && (((String) st.peek()).equals("PUBLIC") | ((String) st
2075
                            .pop()).equals("SYSTEM"))
2076
                    && ((String) st.pop()).equals("<!DOCTYPE")) {
2077
                validate = true;
2078
            }
2079
        }
2080 1360 tao
2081 2753 jones
        logMetacat.info("Validation for dtd is " + validate);
2082 2098 jones
        return validate;
2083 1360 tao
    }
2084
2085 2098 jones
    // END OF INSERT/UPDATE SECTION
2086 68 higgins
2087 2098 jones
    /* check if the xml string contains key words to specify schema loocation */
2088 2169 sgarg
    private String findNamespace(StringReader xml) throws IOException
2089 2098 jones
    {
2090 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2091 2169 sgarg
        String namespace = null;
2092
2093
        String eml2_0_0NameSpace = DocumentImpl.EML2_0_0NAMESPACE;
2094 2224 sgarg
        String eml2_0_1NameSpace = DocumentImpl.EML2_0_1NAMESPACE;
2095 2169 sgarg
        String eml2_1_0NameSpace = DocumentImpl.EML2_1_0NAMESPACE;
2096
2097 2098 jones
        if (xml == null) {
2098 2753 jones
            logMetacat.debug("Validation for schema is "
2099 2663 sgarg
                    + namespace);
2100 2169 sgarg
            return namespace;
2101 2098 jones
        }
2102
        String targetLine = getSchemaLine(xml);
2103 2918 sgarg
2104 2098 jones
        if (targetLine != null) {
2105 1360 tao
2106 2711 sgarg
        	// find if the root element has prefix
2107
        	String prefix = getPrefix(targetLine);
2108 2729 sgarg
        	logMetacat.info("prefix is:" + prefix);
2109 2711 sgarg
        	int startIndex = 0;
2110
2111 2729 sgarg
2112 2711 sgarg
        	if(prefix != null)
2113
        	{
2114
        		// if prefix found then look for xmlns:prefix
2115
        		// element to find the ns
2116 2712 sgarg
        		String namespaceWithPrefix = NAMESPACEKEYWORD
2117
        					+ ":" + prefix;
2118 2711 sgarg
        		startIndex = targetLine.indexOf(namespaceWithPrefix);
2119 2753 jones
            	logMetacat.debug("namespaceWithPrefix is:" + namespaceWithPrefix+":");
2120
            	logMetacat.debug("startIndex is:" + startIndex);
2121 2712 sgarg
2122 2711 sgarg
        	} else {
2123
        		// if prefix not found then look for xmlns
2124
        		// attribute to find the ns
2125
        		startIndex = targetLine.indexOf(NAMESPACEKEYWORD);
2126 2753 jones
            	logMetacat.debug("startIndex is:" + startIndex);
2127 2711 sgarg
        	}
2128
2129 2098 jones
            int start = 1;
2130
            int end = 1;
2131 2711 sgarg
            String namespaceString = null;
2132 2098 jones
            int count = 0;
2133
            if (startIndex != -1) {
2134
                for (int i = startIndex; i < targetLine.length(); i++) {
2135
                    if (targetLine.charAt(i) == '"') {
2136
                        count++;
2137
                    }
2138
                    if (targetLine.charAt(i) == '"' && count == 1) {
2139
                        start = i;
2140
                    }
2141
                    if (targetLine.charAt(i) == '"' && count == 2) {
2142
                        end = i;
2143
                        break;
2144
                    }
2145
                }
2146 2711 sgarg
            }
2147
            // else: xmlns not found. namespace = null will be returned
2148
2149 2753 jones
         	logMetacat.debug("targetLine is " + targetLine);
2150 2729 sgarg
         	logMetacat.debug("start is " + end);
2151
         	logMetacat.debug("end is " + end);
2152
2153 2711 sgarg
            if(start < end){
2154
            	namespaceString = targetLine.substring(start + 1, end);
2155 2753 jones
            	logMetacat.debug("namespaceString is " + namespaceString);
2156 2098 jones
            }
2157 2753 jones
            logMetacat.debug("namespace in xml is: "
2158 2711 sgarg
                    + namespaceString);
2159 2729 sgarg
            if(namespaceString != null){
2160
            	if (namespaceString.indexOf(eml2_0_0NameSpace) != -1) {
2161
            		namespace = eml2_0_0NameSpace;
2162
            	} else if (namespaceString.indexOf(eml2_0_1NameSpace) != -1) {
2163
            		namespace = eml2_0_1NameSpace;
2164
            	} else if (namespaceString.indexOf(eml2_1_0NameSpace) != -1) {
2165
            		namespace = eml2_1_0NameSpace;
2166
            	} else {
2167
            		namespace = namespaceString;
2168
            	}
2169 2098 jones
            }
2170
        }
2171 185 jones
2172 2753 jones
        logMetacat.debug("Validation for eml is " + namespace);
2173 2224 sgarg
2174 2169 sgarg
        return namespace;
2175 1360 tao
2176 103 jones
    }
2177 68 higgins
2178 2098 jones
    private String getSchemaLine(StringReader xml) throws IOException
2179
    {
2180 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2181 2098 jones
        // find the line
2182
        String secondLine = null;
2183
        int count = 0;
2184
        int endIndex = 0;
2185
        int startIndex = 0;
2186 3002 sgarg
        final int TARGETNUM = 1;
2187 2098 jones
        StringBuffer buffer = new StringBuffer();
2188
        boolean comment = false;
2189 3002 sgarg
        boolean processingInstruction = false;
2190 2098 jones
        char thirdPreviousCharacter = '?';
2191
        char secondPreviousCharacter = '?';
2192
        char previousCharacter = '?';
2193
        char currentCharacter = '?';
2194 2268 sgarg
        int tmp = xml.read();
2195
        while (tmp != -1) {
2196
            currentCharacter = (char)tmp;
2197 2098 jones
            //in a comment
2198
            if (currentCharacter == '-' && previousCharacter == '-'
2199
                    && secondPreviousCharacter == '!'
2200
                    && thirdPreviousCharacter == '<') {
2201
                comment = true;
2202
            }
2203
            //out of comment
2204
            if (comment && currentCharacter == '>' && previousCharacter == '-'
2205
                    && secondPreviousCharacter == '-') {
2206
                comment = false;
2207
            }
2208 68 higgins
2209 3002 sgarg
            //in a processingInstruction
2210
            if (currentCharacter == '?' && previousCharacter == '<') {
2211
            	processingInstruction = true;
2212
            }
2213
2214
            //out of processingInstruction
2215
            if (processingInstruction && currentCharacter == '>'
2216
            	&& previousCharacter == '?') {
2217
            	processingInstruction = false;
2218
            }
2219
2220
            //this is not comment or a processingInstruction
2221
            if (currentCharacter != '!' && previousCharacter == '<'
2222
            	&& !comment && !processingInstruction) {
2223 2098 jones
                count++;
2224
            }
2225 3002 sgarg
2226 2098 jones
            // get target line
2227
            if (count == TARGETNUM && currentCharacter != '>') {
2228
                buffer.append(currentCharacter);
2229
            }
2230
            if (count == TARGETNUM && currentCharacter == '>') {
2231
                break;
2232
            }
2233
            thirdPreviousCharacter = secondPreviousCharacter;
2234
            secondPreviousCharacter = previousCharacter;
2235
            previousCharacter = currentCharacter;
2236 2268 sgarg
            tmp = xml.read();
2237 2098 jones
        }
2238
        secondLine = buffer.toString();
2239 2753 jones
        logMetacat.debug("the second line string is: " + secondLine);
2240 2663 sgarg
2241 2098 jones
        xml.reset();
2242
        return secondLine;
2243
    }
2244 253 jones
2245 2711 sgarg
    private String getPrefix(String schemaLine)
2246
    {
2247 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2248 2922 jones
        String prefix = null;
2249 3002 sgarg
2250 2922 jones
        if(schemaLine.indexOf(" ") > 0){
2251
            String rootElement = "";
2252
            try {
2253
                rootElement = schemaLine.substring(0, schemaLine.indexOf(" "));
2254
            } catch (StringIndexOutOfBoundsException sioobe) {
2255
                rootElement = schemaLine;
2256
            }
2257
2258
            logMetacat.debug("rootElement:" + rootElement);
2259 2711 sgarg
2260 2922 jones
            if(rootElement.indexOf(":") > 0){
2261
                prefix = rootElement.substring(rootElement.indexOf(":") + 1,
2262
                    rootElement.length());
2263
            }
2264 3002 sgarg
2265 2922 jones
            if(prefix != null){
2266
                return prefix.trim();
2267
            }
2268
        }
2269
        return null;
2270 2711 sgarg
    }
2271
2272 2098 jones
    /**
2273
     * Handle the database delete request and delete an XML document from the
2274
     * database connection
2275
     */
2276
    private void handleDeleteAction(PrintWriter out, Hashtable params,
2277 2169 sgarg
            HttpServletRequest request, HttpServletResponse response,
2278 2102 jones
            String user, String[] groups)
2279 2098 jones
    {
2280 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2281 2098 jones
        String[] docid = (String[]) params.get("docid");
2282 1360 tao
2283 2251 sgarg
        if(docid == null){
2284
          response.setContentType("text/xml");
2285
          out.println("<?xml version=\"1.0\"?>");
2286
          out.println("<error>");
2287 2252 sgarg
          out.println("Docid not specified.");
2288 2251 sgarg
          out.println("</error>");
2289 2668 sgarg
          logMetacat.error("Docid not specified for the document to be deleted.");
2290 2251 sgarg
        } else {
2291 1360 tao
2292 2251 sgarg
            // delete the document from the database
2293 2098 jones
            try {
2294 2251 sgarg
2295
                try {
2296 2298 tao
                    // null means notify server is null
2297
                    DocumentImpl.delete(docid[0], user, groups, null);
2298 2251 sgarg
                    EventLog.getInstance().log(request.getRemoteAddr(),
2299
                                               user, docid[0], "delete");
2300
                    response.setContentType("text/xml");
2301
                    out.println("<?xml version=\"1.0\"?>");
2302
                    out.println("<success>");
2303
                    out.println("Document deleted.");
2304
                    out.println("</success>");
2305 2753 jones
                    logMetacat.info("Document deleted.");
2306 3034 perry
2307
                    // Delete from spatial cache
2308
                    SpatialHarvester sh = new SpatialHarvester();
2309
                    sh.addToDeleteQue( MetaCatUtil.getSmartDocId( docid[0] ) );
2310
                    sh.destroy();
2311
2312 2251 sgarg
                }
2313
                catch (AccessionNumberException ane) {
2314
                    response.setContentType("text/xml");
2315
                    out.println("<?xml version=\"1.0\"?>");
2316
                    out.println("<error>");
2317 2253 sgarg
                    //out.println("Error deleting document!!!");
2318 2251 sgarg
                    out.println(ane.getMessage());
2319
                    out.println("</error>");
2320 2668 sgarg
                    logMetacat.error("Document could not be deleted: "
2321
                    		+ ane.getMessage());
2322 2251 sgarg
                }
2323
            }
2324
            catch (Exception e) {
2325 2098 jones
                response.setContentType("text/xml");
2326
                out.println("<?xml version=\"1.0\"?>");
2327
                out.println("<error>");
2328 2251 sgarg
                out.println(e.getMessage());
2329 2098 jones
                out.println("</error>");
2330 2668 sgarg
                logMetacat.error("Document could not be deleted: "
2331
                		+ e.getMessage());
2332 2098 jones
            }
2333
        }
2334 1292 tao
    }
2335 1360 tao
2336 2098 jones
    /**
2337
     * Handle the validation request and return the results to the requestor
2338
     */
2339
    private void handleValidateAction(PrintWriter out, Hashtable params)
2340 1292 tao
    {
2341 1360 tao
2342 2098 jones
        // Get the document indicated
2343
        String valtext = null;
2344
        DBConnection dbConn = null;
2345
        int serialNumber = -1;
2346 1292 tao
2347 2098 jones
        try {
2348
            valtext = ((String[]) params.get("valtext"))[0];
2349
        } catch (Exception nullpe) {
2350 1360 tao
2351 2098 jones
            String docid = null;
2352
            try {
2353
                // Find the document id number
2354
                docid = ((String[]) params.get("docid"))[0];
2355 1360 tao
2356 2098 jones
                // Get the document indicated from the db
2357
                DocumentImpl xmldoc = new DocumentImpl(docid);
2358
                valtext = xmldoc.toString();
2359 688 bojilova
2360 2098 jones
            } catch (NullPointerException npe) {
2361 1360 tao
2362 2098 jones
                out.println("<error>Error getting document ID: " + docid
2363
                        + "</error>");
2364
                //if ( conn != null ) { util.returnConnection(conn); }
2365
                return;
2366
            } catch (Exception e) {
2367 688 bojilova
2368 2098 jones
                out.println(e.getMessage());
2369
            }
2370
        }
2371 688 bojilova
2372 2098 jones
        try {
2373
            // get a connection from the pool
2374
            dbConn = DBConnectionPool
2375
                    .getDBConnection("MetaCatServlet.handleValidateAction");
2376
            serialNumber = dbConn.getCheckOutSerialNumber();
2377 2752 jones
            DBValidate valobj = new DBValidate(dbConn);
2378 2098 jones
            boolean valid = valobj.validateString(valtext);
2379 1360 tao
2380 2098 jones
            // set content type and other response header fields first
2381 688 bojilova
2382 2098 jones
            out.println(valobj.returnErrors());
2383 731 bojilova
2384 2098 jones
        } catch (NullPointerException npe2) {
2385
            // set content type and other response header fields first
2386 1360 tao
2387 2098 jones
            out.println("<error>Error validating document.</error>");
2388
        } catch (Exception e) {
2389 731 bojilova
2390 2098 jones
            out.println(e.getMessage());
2391
        } finally {
2392
            // Return db connection
2393
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2394
        }
2395
    }
2396 1360 tao
2397 2098 jones
    /**
2398
     * Handle "getrevsionanddoctype" action Given a docid, return it's current
2399
     * revision and doctype from data base The output is String look like
2400
     * "rev;doctype"
2401
     */
2402
    private void handleGetRevisionAndDocTypeAction(PrintWriter out,
2403
            Hashtable params)
2404
    {
2405
        // To store doc parameter
2406
        String[] docs = new String[10];
2407
        // Store a single doc id
2408
        String givenDocId = null;
2409
        // Get docid from parameters
2410
        if (params.containsKey("docid")) {
2411
            docs = (String[]) params.get("docid");
2412
        }
2413
        // Get first docid form string array
2414
        givenDocId = docs[0];
2415 731 bojilova
2416 2098 jones
        try {
2417
            // Make sure there is a docid
2418
            if (givenDocId == null || givenDocId.equals("")) { throw new Exception(
2419
                    "User didn't specify docid!"); }//if
2420 1360 tao
2421 2098 jones
            // Create a DBUtil object
2422
            DBUtil dbutil = new DBUtil();
2423
            // Get a rev and doctype
2424
            String revAndDocType = dbutil
2425
                    .getCurrentRevisionAndDocTypeForGivenDocument(givenDocId);
2426
            out.println(revAndDocType);
2427 731 bojilova
2428 2098 jones
        } catch (Exception e) {
2429
            // Handle exception
2430
            out.println("<?xml version=\"1.0\"?>");
2431
            out.println("<error>");
2432
            out.println(e.getMessage());
2433
            out.println("</error>");
2434
        }
2435 302 bojilova
2436 2098 jones
    }
2437 1360 tao
2438 2098 jones
    /**
2439
     * Handle "getaccesscontrol" action. Read Access Control List from db
2440
     * connection in XML format
2441
     */
2442
    private void handleGetAccessControlAction(PrintWriter out,
2443
            Hashtable params, HttpServletResponse response, String username,
2444
            String[] groupnames)
2445
    {
2446
        DBConnection dbConn = null;
2447
        int serialNumber = -1;
2448
        String docid = ((String[]) params.get("docid"))[0];
2449 302 bojilova
2450 2098 jones
        try {
2451 1360 tao
2452 2098 jones
            // get connection from the pool
2453
            dbConn = DBConnectionPool
2454
                    .getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2455
            serialNumber = dbConn.getCheckOutSerialNumber();
2456
            AccessControlList aclobj = new AccessControlList(dbConn);
2457
            String acltext = aclobj.getACL(docid, username, groupnames);
2458
            out.println(acltext);
2459 302 bojilova
2460 2098 jones
        } catch (Exception e) {
2461
            out.println("<?xml version=\"1.0\"?>");
2462
            out.println("<error>");
2463
            out.println(e.getMessage());
2464
            out.println("</error>");
2465
        } finally {
2466
            // Retrun db connection to pool
2467
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
2468
        }
2469 1360 tao
    }
2470
2471 2098 jones
    /**
2472
     * Handle the "getprincipals" action. Read all principals from
2473
     * authentication scheme in XML format
2474
     */
2475
    private void handleGetPrincipalsAction(PrintWriter out, String user,
2476
            String password)
2477
    {
2478
        try {
2479
            AuthSession auth = new AuthSession();
2480
            String principals = auth.getPrincipals(user, password);
2481
            out.println(principals);
2482 302 bojilova
2483 2098 jones
        } catch (Exception e) {
2484
            out.println("<?xml version=\"1.0\"?>");
2485
            out.println("<error>");
2486
            out.println(e.getMessage());
2487
            out.println("</error>");
2488
        }
2489
    }
2490 699 bojilova
2491 2098 jones
    /**
2492
     * Handle "getdoctypes" action. Read all doctypes from db connection in XML
2493
     * format
2494
     */
2495
    private void handleGetDoctypesAction(PrintWriter out, Hashtable params,
2496
            HttpServletResponse response)
2497
    {
2498
        try {
2499
            DBUtil dbutil = new DBUtil();
2500
            String doctypes = dbutil.readDoctypes();
2501
            out.println(doctypes);
2502
        } catch (Exception e) {
2503
            out.println("<?xml version=\"1.0\"?>");
2504
            out.println("<error>");
2505
            out.println(e.getMessage());
2506
            out.println("</error>");
2507
        }
2508
    }
2509 1360 tao
2510 2098 jones
    /**
2511
     * Handle the "getdtdschema" action. Read DTD or Schema file for a given
2512
     * doctype from Metacat catalog system
2513
     */
2514
    private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
2515
            HttpServletResponse response)
2516
    {
2517 699 bojilova
2518 2098 jones
        String doctype = null;
2519
        String[] doctypeArr = (String[]) params.get("doctype");
2520 699 bojilova
2521 2098 jones
        // get only the first doctype specified in the list of doctypes
2522
        // it could be done for all doctypes in that list
2523
        if (doctypeArr != null) {
2524
            doctype = ((String[]) params.get("doctype"))[0];
2525
        }
2526 699 bojilova
2527 2098 jones
        try {
2528
            DBUtil dbutil = new DBUtil();
2529
            String dtdschema = dbutil.readDTDSchema(doctype);
2530
            out.println(dtdschema);
2531 1360 tao
2532 2098 jones
        } catch (Exception e) {
2533
            out.println("<?xml version=\"1.0\"?>");
2534
            out.println("<error>");
2535
            out.println(e.getMessage());
2536
            out.println("</error>");
2537
        }
2538 699 bojilova
2539 1360 tao
    }
2540
2541 2098 jones
    /**
2542
     * Handle the "getlastdocid" action. Get the latest docid with rev number
2543
     * from db connection in XML format
2544
     */
2545
    private void handleGetMaxDocidAction(PrintWriter out, Hashtable params,
2546
            HttpServletResponse response)
2547
    {
2548 699 bojilova
2549 2098 jones
        String scope = ((String[]) params.get("scope"))[0];
2550
        if (scope == null) {
2551
            scope = ((String[]) params.get("username"))[0];
2552
        }
2553 793 bojilova
2554 2098 jones
        try {
2555 1217 tao
2556 2098 jones
            DBUtil dbutil = new DBUtil();
2557
            String lastDocid = dbutil.getMaxDocid(scope);
2558
            out.println("<?xml version=\"1.0\"?>");
2559
            out.println("<lastDocid>");
2560
            out.println("  <scope>" + scope + "</scope>");
2561
            out.println("  <docid>" + lastDocid + "</docid>");
2562
            out.println("</lastDocid>");
2563 793 bojilova
2564 2098 jones
        } catch (Exception e) {
2565
            out.println("<?xml version=\"1.0\"?>");
2566
            out.println("<error>");
2567
            out.println(e.getMessage());
2568
            out.println("</error>");
2569
        }
2570 1217 tao
    }
2571 1360 tao
2572 2098 jones
    /**
2573 2113 jones
     * Print a report from the event log based on filter parameters passed in
2574
     * from the web.
2575 2169 sgarg
     *
2576 2113 jones
     * @param params the parameters from the web request
2577
     * @param request the http request object for getting request details
2578
     * @param response the http response object for writing output
2579
     */
2580
    private void handleGetLogAction(Hashtable params, HttpServletRequest request,
2581 2558 sgarg
            HttpServletResponse response, String username, String[] groups)
2582 2113 jones
    {
2583 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2584 2113 jones
        try {
2585 2312 jones
            response.setContentType("text/xml");
2586
            PrintWriter out = response.getWriter();
2587 2347 sgarg
2588 2312 jones
            // Check that the user is authenticated as an administrator account
2589 2558 sgarg
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2590 2312 jones
                out.print("<error>");
2591 2347 sgarg
                out.print("The user \"" + username +
2592 2312 jones
                        "\" is not authorized for this action.");
2593
                out.print("</error>");
2594
                return;
2595 2113 jones
            }
2596 2347 sgarg
2597 2312 jones
            // Get all of the parameters in the correct formats
2598
            String[] ipAddress = (String[])params.get("ipaddress");
2599
            String[] principal = (String[])params.get("principal");
2600
            String[] docid = (String[])params.get("docid");
2601
            String[] event = (String[])params.get("event");
2602
            String[] startArray = (String[]) params.get("start");
2603
            String[] endArray = (String[]) params.get("end");
2604
            String start = null;
2605
            String end = null;
2606
            if (startArray != null) {
2607
                start = startArray[0];
2608
            }
2609
            if (endArray != null) {
2610
                end = endArray[0];
2611
            }
2612
            Timestamp startDate = null;
2613
            Timestamp endDate = null;
2614
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2615
            try {
2616
                if (start != null) {
2617
                    startDate = new Timestamp((format.parse(start)).getTime());
2618
                }
2619
                if (end != null) {
2620
                    endDate = new Timestamp((format.parse(end)).getTime());
2621
                }
2622
            } catch (ParseException e) {
2623
                System.out.println("Failed to created Timestamp from input.");
2624
            }
2625 2347 sgarg
2626 2312 jones
            // Request the report by passing the filter parameters
2627
            out.println(EventLog.getInstance().getReport(ipAddress, principal,
2628
                    docid, event, startDate, endDate));
2629
            out.close();
2630
        } catch (IOException e) {
2631 2663 sgarg
            logMetacat.error(
2632
                    "Could not open http response for writing: " + e.getMessage());
2633 2113 jones
        }
2634 2312 jones
    }
2635 2169 sgarg
2636 2312 jones
    /**
2637
     * Rebuild the index for one or more documents. If the docid parameter is
2638
     * provided, rebuild for just that one document or list of documents. If
2639
     * not, then rebuild the index for all documents in the xml_documents
2640
     * table.
2641
     *
2642
     * @param params the parameters from the web request
2643
     * @param request the http request object for getting request details
2644
     * @param response the http response object for writing output
2645
     * @param username the username of the authenticated user
2646
     */
2647 2347 sgarg
    private void handleBuildIndexAction(Hashtable params,
2648 2312 jones
            HttpServletRequest request, HttpServletResponse response,
2649 2558 sgarg
            String username, String[] groups)
2650 2312 jones
    {
2651 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2652
2653 2312 jones
        // Get all of the parameters in the correct formats
2654
        String[] docid = (String[])params.get("docid");
2655
2656
        // Rebuild the indices for appropriate documents
2657 2113 jones
        try {
2658
            response.setContentType("text/xml");
2659
            PrintWriter out = response.getWriter();
2660 2347 sgarg
2661 2312 jones
            // Check that the user is authenticated as an administrator account
2662 2558 sgarg
            if (!MetaCatUtil.isAdministrator(username, groups)) {
2663 2312 jones
                out.print("<error>");
2664 2347 sgarg
                out.print("The user \"" + username +
2665 2312 jones
                        "\" is not authorized for this action.");
2666
                out.print("</error>");
2667
                return;
2668
            }
2669
2670
            // Process the documents
2671
            out.println("<success>");
2672
            if (docid == null || docid.length == 0) {
2673
                // Process all of the documents
2674
                try {
2675
                    Vector documents = getDocumentList();
2676
                    Iterator it = documents.iterator();
2677
                    while (it.hasNext()) {
2678
                        String id = (String) it.next();
2679
                        buildDocumentIndex(id, out);
2680
                    }
2681
                } catch (SQLException se) {
2682
                    out.print("<error>");
2683
                    out.print(se.getMessage());
2684
                    out.println("</error>");
2685
                }
2686
            } else {
2687
                // Only process the requested documents
2688
                for (int i = 0; i < docid.length; i++) {
2689
                    buildDocumentIndex(docid[i], out);
2690
                }
2691
            }
2692
            out.println("</success>");
2693 2113 jones
            out.close();
2694
        } catch (IOException e) {
2695 2663 sgarg
            logMetacat.error(
2696 2169 sgarg
                    "Could not open http response for writing: "
2697 2663 sgarg
                    + e.getMessage());
2698 2113 jones
        }
2699
    }
2700 2169 sgarg
2701 2113 jones
    /**
2702 2347 sgarg
     * Build the index for one document by reading the document and
2703 2312 jones
     * calling its buildIndex() method.
2704
     *
2705
     * @param docid the document (with revision) to rebuild
2706
     * @param out the PrintWriter to which output is printed
2707
     */
2708
    private void buildDocumentIndex(String docid, PrintWriter out)
2709
    {
2710
        try {
2711
            DocumentImpl doc = new DocumentImpl(docid, false);
2712
            doc.buildIndex();
2713
            out.print("<docid>" + docid);
2714
            out.println("</docid>");
2715
        } catch (McdbException me) {
2716
            out.print("<error>");
2717
            out.print(me.getMessage());
2718
            out.println("</error>");
2719
        }
2720
    }
2721
2722
    /**
2723 2098 jones
     * Handle documents passed to metacat that are encoded using the
2724
     * "multipart/form-data" mime type. This is typically used for uploading
2725
     * data files which may be binary and large.
2726
     */
2727
    private void handleMultipartForm(HttpServletRequest request,
2728
            HttpServletResponse response)
2729
    {
2730 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2731 2098 jones
        PrintWriter out = null;
2732
        String action = null;
2733 793 bojilova
2734 2098 jones
        // Parse the multipart form, and save the parameters in a Hashtable and
2735
        // save the FileParts in a hashtable
2736 798 jones
2737 2098 jones
        Hashtable params = new Hashtable();
2738
        Hashtable fileList = new Hashtable();
2739
        int sizeLimit = (new Integer(MetaCatUtil.getOption("datafilesizelimit")))
2740
                .intValue();
2741 2663 sgarg
        logMetacat.info(
2742 2753 jones
                "The size limit of uploaded data files is: " + sizeLimit);
2743 798 jones
2744 2098 jones
        try {
2745
            MultipartParser mp = new MultipartParser(request,
2746
                    sizeLimit * 1024 * 1024);
2747
            Part part;
2748
            while ((part = mp.readNextPart()) != null) {
2749
                String name = part.getName();
2750 798 jones
2751 2098 jones
                if (part.isParam()) {
2752
                    // it's a parameter part
2753
                    ParamPart paramPart = (ParamPart) part;
2754
                    String value = paramPart.getStringValue();
2755
                    params.put(name, value);
2756
                    if (name.equals("action")) {
2757
                        action = value;
2758
                    }
2759
                } else if (part.isFile()) {
2760
                    // it's a file part
2761
                    FilePart filePart = (FilePart) part;
2762
                    fileList.put(name, filePart);
2763 798 jones
2764 2098 jones
                    // Stop once the first file part is found, otherwise going
2765
                    // onto the
2766
                    // next part prevents access to the file contents. So...for
2767
                    // upload
2768
                    // to work, the datafile must be the last part
2769
                    break;
2770
                }
2771
            }
2772
        } catch (IOException ioe) {
2773
            try {
2774
                out = response.getWriter();
2775
            } catch (IOException ioe2) {
2776 2663 sgarg
                logMetacat.fatal("Fatal Error: couldn't get response output stream.");
2777 2098 jones
            }
2778
            out.println("<?xml version=\"1.0\"?>");
2779
            out.println("<error>");
2780
            out.println("Error: problem reading multipart data.");
2781
            out.println("</error>");
2782 798 jones
        }
2783
2784 2098 jones
        // Get the session information
2785
        String username = null;
2786
        String password = null;
2787
        String[] groupnames = null;
2788
        String sess_id = null;
2789 798 jones
2790 2098 jones
        // be aware of session expiration on every request
2791
        HttpSession sess = request.getSession(true);
2792
        if (sess.isNew()) {
2793
            // session expired or has not been stored b/w user requests
2794
            username = "public";
2795
            sess.setAttribute("username", username);
2796
        } else {
2797
            username = (String) sess.getAttribute("username");
2798
            password = (String) sess.getAttribute("password");
2799
            groupnames = (String[]) sess.getAttribute("groupnames");
2800
            try {
2801
                sess_id = (String) sess.getId();
2802
            } catch (IllegalStateException ise) {
2803
                System.out
2804
                        .println("error in  handleMultipartForm: this shouldn't "
2805
                                + "happen: the session should be valid: "
2806
                                + ise.getMessage());
2807
            }
2808
        }
2809 1360 tao
2810 2098 jones
        // Get the out stream
2811
        try {
2812
            out = response.getWriter();
2813 798 jones
        } catch (IOException ioe2) {
2814 2663 sgarg
            logMetacat.error("Fatal Error: couldn't get response "
2815
                    + "output stream.");
2816 798 jones
        }
2817 1360 tao
2818 2098 jones
        if (action.equals("upload")) {
2819
            if (username != null && !username.equals("public")) {
2820
                handleUploadAction(request, out, params, fileList, username,
2821
                        groupnames);
2822
            } else {
2823 1360 tao
2824 2098 jones
                out.println("<?xml version=\"1.0\"?>");
2825
                out.println("<error>");
2826
                out.println("Permission denied for " + action);
2827
                out.println("</error>");
2828
            }
2829
        } else {
2830
            /*
2831
             * try { out = response.getWriter(); } catch (IOException ioe2) {
2832
             * System.err.println("Fatal Error: couldn't get response output
2833
             * stream.");
2834
             */
2835
            out.println("<?xml version=\"1.0\"?>");
2836
            out.println("<error>");
2837
            out.println(
2838
                    "Error: action not registered.  Please report this error.");
2839
            out.println("</error>");
2840
        }
2841
        out.close();
2842 798 jones
    }
2843
2844 2098 jones
    /**
2845
     * Handle the upload action by saving the attached file to disk and
2846
     * registering it in the Metacat db
2847
     */
2848
    private void handleUploadAction(HttpServletRequest request,
2849
            PrintWriter out, Hashtable params, Hashtable fileList,
2850
            String username, String[] groupnames)
2851 1041 tao
    {
2852 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2853 2098 jones
        //PrintWriter out = null;
2854
        //Connection conn = null;
2855
        String action = null;
2856
        String docid = null;
2857 798 jones
2858 2098 jones
        /*
2859
         * response.setContentType("text/xml"); try { out =
2860
         * response.getWriter(); } catch (IOException ioe2) {
2861
         * System.err.println("Fatal Error: couldn't get response output
2862
         * stream.");
2863
         */
2864 798 jones
2865 2098 jones
        if (params.containsKey("docid")) {
2866
            docid = (String) params.get("docid");
2867
        }
2868 798 jones
2869 2098 jones
        // Make sure we have a docid and datafile
2870
        if (docid != null && fileList.containsKey("datafile")) {
2871 2753 jones
            logMetacat.info("Uploading data docid: " + docid);
2872 2098 jones
            // Get a reference to the file part of the form
2873
            FilePart filePart = (FilePart) fileList.get("datafile");
2874
            String fileName = filePart.getFileName();
2875 2753 jones
            logMetacat.info("Uploading filename: " + fileName);
2876 2098 jones
            // Check if the right file existed in the uploaded data
2877
            if (fileName != null) {
2878 1360 tao
2879 2098 jones
                try {
2880 2663 sgarg
                    //logMetacat.info("Upload datafile " + docid
2881 2098 jones
                    // +"...", 10);
2882
                    //If document get lock data file grant
2883
                    if (DocumentImpl.getDataFileLockGrant(docid)) {
2884
                        // Save the data file to disk using "docid" as the name
2885 2752 jones
                        String datafilepath = MetaCatUtil.getOption("datafilepath");
2886
                        File dataDirectory = new File(datafilepath);
2887 2098 jones
                        dataDirectory.mkdirs();
2888 2749 tao
                        File newFile = null;
2889
                        long size = 0;
2890
                        try
2891
                        {
2892
                          newFile = new File(dataDirectory, docid);
2893
                          size = filePart.writeTo(newFile);
2894
2895
//                        register the file in the database (which generates
2896
                          // an exception
2897
                          //if the docid is not acceptable or other untoward
2898
                          // things happen
2899
                          DocumentImpl.registerDocument(fileName, "BIN", docid,
2900
                                username, groupnames);
2901
                        }
2902
                        catch (Exception ee)
2903
                        {
2904
                           //detelte the file to create
2905
                            newFile.delete();
2906
                            throw ee;
2907
                        }
2908 1360 tao
2909 2169 sgarg
                        EventLog.getInstance().log(request.getRemoteAddr(),
2910 2102 jones
                                username, docid, "upload");
2911 2098 jones
                        // Force replication this data file
2912
                        // To data file, "insert" and update is same
2913
                        // The fourth parameter is null. Because it is
2914
                        // notification server
2915
                        // and this method is in MetaCatServerlet. It is
2916
                        // original command,
2917
                        // not get force replication info from another metacat
2918
                        ForceReplicationHandler frh = new ForceReplicationHandler(
2919
                                docid, "insert", false, null);
2920 1360 tao
2921 2098 jones
                        // set content type and other response header fields
2922
                        // first
2923
                        out.println("<?xml version=\"1.0\"?>");
2924
                        out.println("<success>");
2925
                        out.println("<docid>" + docid + "</docid>");
2926
                        out.println("<size>" + size + "</size>");
2927
                        out.println("</success>");
2928
                    }
2929
2930
                } catch (Exception e) {
2931 2749 tao
2932 2098 jones
                    out.println("<?xml version=\"1.0\"?>");
2933
                    out.println("<error>");
2934
                    out.println(e.getMessage());
2935
                    out.println("</error>");
2936
                }
2937
            } else {
2938
                // the field did not contain a file
2939
                out.println("<?xml version=\"1.0\"?>");
2940
                out.println("<error>");
2941
                out.println("The uploaded data did not contain a valid file.");
2942
                out.println("</error>");
2943
            }
2944
        } else {
2945
            // Error bcse docid missing or file missing
2946
            out.println("<?xml version=\"1.0\"?>");
2947
            out.println("<error>");
2948
            out.println("The uploaded data did not contain a valid docid "
2949
                    + "or valid file.");
2950
            out.println("</error>");
2951 798 jones
        }
2952 2098 jones
    }
2953 1360 tao
2954 2098 jones
    /*
2955
     * A method to handle set access action
2956
     */
2957
    private void handleSetAccessAction(PrintWriter out, Hashtable params,
2958
            String username)
2959 1041 tao
    {
2960 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2961 2098 jones
        String[] docList = null;
2962
        String[] principalList = null;
2963
        String[] permissionList = null;
2964
        String[] permTypeList = null;
2965
        String[] permOrderList = null;
2966
        String permission = null;
2967
        String permType = null;
2968
        String permOrder = null;
2969
        Vector errorList = new Vector();
2970
        String error = null;
2971
        Vector successList = new Vector();
2972
        String success = null;
2973 1716 berkley
2974 2098 jones
        // Get parameters
2975
        if (params.containsKey("docid")) {
2976
            docList = (String[]) params.get("docid");
2977
        }
2978
        if (params.containsKey("principal")) {
2979
            principalList = (String[]) params.get("principal");
2980
        }
2981
        if (params.containsKey("permission")) {
2982
            permissionList = (String[]) params.get("permission");
2983 1716 berkley
2984 2098 jones
        }
2985
        if (params.containsKey("permType")) {
2986
            permTypeList = (String[]) params.get("permType");
2987 1716 berkley
2988 2098 jones
        }
2989
        if (params.containsKey("permOrder")) {
2990
            permOrderList = (String[]) params.get("permOrder");
2991 1716 berkley
2992 2098 jones
        }
2993 1716 berkley
2994 2098 jones
        // Make sure the parameter is not null
2995
        if (docList == null || principalList == null || permTypeList == null
2996
                || permissionList == null) {
2997
            error = "Please check your parameter list, it should look like: "
2998
                    + "?action=setaccess&docid=pipeline.1.1&principal=public"
2999
                    + "&permission=read&permType=allow&permOrder=allowFirst";
3000
            errorList.addElement(error);
3001
            outputResponse(successList, errorList, out);
3002
            return;
3003
        }
3004 1716 berkley
3005 2098 jones
        // Only select first element for permission, type and order
3006
        permission = permissionList[0];
3007
        permType = permTypeList[0];
3008
        if (permOrderList != null) {
3009
            permOrder = permOrderList[0];
3010
        }
3011 1716 berkley
3012 2098 jones
        // Get package doctype set
3013
        Vector packageSet = MetaCatUtil.getOptionList(MetaCatUtil
3014
                .getOption("packagedoctypeset"));
3015
        //debug
3016
        if (packageSet != null) {
3017
            for (int i = 0; i < packageSet.size(); i++) {
3018 2753 jones
                logMetacat.debug("doctype in package set: "
3019 2663 sgarg
                        + (String) packageSet.elementAt(i));
3020 2098 jones
            }
3021
        }
3022 1716 berkley
3023 2098 jones
        // handle every accessionNumber
3024
        for (int i = 0; i < docList.length; i++) {
3025
            String accessionNumber = docList[i];
3026
            String owner = null;
3027
            String publicId = null;
3028
            // Get document owner and public id
3029
            try {
3030
                owner = getFieldValueForDoc(accessionNumber, "user_owner");
3031
                publicId = getFieldValueForDoc(accessionNumber, "doctype");
3032
            } catch (Exception e) {
3033 2663 sgarg
                logMetacat.error("Error in handleSetAccessAction: "
3034
                        + e.getMessage());
3035 2098 jones
                error = "Error in set access control for document - "
3036
                        + accessionNumber + e.getMessage();
3037
                errorList.addElement(error);
3038
                continue;
3039
            }
3040
            //check if user is the owner. Only owner can do owner
3041
            if (username == null || owner == null || !username.equals(owner)) {
3042
                error = "User - " + username
3043
                        + " does not have permission to set "
3044
                        + "access control for docid - " + accessionNumber;
3045
                errorList.addElement(error);
3046
                continue;
3047
            }
3048 1716 berkley
3049 2098 jones
            // If docid publicid is BIN data file or other beta4, 6 package
3050
            // document
3051
            // we could not do set access control. Because we don't want
3052
            // inconsistent
3053
            // to its access docuemnt
3054
            if (publicId != null && packageSet != null
3055
                    && packageSet.contains(publicId)) {
3056
                error = "Could not set access control to document "
3057
                        + accessionNumber
3058
                        + "because it is in a pakcage and it has a access file for it";
3059
                errorList.addElement(error);
3060
                continue;
3061
            }
3062 1716 berkley
3063 2098 jones
            // for every principle
3064
            for (int j = 0; j < principalList.length; j++) {
3065
                String principal = principalList[j];
3066
                try {
3067
                    //insert permission
3068
                    AccessControlForSingleFile accessControl = new AccessControlForSingleFile(
3069
                            accessionNumber, principal, permission, permType,
3070
                            permOrder);
3071
                    accessControl.insertPermissions();
3072
                    success = "Set access control to document "
3073
                            + accessionNumber + " successfully";
3074
                    successList.addElement(success);
3075
                } catch (Exception ee) {
3076 2663 sgarg
                    logMetacat.error(
3077 2098 jones
                            "Erorr in handleSetAccessAction2: "
3078 2663 sgarg
                                    + ee.getMessage());
3079 2098 jones
                    error = "Faild to set access control for document "
3080
                            + accessionNumber + " because " + ee.getMessage();
3081
                    errorList.addElement(error);
3082
                    continue;
3083
                }
3084
            }
3085 1369 tao
        }
3086 2098 jones
        outputResponse(successList, errorList, out);
3087
    }
3088 1716 berkley
3089 2098 jones
    /*
3090
     * A method try to determin a docid's public id, if couldn't find null will
3091
     * be returned.
3092
     */
3093
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
3094
            throws Exception
3095 1369 tao
    {
3096 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3097 2098 jones
        if (accessionNumber == null || accessionNumber.equals("")
3098
                || fieldName == null || fieldName.equals("")) { throw new Exception(
3099
                "Docid or field name was not specified"); }
3100 1716 berkley
3101 2098 jones
        PreparedStatement pstmt = null;
3102
        ResultSet rs = null;
3103
        String fieldValue = null;
3104
        String docId = null;
3105
        DBConnection conn = null;
3106
        int serialNumber = -1;
3107 1716 berkley
3108 2098 jones
        // get rid of revision if access number has
3109
        docId = MetaCatUtil.getDocIdFromString(accessionNumber);
3110
        try {
3111
            //check out DBConnection
3112
            conn = DBConnectionPool
3113
                    .getDBConnection("MetaCatServlet.getPublicIdForDoc");
3114
            serialNumber = conn.getCheckOutSerialNumber();
3115
            pstmt = conn.prepareStatement("SELECT " + fieldName
3116
                    + " FROM xml_documents " + "WHERE docid = ? ");
3117 1716 berkley
3118 2098 jones
            pstmt.setString(1, docId);
3119
            pstmt.execute();
3120
            rs = pstmt.getResultSet();
3121
            boolean hasRow = rs.next();
3122
            int perm = 0;
3123
            if (hasRow) {
3124
                fieldValue = rs.getString(1);
3125
            } else {
3126
                throw new Exception("Could not find document: "
3127
                        + accessionNumber);
3128
            }
3129
        } catch (Exception e) {
3130 2663 sgarg
            logMetacat.error(
3131 2098 jones
                    "Exception in MetacatServlet.getPublicIdForDoc: "
3132 2663 sgarg
                            + e.getMessage());
3133 2098 jones
            throw e;
3134
        } finally {
3135
            try {
3136
                rs.close();
3137
                pstmt.close();
3138 1716 berkley
3139 2098 jones
            } finally {
3140
                DBConnectionPool.returnDBConnection(conn, serialNumber);
3141
            }
3142
        }
3143
        return fieldValue;
3144 1369 tao
    }
3145 1716 berkley
3146 2098 jones
    /*
3147 2312 jones
     * Get the list of documents from the database and return the list in an
3148
     * Vector of identifiers.
3149
     *
3150
     * @ returns the array of identifiers
3151
     */
3152
    private Vector getDocumentList() throws SQLException
3153
    {
3154 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3155 2312 jones
        Vector docList = new Vector();
3156
        PreparedStatement pstmt = null;
3157
        ResultSet rs = null;
3158
        DBConnection conn = null;
3159
        int serialNumber = -1;
3160
3161
        try {
3162
            //check out DBConnection
3163
            conn = DBConnectionPool
3164
                    .getDBConnection("MetaCatServlet.getDocumentList");
3165
            serialNumber = conn.getCheckOutSerialNumber();
3166
            pstmt = conn.prepareStatement("SELECT docid, rev"
3167
                    + " FROM xml_documents ");
3168
            pstmt.execute();
3169
            rs = pstmt.getResultSet();
3170
            while (rs.next()) {
3171
                String docid = rs.getString(1);
3172
                String rev = rs.getString(2);
3173
                docList.add(docid + "." + rev);
3174
            }
3175
        } catch (SQLException e) {
3176 2663 sgarg
            logMetacat.error(
3177 2312 jones
                    "Exception in MetacatServlet.getDocumentList: "
3178 2663 sgarg
                            + e.getMessage());
3179 2312 jones
            throw e;
3180
        } finally {
3181
            try {
3182
                rs.close();
3183
                pstmt.close();
3184
3185
            } catch (SQLException se) {
3186 2663 sgarg
                logMetacat.error(
3187 2312 jones
                    "Exception in MetacatServlet.getDocumentList: "
3188 2663 sgarg
                            + se.getMessage());
3189 2312 jones
                throw se;
3190
            } finally {
3191
                DBConnectionPool.returnDBConnection(conn, serialNumber);
3192
            }
3193
        }
3194
        return docList;
3195
    }
3196
3197
    /*
3198 2098 jones
     * A method to output setAccess action result
3199
     */
3200
    private void outputResponse(Vector successList, Vector errorList,
3201
            PrintWriter out)
3202 1369 tao
    {
3203 2098 jones
        boolean error = false;
3204
        boolean success = false;
3205
        // Output prolog
3206
        out.println(PROLOG);
3207
        // output success message
3208
        if (successList != null) {
3209
            for (int i = 0; i < successList.size(); i++) {
3210
                out.println(SUCCESS);
3211
                out.println((String) successList.elementAt(i));
3212
                out.println(SUCCESSCLOSE);
3213
                success = true;
3214
            }
3215
        }
3216
        // output error message
3217
        if (errorList != null) {
3218
            for (int i = 0; i < errorList.size(); i++) {
3219
                out.println(ERROR);
3220
                out.println((String) errorList.elementAt(i));
3221
                out.println(ERRORCLOSE);
3222
                error = true;
3223
            }
3224
        }
3225 1716 berkley
3226 2098 jones
        // if no error and no success info, send a error that nothing happened
3227
        if (!error && !success) {
3228
            out.println(ERROR);
3229
            out.println("Nothing happend for setaccess action");
3230
            out.println(ERRORCLOSE);
3231
        }
3232 1369 tao
    }
3233 2582 tao
3234
    /**
3235
     * Method to get session table which store the session info
3236
     * @return
3237
     */
3238
    public static Hashtable getSessionHash()
3239
    {
3240
        return sessionHash;
3241
    }
3242 2648 tao
3243
    /*
3244
     * If the given docid only have one seperter, we need
3245
     * append rev for it. The rev come from xml_documents
3246
     */
3247
    private static String appendRev(String docid) throws Exception
3248
    {
3249 2753 jones
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3250 2648 tao
        String newAccNum = null;
3251
        String separator = MetaCatUtil.getOption("accNumSeparator");
3252
        int firstIndex = docid.indexOf(separator);
3253
        int lastIndex = docid.lastIndexOf(separator);
3254
        if (firstIndex == lastIndex)
3255
        {
3256
3257
           //only one seperater
3258
            int rev = DBUtil.getLatestRevisionInDocumentTable(docid);
3259
            if (rev == -1)
3260
            {
3261 2776 tao
                throw new Exception("the requested docid '"
3262
                        + docid+ "' does not exist");
3263 2648 tao
            }
3264
            else
3265
            {
3266
                newAccNum = docid+ separator+ rev;
3267
            }
3268
        }
3269
        else
3270
        {
3271
            // in other suituation we don't change the docid
3272
            newAccNum = docid;
3273
        }
3274 2776 tao
        //logMetacat.debug("The docid will be read is "+newAccNum);
3275 2648 tao
        return newAccNum;
3276 2912 harris
  }
3277 46 jones
}