Project

General

Profile

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

    
27
package edu.ucsb.nceas.metacat;
28

    
29
import java.io.IOException;
30
import java.io.PrintWriter;
31
import java.sql.PreparedStatement;
32
import java.sql.ResultSet;
33
import java.sql.SQLException;
34
import java.util.Enumeration;
35
import java.util.Hashtable;
36
import java.util.Timer;
37
import java.util.Vector;
38

    
39
import javax.servlet.ServletConfig;
40
import javax.servlet.ServletContext;
41
import javax.servlet.ServletException;
42
import javax.servlet.ServletOutputStream;
43
import javax.servlet.http.HttpServlet;
44
import javax.servlet.http.HttpServletRequest;
45
import javax.servlet.http.HttpServletResponse;
46
import javax.servlet.http.HttpSession;
47

    
48
import org.apache.log4j.Logger;
49
import org.apache.log4j.PropertyConfigurator;
50

    
51
import edu.ucsb.nceas.metacat.database.DBConnection;
52
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
53
import edu.ucsb.nceas.metacat.database.DatabaseService;
54
import edu.ucsb.nceas.metacat.properties.PropertyService;
55
import edu.ucsb.nceas.metacat.properties.SkinPropertyService;
56
import edu.ucsb.nceas.metacat.replication.ReplicationService;
57
import edu.ucsb.nceas.metacat.service.ServiceService;
58
import edu.ucsb.nceas.metacat.service.SessionService;
59
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
60
import edu.ucsb.nceas.metacat.shared.BaseException;
61
import edu.ucsb.nceas.metacat.shared.HandlerException;
62
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
63
import edu.ucsb.nceas.metacat.shared.ServiceException;
64
import edu.ucsb.nceas.metacat.spatial.SpatialFeatureSchema;
65
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
66
import edu.ucsb.nceas.metacat.util.AuthUtil;
67
import edu.ucsb.nceas.metacat.util.ConfigurationUtil;
68
import edu.ucsb.nceas.metacat.util.DocumentUtil;
69
import edu.ucsb.nceas.metacat.util.ErrorSendingErrorException;
70
import edu.ucsb.nceas.metacat.util.RequestUtil;
71
import edu.ucsb.nceas.metacat.util.ResponseUtil;
72
import edu.ucsb.nceas.metacat.util.SessionData;
73
import edu.ucsb.nceas.metacat.util.SystemUtil;
74
import edu.ucsb.nceas.metacat.workflow.WorkflowSchedulerClient;
75
import edu.ucsb.nceas.utilities.FileUtil;
76
import edu.ucsb.nceas.utilities.GeneralPropertyException;
77
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
78
import edu.ucsb.nceas.utilities.UtilException;
79

    
80
/**
81
 * A metadata catalog server implemented as a Java Servlet
82
 *
83
 * Valid actions are:
84
 * 
85
 * action=login
86
 *     username
87
 *     password
88
 *     qformat
89
 * action=logout
90
 *     qformat
91
 * action=query -- query the values of all elements and attributes and return a result set of nodes
92
 *     meta_file_id --
93
 *     returndoctype --
94
 *     filterdoctype --
95
 *     returnfield --
96
 *     owner --
97
 *     site --
98
 *     operator --
99
 *     casesensitive --
100
 *     searchmode --
101
 *     anyfield --
102
 * action=spatial_query -- run a spatial query.  these queries may include any of the
103
 *                         queries supported by the WFS / WMS standards
104
 *     xmax --
105
 *     ymax --
106
 *     xmin --
107
 *     ymin --
108
 *     skin --
109
 *     pagesize --
110
 *     pagestart --
111
 * action=squery -- structured query (see pathquery.dtd)
112
 *     query --
113
 *     pagesize --
114
 *     pagestart --
115
 * action=export -- export a zip format for data packadge
116
 *     docid -- 
117
 * action=read -- read any metadata/data file from Metacat and from Internet
118
 *     archiveEntryName --
119
 *     docid --
120
 *     qformat --
121
 *     metadatadocid --
122
 * action=readinlinedata -- read inline data only
123
 *     inlinedataid
124
 * action=insert -- insert an XML document into the database store
125
 *     qformat -- 
126
 *     docid --
127
 *     doctext --
128
 *     dtdtext --
129
 * action=insertmultipart -- insert an xml document into the database using multipart encoding
130
 *     qformat -- 
131
 *     docid --
132
 * action=update -- update an XML document that is in the database store
133
 *     qformat -- 
134
 *     docid --
135
 *     doctext --
136
 *     dtdtext --
137
 * action=delete -- delete an XML document from the database store
138
 *     docid --
139
 * action=validate -- validate the xml contained in valtext
140
 *     valtext --
141
 *     docid --
142
 * action=setaccess -- change access permissions for a user on a document.
143
 *     docid --
144
 *     principal --
145
 *     permission --
146
 *     permType --
147
 *     permOrder --
148
 * action=getaccesscontrol -- retrieve acl info for Metacat document
149
 *     docid -- 
150
 * action=getprincipals -- retrieve a list of principals in XML
151
 * action=getalldocids -- retrieves a list of all docids registered with the system
152
 *     scope --
153
 * action=getlastdocid --
154
 *     scope --
155
 *     username --
156
 * action=isregistered -- checks to see if the provided docid is registered
157
 *     docid --
158
 * action=getrevisionanddoctype -- get a document's revision and doctype from database 
159
 *     docid --
160
 * action=getversion -- 
161
 * action=getdoctypes -- retrieve all doctypes (publicID) 
162
 * action=getdtdschema -- retrieve a DTD or Schema file
163
 *     doctype --
164
 * action=getlog -- get a report of events that have occurred in the system
165
 *     ipAddress --  filter on one or more IP addresses>
166
 *     principal -- filter on one or more principals (LDAP DN syntax)
167
 *     docid -- filter on one or more document identifiers (with revision)
168
 *     event -- filter on event type (e.g., read, insert, update, delete)
169
 *     start -- filter out events before the start date-time
170
 *     end -- filter out events before the end date-time
171
 * action=getloggedinuserinfo -- get user info for the currently logged in user
172
 *     ipAddress --  filter on one or more IP addresses>
173
 *     principal -- filter on one or more principals (LDAP DN syntax)
174
 *     docid -- filter on one or more document identifiers (with revision)
175
 *     event -- filter on event type (e.g., read, insert, update, delete)
176
 *     start -- filter out events before the start date-time
177
 *     end -- filter out events before the end date-time
178
 * action=shrink -- Shrink the database connection pool size if it has grown and 
179
 *                  extra connections are no longer being used.
180
 * action=buildindex --
181
 *     docid --
182
 * action=refreshServices --
183
 * action=scheduleWorkflow -- Schedule a workflow to be run.  Scheduling a workflow 
184
 *                            registers it with the scheduling engine and creates a row
185
 *                            in the scheduled_job table.  Note that this may be 
186
 *                            extracted into a separate servlet.
187
 *     delay -- The amount of time from now before the workflow should be run.  The 
188
 *              delay can be expressed in number of seconds, minutes, hours and days, 
189
 *              for instance 30s, 2h, etc.
190
 *     starttime -- The time that the workflow should first run.  If both are provided
191
 *                  this takes precedence over delay.  The time should be expressed as: 
192
 *                  MM/dd/yyyy HH:mm:ss with the timezone assumed to be that of the OS.
193
 *     endtime -- The time when the workflow should end. The time should be expressed as: 
194
 *                  MM/dd/yyyy HH:mm:ss with the timezone assumed to be that of the OS.
195
 *     intervalvalue -- The numeric value of the interval between runs
196
 *     intervalunit -- The unit of the interval between runs.  Can be s, m, h, d for 
197
 *                     seconds, minutes, hours and days respectively
198
 *     workflowid -- The lsid of the workflow that we want to schedule.  This workflow
199
 *                   must already exist in the database.
200
 *     karid -- The karid for the workflow that we want to schedule.
201
 *     workflowname -- The name of the workflow.
202
 *     forwardto -- If provided, forward to this page when processing is done.
203
 *     qformat -- If provided, render results using the stylesheets associated with
204
 *                this skin.  Default is xml.
205
 * action=unscheduleWorkflow -- Unschedule a workflow.  Unscheduling a workflow 
206
 *                            removes it from the scheduling engine and changes the 
207
 *                            status in the scheduled_job table to " unscheduled.  Note 
208
 *                            that this may be extracted into a separate servlet.
209
 *     workflowjobname -- The job ID for the workflow run that we want to unschedule.  This
210
 *                      is held in the database as scheduled_job.name
211
 *     forwardto -- If provided, forward to this page when processing is done.
212
 *     qformat -- If provided, render results using the stylesheets associated with
213
 *                this skin.  Default is xml.
214
 * action=rescheduleWorkflow -- Unschedule a workflow.  Rescheduling a workflow 
215
 *                            registers it with the scheduling engine and changes the 
216
 *                            status in the scheduled_job table to " scheduled.  Note 
217
 *                            that this may be extracted into a separate servlet.
218
 *     workflowjobname -- The job ID for the workflow run that we want to reschedule.  This
219
 *                      is held in the database as scheduled_job.name
220
 *     forwardto -- If provided, forward to this page when processing is done.
221
 *     qformat -- If provided, render results using the stylesheets associated with
222
 *                this skin.  Default is xml.
223
 * action=deleteScheduledWorkflow -- Delete a workflow.  Deleting a workflow 
224
 *                            removes it from the scheduling engine and changes the 
225
 *                            status in the scheduled_job table to " deleted.  Note 
226
 *                            that this may be extracted into a separate servlet.
227
 *     workflowjobname -- The job ID for the workflow run that we want to delete.  This
228
 *                      is held in the database as scheduled_job.name
229
 *     forwardto -- If provided, forward to this page when processing is done.
230
 *     qformat -- If provided, render results using the stylesheets associated with
231
 *                this skin.  Default is xml.
232
 *     
233
 *     
234
 * Here are some of the common parameters for actions
235
 *     doctype -- document type list returned by the query (publicID) 
236
 *     qformat=xml -- display resultset from query in XML 
237
 *     qformat=html -- display resultset from query in HTML 
238
 *     qformat=zip -- zip resultset from query
239
 *     docid=34 -- display the document with the document ID number 34 
240
 *     doctext -- XML text of the document to load into the database 
241
 *     acltext -- XML access text for a document to load into the database 
242
 *     dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog 
243
 *     query -- actual query text (to go with 'action=query' or 'action=squery')
244
 *     valtext -- XML text to be validated 
245
 *     scope --can limit the query by the scope of the id
246
 *     docid --the docid to check
247
 *     datadoc -- data document name (id)
248
 */
249
public class MetaCatServlet extends HttpServlet {
250

    
251
	private static final long serialVersionUID = 1L;
252
	private Timer timer = null;
253
    private static boolean _firstHalfInitialized = false;
254
    private static boolean _fullyInitialized = false;
255
    private MetacatHandler handler = null;
256
    
257
    // Constants -- these should be final in a servlet
258
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
259
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
260
    public static final String EML2KEYWORD = ":eml";
261
    private static final String FALSE = "false";
262
    private static final String TRUE  = "true";
263
    private static String LOG_CONFIG_NAME = null;
264
    public static final String APPLICATION_NAME = "metacat";
265
    
266
    /**
267
     * Initialize the servlet by creating appropriate database connections
268
     */
269
    public void init(ServletConfig config) throws ServletException {
270
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
271
    	try {
272
    		if(_firstHalfInitialized) {
273
    			return;
274
    		}
275
    		
276
            super.init(config);
277
            
278
            ServletContext context = config.getServletContext();
279
            context.setAttribute("APPLICATION_NAME", APPLICATION_NAME);
280
            
281
            ServiceService serviceService = ServiceService.getInstance(context);
282
            logMetacat.debug("MetaCatServlet.init - ServiceService singleton created " + serviceService);
283
            
284
            // Initialize the properties file
285
            String dirPath = ServiceService.getRealConfigDir();
286
            
287
            LOG_CONFIG_NAME = dirPath + "/log4j.properties";
288
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
289
            
290
            // Register preliminary services
291
            ServiceService.registerService("PropertyService", PropertyService.getInstance(context));         
292
            ServiceService.registerService("SkinPropertyService", SkinPropertyService.getInstance());
293
            ServiceService.registerService("SessionService", SessionService.getInstance()); 
294
            
295
    		// Check to see if the user has requested to bypass configuration 
296
            // (dev option) and check see if metacat has been configured.
297
    		// If both are false then stop the initialization
298
            if (!ConfigurationUtil.bypassConfiguration() && !ConfigurationUtil.isMetacatConfigured()) {
299
            	return;
300
            }  
301
            
302
            _firstHalfInitialized = true;
303
            
304
            initSecondHalf(context);
305
            
306
    	} catch (ServiceException se) {
307
        	String errorMessage = 
308
        		"Service problem while intializing MetaCat Servlet: " + se.getMessage();
309
            logMetacat.error("MetaCatServlet.init - " + errorMessage);
310
            throw new ServletException(errorMessage);
311
        } catch (MetacatUtilException mue) {
312
        	String errorMessage = "Metacat utility problem while intializing MetaCat Servlet: " 
313
        		+ mue.getMessage();
314
            logMetacat.error("MetaCatServlet.init - " + errorMessage);
315
            throw new ServletException(errorMessage);
316
        } 
317
    }
318

    
319
            
320
	/**
321
	 * Initialize the remainder of the servlet. This is the part that can only
322
	 * be initialized after metacat properties have been configured
323
	 * 
324
	 * @param context
325
	 *            the servlet context of MetaCatServlet
326
	 */
327
	public void initSecondHalf(ServletContext context) throws ServletException {
328
		
329
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
330

    
331
		try {			
332
			ServiceService.registerService("DatabaseService", DatabaseService.getInstance());
333
			
334
			// initialize DBConnection pool
335
			DBConnectionPool connPool = DBConnectionPool.getInstance();
336
			logMetacat.debug("MetaCatServlet.initSecondHalf - DBConnection pool initialized: " + connPool.toString());
337
			
338
			ServiceService.registerService("XMLSchemaService", XMLSchemaService.getInstance());
339
//			ServiceService.registerService("SchedulerService", SchedulerService.getInstance());
340

    
341
			// check if eml201 document were corrected or not. if not, correct eml201 documents.
342
			// Before Metacat 1.8.1, metacat uses tag RELEASE_EML_2_0_1_UPDATE_6 as eml
343
			// schema, which accidentily points to wrong version of eml-resource.xsd.
344
			String correctedEML201Doc = PropertyService.getProperty("document.eml201DocumentCorrected");
345
			if (correctedEML201Doc != null && correctedEML201Doc.equals(FALSE)) {
346
				logMetacat.info("MetaCatServlet.initSecondHalf - Start to correct eml201 documents");
347
				EML201DocumentCorrector correct = new EML201DocumentCorrector();
348
				boolean success = correct.run();
349
				if (success) {
350
					PropertyService.setProperty("document.eml201DocumentCorrected", TRUE);
351
				}
352
				logMetacat.info("MetaCatServlet.initSecondHalf - Finish to correct eml201 documents");
353
			}
354

    
355
			// Index the paths specified in the metacat.properties
356
			checkIndexPaths();
357

    
358
			// initiate the indexing Queue
359
			IndexingQueue.getInstance();
360

    
361
			// start the IndexingThread if indexingTimerTaskTime more than 0.
362
			// It will index all the documents not yet indexed in the database
363
			int indexingTimerTaskTime = Integer.parseInt(PropertyService
364
					.getProperty("database.indexingTimerTaskTime"));
365
			int delayTime = Integer.parseInt(PropertyService
366
					.getProperty("database.indexingInitialDelay"));
367

    
368
			if (indexingTimerTaskTime > 0) {
369
				timer = new Timer();
370
				timer.schedule(new IndexingTimerTask(), delayTime, indexingTimerTaskTime);
371
			}
372
			
373
			/*
374
			 * If spatial option is turned on and set to regenerate the spatial
375
			 * cache on restart, trigger the harvester regeneratation method
376
			 */
377
			if (PropertyService.getProperty("spatial.runSpatialOption").equals("true")) {
378
			//      && PropertyService.getProperty("spatial.regenerateCacheOnRestart").equals("true")) {
379
			        
380
				// Begin timer
381
				long before = System.currentTimeMillis();
382

    
383
                // if either the point or polygon shape files do not exist, then regenerate the entire spatial cache
384
                // this may be expensive with many documents
385
                if (FileUtil.getFileStatus(SpatialFeatureSchema.pointShpUri) == FileUtil.DOES_NOT_EXIST) {      
386
                    SpatialHarvester sh = new SpatialHarvester();
387
                    sh.regenerate();
388
                    sh.destroy();
389
                }
390

    
391
				// After running the first time, we want to to set
392
				// regenerateCacheOnRestart to false
393
				// so that it does not regenerate the cache every time tomcat is
394
				// restarted
395
//				PropertyService.setProperty("spatial.regenerateCacheOnRestart", "false");
396

    
397
				// End timer
398
				long after = System.currentTimeMillis();
399
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial Harvester Time  " 
400
						+ (after - before) + "ms");
401

    
402
			} else {
403
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial cache is not set to regenerate on restart");
404
			}
405
		
406
			// Set up the replication log file by setting the "replication.logfile.name" 
407
			// system property and reconfiguring the log4j property configurator.
408
			String replicationLogPath = PropertyService.getProperty("replication.logdir") 
409
				+ FileUtil.getFS() + ReplicationService.REPLICATION_LOG_FILE_NAME;				
410
			
411
			if (FileUtil.getFileStatus(replicationLogPath) == FileUtil.DOES_NOT_EXIST) {
412
				FileUtil.createFile(replicationLogPath);
413
			}
414

    
415
			if (FileUtil.getFileStatus(replicationLogPath) < FileUtil.EXISTS_READ_WRITABLE) {
416
				logMetacat.error("MetaCatServlet.initSecondHalf - Replication log file: " + replicationLogPath 
417
						+ " does not exist read/writable.");
418
			}
419
			
420
			System.setProperty("replication.logfile.name", replicationLogPath);			
421
			PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
422
			
423
	         //Initialize Metacat Handler
424
            handler = new MetacatHandler(getServletContext(), timer);
425

    
426
			MetacatHandler.set_sitemapScheduled(false);
427

    
428
			_fullyInitialized = true;
429
			
430
			logMetacat.warn("MetaCatServlet.initSecondHalf - Metacat (" + MetacatVersion.getVersionID()
431
					+ ") initialized.");
432
			
433
		} catch (SQLException e) {
434
			String errorMessage = "SQL problem while intializing MetaCat Servlet: "
435
					+ e.getMessage();
436
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
437
			throw new ServletException(errorMessage);
438
		} catch (IOException ie) {
439
			String errorMessage = "IO problem while intializing MetaCat Servlet: "
440
					+ ie.getMessage();
441
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
442
			throw new ServletException(errorMessage);
443
		} catch (GeneralPropertyException gpe) {
444
			String errorMessage = "Could not retrieve property while intializing MetaCat Servlet: "
445
					+ gpe.getMessage();
446
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
447
			throw new ServletException(errorMessage);
448
		} catch (ServiceException se) {
449
			String errorMessage = "Service problem while intializing MetaCat Servlet: "
450
				+ se.getMessage();
451
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
452
			throw new ServletException(errorMessage);
453
		} catch (UtilException ue) {
454
        	String errorMessage = "Utility problem while intializing MetaCat Servlet: " 
455
        		+ ue.getMessage();
456
            logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
457
            throw new ServletException(errorMessage);
458
        } 
459
	}
460
    
461
    /**
462
	 * Close all db connections from the pool
463
	 */
464
    public void destroy() {
465
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
466
    	
467
    	ServiceService.stopAllServices();
468
    	
469
        // Close all db connection
470
        logMetacat.warn("MetaCatServlet.destroy - Destroying MetacatServlet");
471
        timer.cancel();
472
        IndexingQueue.getInstance().setMetacatRunning(false);
473
        DBConnectionPool.release();
474
    }
475
    
476
    /** Handle "GET" method requests from HTTP clients */
477
    public void doGet(HttpServletRequest request, HttpServletResponse response)
478
    throws ServletException, IOException {
479
        
480
        // Process the data and send back the response
481
        handleGetOrPost(request, response);
482
    }
483
    
484
    /** Handle "POST" method requests from HTTP clients */
485
    public void doPost(HttpServletRequest request, HttpServletResponse response)
486
    throws ServletException, IOException {
487
        
488
        // Process the data and send back the response
489
        handleGetOrPost(request, response);
490
    }
491
    
492
    /**
493
	 * Index the paths specified in the metacat.properties
494
	 */
495
    private void checkIndexPaths() {
496
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
497

    
498
        Vector<String> pathsForIndexing = null;
499
        try {  
500
        	pathsForIndexing = SystemUtil.getPathsForIndexing();
501
        }
502
        catch (MetacatUtilException ue) {
503
        	pathsForIndexing = null;
504
            logMetacat.error("MetaCatServlet.checkIndexPaths - not find index paths.  Setting " 
505
            		+ "pathsForIndexing to null: " + ue.getMessage());
506
        }
507
        
508
        if (pathsForIndexing != null && !pathsForIndexing.isEmpty()) {
509
            
510
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Indexing paths specified in metacat.properties....");
511
            
512
            DBConnection conn = null;
513
            int serialNumber = -1;
514
            PreparedStatement pstmt = null;
515
            PreparedStatement pstmt1 = null;
516
            ResultSet rs = null;
517
            
518
            for (String pathIndex : pathsForIndexing) {
519
                logMetacat.debug("MetaCatServlet.checkIndexPaths - Checking if '" + pathIndex  + "' is indexed.... ");
520
                
521
                try {
522
                    //check out DBConnection
523
                    conn = DBConnectionPool.
524
                            getDBConnection("MetaCatServlet.checkIndexPaths");
525
                    serialNumber = conn.getCheckOutSerialNumber();
526
                    
527
                    pstmt = conn.prepareStatement(
528
                            "SELECT * FROM xml_path_index " + "WHERE path = ?");
529
                    pstmt.setString(1, pathIndex);
530
                    
531
                    pstmt.execute();
532
                    rs = pstmt.getResultSet();
533
                    
534
                    if (!rs.next()) {
535
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - not indexed yet.");
536
                        rs.close();
537
                        pstmt.close();
538
                        conn.increaseUsageCount(1);
539
                        
540
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Inserting following path in xml_path_index: "
541
                                + pathIndex);
542
                        if(pathIndex.indexOf("@")<0){
543
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
544
                                    + "n.nodedata, n.nodedatanumerical, n.parentnodeid"
545
                                    + " FROM xml_nodes n, xml_index i WHERE"
546
                                    + " i.path = ? and n.parentnodeid=i.nodeid and"
547
                                    + " n.nodetype LIKE 'TEXT' order by n.parentnodeid");
548
                        } else {
549
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
550
                                    + "n.nodedata, n.nodedatanumerical, n.parentnodeid"
551
                                    + " FROM xml_nodes n, xml_index i WHERE"
552
                                    + " i.path = ? and n.nodeid=i.nodeid and"
553
                                    + " n.nodetype LIKE 'ATTRIBUTE' order by n.parentnodeid");
554
                        }
555
                        pstmt.setString(1, pathIndex);
556
                        pstmt.execute();
557
                        rs = pstmt.getResultSet();
558
                        
559
                        int count = 0;
560
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Executed the select statement for: "
561
                                + pathIndex);
562
                        
563
                        try {
564
                            while (rs.next()) {
565
                                
566
                                String docid = rs.getString(1);
567
                                String nodedata = rs.getString(2);
568
                                float nodedatanumerical = rs.getFloat(3);
569
                                int parentnodeid = rs.getInt(4);
570
                                
571
                                if (!nodedata.trim().equals("")) {
572
                                    pstmt1 = conn.prepareStatement(
573
                                            "INSERT INTO xml_path_index"
574
                                            + " (docid, path, nodedata, "
575
                                            + "nodedatanumerical, parentnodeid)"
576
                                            + " VALUES (?, ?, ?, ?, ?)");
577
                                    
578
                                    pstmt1.setString(1, docid);
579
                                    pstmt1.setString(2, pathIndex);
580
                                    pstmt1.setString(3, nodedata);
581
                                    pstmt1.setFloat(4, nodedatanumerical);
582
                                    pstmt1.setInt(5, parentnodeid);
583
                                    
584
                                    pstmt1.execute();
585
                                    pstmt1.close();
586
                                    
587
                                    count++;
588
                                    
589
                                }
590
                            }
591
                        } catch (Exception e) {
592
                            logMetacat.error("MetaCatServlet.checkIndexPaths - Exception:" + e.getMessage());
593
                            e.printStackTrace();
594
                        }
595
                        
596
                        rs.close();
597
                        pstmt.close();
598
                        conn.increaseUsageCount(1);
599
                        
600
                        logMetacat.info("MetaCatServlet.checkIndexPaths - Indexed " + count + " records from xml_nodes for '"
601
                                + pathIndex + "'");
602
                        
603
                    } else {
604
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - already indexed.");
605
                    }
606
                    
607
                    rs.close();
608
                    pstmt.close();
609
                    conn.increaseUsageCount(1);
610
                    
611
                } catch (Exception e) {
612
                    logMetacat.error("MetaCatServlet.checkIndexPaths - Error in MetaCatServlet.checkIndexPaths: "
613
                            + e.getMessage());
614
                }finally {
615
                    //check in DBonnection
616
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
617
                }
618
                
619
                
620
            }
621
            
622
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Path Indexing Completed");
623
        }
624
    }
625
    
626
    /**
627
	 * Control servlet response depending on the action parameter specified
628
	 */
629
	@SuppressWarnings("unchecked")
630
	private void handleGetOrPost(HttpServletRequest request,
631
			HttpServletResponse response) throws ServletException, IOException {
632
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
633

    
634
		// Update the last update time for this user if they are not new
635
		HttpSession httpSession = request.getSession(false);
636
		if (httpSession != null) {
637
			SessionService.touchSession(httpSession.getId());
638
		}
639
		
640
		// Each time metacat is called, check to see if metacat has been 
641
		// configured. If not then forward to the administration servlet
642
		if (!ConfigurationUtil.isMetacatConfigured()) {
643
			try {
644
				RequestUtil.forwardRequest(request, response, "/admin?action=configure", null);
645
				return;
646
			} catch (MetacatUtilException mue) {
647
				logMetacat.error("MetacatServlet.handleGetOrPost - utility error when forwarding to " + 
648
						"configuration screen: " + mue.getMessage());
649
				throw new ServletException("MetacatServlet.handleGetOrPost - utility error when forwarding to " + 
650
						"configuration screen: " + mue.getMessage());
651
			}
652
		}
653

    
654
		// if we get here, metacat is configured.  If we have not completed the 
655
		// second half of the initialization, do so now.  This allows us to initially
656
		// configure metacat without a restart.
657
		if (!_fullyInitialized) {
658
			initSecondHalf(request.getSession().getServletContext());
659
		}
660
		
661
		/*
662
		 * logMetacat.debug("Connection pool size: "
663
		 * +connPool.getSizeOfDBConnectionPool(),10); logMetacat.debug("Free
664
		 * DBConnection number: "
665
		 */
666
		// If all DBConnection in the pool are free and DBConnection pool
667
		// size is greater than initial value, shrink the connection pool
668
		// size to initial value
669
		DBConnectionPool.shrinkDBConnectionPoolSize();
670

    
671
		// Debug message to print out the method which have a busy DBConnection
672
		try {
673
			@SuppressWarnings("unused")
674
			DBConnectionPool pool = DBConnectionPool.getInstance();
675
//			pool.printMethodNameHavingBusyDBConnection();
676
		} catch (SQLException e) {
677
			logMetacat.error("MetaCatServlet.handleGetOrPost - Error in MetacatServlet.handleGetOrPost: " + e.getMessage());
678
			e.printStackTrace();
679
		}
680

    
681
		try {
682
			String ctype = request.getContentType();
683
			
684
			if (ctype != null && ctype.startsWith("multipart/form-data")) {
685
				handler.handleMultipartForm(request, response);
686
				return;
687
			} 
688

    
689
			String name = null;
690
			String[] value = null;
691
			String[] docid = new String[3];
692
			Hashtable<String, String[]> params = new Hashtable<String, String[]>();
693

    
694
			// Check if this is a simple read request that doesn't use the
695
			// "action" syntax
696
			// These URLs are of the form:
697
			// http://localhost:8180/knb/metacat/docid/skinname
698
			// e.g., http://localhost:8180/knb/metacat/test.1.1/knb
699
			String pathInfo = request.getPathInfo();
700
			if (pathInfo != null) {
701
				String[] path = pathInfo.split("/");
702
				if (path.length > 1) {
703
					String docidToRead = path[1];
704
					String docs[] = new String[1];
705
					docs[0] = docidToRead;
706
					logMetacat.debug("MetaCatServlet.handleGetOrPost - READING DOCID FROM PATHINFO: " + docs[0]);
707
					params.put("docid", docs);
708
					String skin = null;
709
					if (path.length > 2) {
710
						skin = path[2];
711
						String skins[] = new String[1];
712
						skins[0] = skin;
713
						params.put("qformat", skins);
714
					}
715
					handler.handleReadAction(params, request, response, "public", null, null);
716
					return;
717
				}
718
			}
719

    
720
			Enumeration<String> paramlist = 
721
				(Enumeration<String>) request.getParameterNames();
722
			while (paramlist.hasMoreElements()) {
723

    
724
				name = paramlist.nextElement();
725
				value = request.getParameterValues(name);
726

    
727
				// Decode the docid and mouse click information
728
				// THIS IS OBSOLETE -- I THINK -- REMOVE THIS BLOCK
729
				// 4/12/2007d
730
				// MBJ
731
				if (name.endsWith(".y")) {
732
					docid[0] = name.substring(0, name.length() - 2);
733
					params.put("docid", docid);
734
					name = "ypos";
735
				}
736
				if (name.endsWith(".x")) {
737
					name = "xpos";
738
				}
739

    
740
				params.put(name, value);
741
			}
742

    
743
			// handle param is emptpy
744
			if (params.isEmpty() || params == null) {
745
				return;
746
			}
747

    
748
			// if the user clicked on the input images, decode which image
749
			// was clicked then set the action.
750
			if (params.get("action") == null) {
751
				PrintWriter out = response.getWriter();
752
				response.setContentType("text/xml");
753
				out.println("<?xml version=\"1.0\"?>");
754
				out.println("<error>");
755
				out.println("Action not specified");
756
				out.println("</error>");
757
				out.close();
758
				return;
759
			}
760

    
761
			String action = (params.get("action"))[0];
762
			logMetacat.info("MetaCatServlet.handleGetOrPost - Action is: " + action);
763

    
764
			// This block handles session management for the servlet
765
			// by looking up the current session information for all actions
766
			// other than "login" and "logout"
767
			String userName = null;
768
			String password = null;
769
			String[] groupNames = null;
770
			String sessionId = null;
771
			name = null;
772

    
773
			// handle login action
774
			if (action.equals("login")) {
775
				PrintWriter out = response.getWriter();
776
				handler.handleLoginAction(out, params, request, response);
777
				out.close();
778

    
779
				// handle logout action
780
			} else if (action.equals("logout")) {
781
				PrintWriter out = response.getWriter();
782
				handler.handleLogoutAction(out, params, request, response);
783
				out.close();
784

    
785
				// handle shrink DBConnection request
786
			} else if (action.equals("validatesession")) {
787
				PrintWriter out = response.getWriter();
788
				String idToValidate = null;
789
				String idsToValidate[] = params.get("sessionid");
790
				if (idsToValidate != null) {
791
					idToValidate = idsToValidate[0];
792
				}
793
				SessionService.validateSession(out, response, idToValidate);
794
				out.close();
795

    
796
				// handle shrink DBConnection request
797
			} else if (action.equals("shrink")) {
798
				PrintWriter out = response.getWriter();
799
				boolean success = false;
800
				// If all DBConnection in the pool are free and DBConnection
801
				// pool
802
				// size is greater than initial value, shrink the connection
803
				// pool
804
				// size to initial value
805
				success = DBConnectionPool.shrinkConnectionPoolSize();
806
				if (success) {
807
					// if successfully shrink the pool size to initial value
808
					out.println("DBConnection Pool shrunk successfully.");
809
				}// if
810
				else {
811
					out.println("DBConnection pool not shrunk successfully.");
812
				}
813
				// close out put
814
				out.close();
815

    
816
				// aware of session expiration on every request
817
			} else {
818
				SessionData sessionData = RequestUtil.getSessionData(request);
819
				
820
				if (sessionData != null) {
821
					userName = sessionData.getUserName();
822
					password = sessionData.getPassword();
823
					groupNames = sessionData.getGroupNames();
824
					sessionId = sessionData.getId();
825
				}
826

    
827
				logMetacat.info("MetaCatServlet.handleGetOrPost - The user is : " + userName);
828
			}
829
			// Now that we know the session is valid, we can delegate the
830
			// request to a particular action handler
831
			if (action.equals("query")) {
832
				ServletOutputStream streamOut = response.getOutputStream();
833
				PrintWriter out = new PrintWriter(streamOut);
834
				handler.handleQuery(out, params, response, userName, groupNames, sessionId);
835
				out.close();
836
			} else if (action.equals("squery")) {
837
				ServletOutputStream streamOut = response.getOutputStream();
838
				PrintWriter out = new PrintWriter(streamOut);
839
				if (params.containsKey("query")) {
840
					handler.handleSQuery(out, params, response, userName, groupNames, sessionId);
841
					out.close();
842
				} else {
843
					out.println("Illegal action squery without \"query\" parameter");
844
					out.close();
845
				}
846
			} else if (action.trim().equals("spatial_query")) {
847

    
848
				logMetacat
849
						.debug("MetaCatServlet.handleGetOrPost - ******************* SPATIAL QUERY ********************");
850
				ServletOutputStream streamOut = response.getOutputStream();
851
				PrintWriter out = new PrintWriter(streamOut);
852
				handler.handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
853
				out.close();
854

    
855
			} else if (action.trim().equals("dataquery")) {
856

    
857
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* DATA QUERY ********************");
858
				handler.handleDataquery(params, response, sessionId);
859
			} else if (action.trim().equals("editcart")) {
860
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* EDIT CART ********************");
861
				handler.handleEditCart(params, response, sessionId);
862
			} else if (action.equals("export")) {
863

    
864
				handler.handleExportAction(params, response, userName, groupNames, password);
865
			} else if (action.equals("read")) {
866
				if (params.get("archiveEntryName") != null) {
867
					ArchiveHandler.getInstance().readArchiveEntry(params, request,
868
							response, userName, password, groupNames);
869
				} else {
870
					handler.handleReadAction(params, request, response, userName, password,
871
							groupNames);
872
				}
873
			} else if (action.equals("readinlinedata")) {
874
				handler.handleReadInlineDataAction(params, request, response, userName, password,
875
						groupNames);
876
			} else if (action.equals("insert") || action.equals("update")) {
877
				PrintWriter out = response.getWriter();
878
				if ((userName != null) && !userName.equals("public")) {
879
					handler.handleInsertOrUpdateAction(request, response, out, params, userName,
880
							groupNames);
881
				} else {
882
					response.setContentType("text/xml");
883
					out.println("<?xml version=\"1.0\"?>");
884
					out.println("<error>");
885
					out.println("Permission denied for user " + userName + " " + action);
886
					out.println("</error>");
887
				}
888
				out.close();
889
			} else if (action.equals("delete")) {
890
				PrintWriter out = response.getWriter();
891
				if ((userName != null) && !userName.equals("public")) {
892
					handler.handleDeleteAction(out, params, request, response, userName,
893
							groupNames);
894
				} else {
895
					response.setContentType("text/xml");
896
					out.println("<?xml version=\"1.0\"?>");
897
					out.println("<error>");
898
					out.println("Permission denied for " + action);
899
					out.println("</error>");
900
				}
901
				out.close();
902
			} else if (action.equals("validate")) {
903
				PrintWriter out = response.getWriter();
904
				handler.handleValidateAction(out, params);
905
				out.close();
906
			} else if (action.equals("setaccess")) {
907
				PrintWriter out = response.getWriter();
908
				handler.handleSetAccessAction(out, params, userName, request, response);
909
				out.close();
910
			} else if (action.equals("getaccesscontrol")) {
911
				PrintWriter out = response.getWriter();
912
				handler.handleGetAccessControlAction(out, params, response, userName, groupNames);
913
				out.close();
914
			} else if (action.equals("isauthorized")) {
915
				PrintWriter out = response.getWriter();
916
				DocumentUtil.isAuthorized(out, params, request, response);
917
				out.close();
918
			} else if (action.equals("getprincipals")) {
919
				PrintWriter out = response.getWriter();
920
				handler.handleGetPrincipalsAction(out, userName, password);
921
				out.close();
922
			} else if (action.equals("getdoctypes")) {
923
				PrintWriter out = response.getWriter();
924
				handler.handleGetDoctypesAction(out, params, response);
925
				out.close();
926
			} else if (action.equals("getdtdschema")) {
927
				PrintWriter out = response.getWriter();
928
				handler.handleGetDTDSchemaAction(out, params, response);
929
				out.close();
930
			} else if (action.equals("getlastdocid")) {
931
				PrintWriter out = response.getWriter();
932
				handler.handleGetMaxDocidAction(out, params, response);
933
				out.close();
934
			} else if (action.equals("getalldocids")) {
935
				PrintWriter out = response.getWriter();
936
				handler.handleGetAllDocidsAction(out, params, response);
937
				out.close();
938
			} else if (action.equals("isregistered")) {
939
				PrintWriter out = response.getWriter();
940
				handler.handleIdIsRegisteredAction(out, params, response);
941
				out.close();
942
			} else if (action.equals("getrevisionanddoctype")) {
943
				PrintWriter out = response.getWriter();
944
				handler.handleGetRevisionAndDocTypeAction(out, params);
945
				out.close();
946
			} else if (action.equals("getversion")) {
947
				response.setContentType("text/xml");
948
				PrintWriter out = response.getWriter();
949
				out.println(MetacatVersion.getVersionAsXml());
950
				out.close();
951
			} else if (action.equals("getlog")) {
952
				handler.handleGetLogAction(params, request, response, userName, groupNames);
953
			} else if (action.equals("getloggedinuserinfo")) {
954
				PrintWriter out = response.getWriter();
955
				response.setContentType("text/xml");
956
				out.println("<?xml version=\"1.0\"?>");
957
				out.println("\n<user>\n");
958
				out.println("\n<username>\n");
959
				out.println(userName);
960
				out.println("\n</username>\n");
961
				if (name != null) {
962
					out.println("\n<name>\n");
963
					out.println(name);
964
					out.println("\n</name>\n");
965
				}
966
				if (AuthUtil.isAdministrator(userName, groupNames)) {
967
					out.println("<isAdministrator></isAdministrator>\n");
968
				}
969
				if (AuthUtil.isModerator(userName, groupNames)) {
970
					out.println("<isModerator></isModerator>\n");
971
				}
972
				out.println("\n</user>\n");
973
				out.close();
974
			} else if (action.equals("buildindex")) {
975
				handler.handleBuildIndexAction(params, request, response, userName, groupNames);
976
			} else if (action.equals("login") || action.equals("logout")) {
977
				/*
978
				 * } else if (action.equals("protocoltest")) { String testURL =
979
				 * "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9"; try { testURL =
980
				 * ((String[]) params.get("url"))[0]; } catch (Throwable t) { }
981
				 * String phandler = System
982
				 * .getProperty("java.protocol.handler.pkgs");
983
				 * response.setContentType("text/html"); PrintWriter out =
984
				 * response.getWriter(); out.println("<body
985
				 * bgcolor=\"white\">"); out.println("<p>Handler property:
986
				 * <code>" + phandler + "</code></p>"); out.println("<p>Starting
987
				 * test for:<br>"); out.println(" " + testURL + "</p>"); try {
988
				 * URL u = new URL(testURL); out.println("<pre>");
989
				 * out.println("Protocol: " + u.getProtocol()); out.println("
990
				 * Host: " + u.getHost()); out.println(" Port: " + u.getPort());
991
				 * out.println(" Path: " + u.getPath()); out.println(" Ref: " +
992
				 * u.getRef()); String pquery = u.getQuery(); out.println("
993
				 * Query: " + pquery); out.println(" Params: "); if (pquery !=
994
				 * null) { Hashtable qparams =
995
				 * MetacatUtil.parseQuery(u.getQuery()); for (Enumeration en =
996
				 * qparams.keys(); en .hasMoreElements();) { String pname =
997
				 * (String) en.nextElement(); String pvalue = (String)
998
				 * qparams.get(pname); out.println(" " + pname + ": " + pvalue); } }
999
				 * out.println("</pre>"); out.println("</body>");
1000
				 * out.close(); } catch (MalformedURLException mue) {
1001
				 * System.out.println( "bad url from
1002
				 * MetacatServlet.handleGetOrPost");
1003
				 * out.println(mue.getMessage()); mue.printStackTrace(out);
1004
				 * out.close(); }
1005
				 */
1006
			} else if (action.equals("refreshServices")) {
1007
				// TODO MCD this interface is for testing. It should go through
1008
				// a ServiceService class and only work for an admin user. Move 
1009
				// to the MetacatAdminServlet
1010
				ServiceService.refreshService("XMLSchemaService");
1011
				return;
1012
			} else if (action.equals("scheduleWorkflow")) {
1013
				try {
1014
					WorkflowSchedulerClient.getInstance().scheduleJob(request, response,
1015
							params, userName, groupNames);
1016
					return;
1017
				} catch (BaseException be) {
1018
					ResponseUtil.sendErrorXML(response,
1019
							ResponseUtil.SCHEDULE_WORKFLOW_ERROR, be);
1020
					return;
1021
				}
1022
			} else if (action.equals("unscheduleWorkflow")) {
1023
				try {
1024
					WorkflowSchedulerClient.getInstance().unScheduleJob(request,
1025
							response, params, userName, groupNames);
1026
					return;
1027
				} catch (BaseException be) {
1028
					ResponseUtil.sendErrorXML(response,
1029
							ResponseUtil.UNSCHEDULE_WORKFLOW_ERROR, be);
1030
					return;
1031
				}
1032
			} else if (action.equals("rescheduleWorkflow")) {
1033
				try {
1034
					WorkflowSchedulerClient.getInstance().reScheduleJob(request,
1035
							response, params, userName, groupNames);
1036
					return;
1037
				} catch (BaseException be) {
1038
					ResponseUtil.sendErrorXML(response,
1039
							ResponseUtil.RESCHEDULE_WORKFLOW_ERROR, be);
1040
					return;
1041
				}
1042
			} else if (action.equals("getScheduledWorkflow")) {
1043
				try {
1044
					WorkflowSchedulerClient.getInstance().getJobs(request, response,
1045
							params, userName, groupNames);
1046
					return;
1047
				} catch (BaseException be) {
1048
					ResponseUtil.sendErrorXML(response,
1049
							ResponseUtil.GET_SCHEDULED_WORKFLOW_ERROR, be);
1050
					return;
1051
				}
1052
			} else if (action.equals("deleteScheduledWorkflow")) {
1053
				try {
1054
					WorkflowSchedulerClient.getInstance().deleteJob(request, response,
1055
							params, userName, groupNames);
1056
					return;
1057
				} catch (BaseException be) {
1058
					ResponseUtil.sendErrorXML(response,
1059
							ResponseUtil.DELETE_SCHEDULED_WORKFLOW_ERROR, be);
1060
					return;
1061
				}
1062

    
1063
			} else {
1064
				PrintWriter out = response.getWriter();
1065
				out.println("<?xml version=\"1.0\"?>");
1066
				out.println("<error>");
1067
				out.println("Error: action: " + action + " not registered.  Please report this error.");
1068
				out.println("</error>");
1069
				out.close();
1070
			}
1071

    
1072
			// Schedule the sitemap generator to run periodically
1073
			handler.scheduleSitemapGeneration(request);
1074

    
1075

    
1076
		} catch (PropertyNotFoundException pnfe) {
1077
			String errorString = "Critical property not found: " + pnfe.getMessage();
1078
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1079
			throw new ServletException(errorString);
1080
		} catch (MetacatUtilException ue) {
1081
			String errorString = "Utility error: " + ue.getMessage();
1082
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1083
			throw new ServletException(errorString);
1084
		} catch (ServiceException ue) {
1085
			String errorString = "Service error: " + ue.getMessage();
1086
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1087
			throw new ServletException(errorString);
1088
		} catch (HandlerException he) {
1089
			String errorString = "Handler error: " + he.getMessage();
1090
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1091
			throw new ServletException(errorString);
1092
		} catch (ErrorSendingErrorException esee) {
1093
			String errorString = "Error sending error message: " + esee.getMessage();
1094
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1095
			throw new ServletException(errorString);
1096
		} catch (ErrorHandledException ehe) {
1097
			// Nothing to do here.  We assume if we get here, the error has been 
1098
			// written to ouput.  Continue on and let it display.
1099
		} 
1100
	}
1101
    
1102
    /**
1103
     * Reports whether the MetaCatServlet has been fully initialized
1104
     * 
1105
     * @return true if fully intialized, false otherwise
1106
     */
1107
    public static boolean isFullyInitialized() {
1108
    	return _fullyInitialized;
1109
    }
1110
}
(41-41/61)