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: tao $'
9
 *     '$Date: 2013-10-09 20:53:26 -0700 (Wed, 09 Oct 2013) $'
10
 * '$Revision: 8303 $'
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.OutputStreamWriter;
31
import java.io.PrintWriter;
32
import java.io.Writer;
33
import java.sql.PreparedStatement;
34
import java.sql.ResultSet;
35
import java.sql.SQLException;
36
import java.sql.Timestamp;
37
import java.util.Enumeration;
38
import java.util.Hashtable;
39
import java.util.Timer;
40
import java.util.Vector;
41

    
42
import javax.servlet.ServletConfig;
43
import javax.servlet.ServletContext;
44
import javax.servlet.ServletException;
45
import javax.servlet.ServletOutputStream;
46
import javax.servlet.http.HttpServlet;
47
import javax.servlet.http.HttpServletRequest;
48
import javax.servlet.http.HttpServletResponse;
49
import javax.servlet.http.HttpSession;
50

    
51
import org.apache.log4j.Logger;
52
import org.apache.log4j.PropertyConfigurator;
53

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

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

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

    
327
            
328
	/**
329
	 * Initialize the remainder of the servlet. This is the part that can only
330
	 * be initialized after metacat properties have been configured
331
	 * 
332
	 * @param context
333
	 *            the servlet context of MetaCatServlet
334
	 */
335
	public void initSecondHalf(ServletContext context) throws ServletException {
336
		
337
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
338

    
339
		try {			
340
			ServiceService.registerService("DatabaseService", DatabaseService.getInstance());
341
			
342
			// initialize DBConnection pool
343
			DBConnectionPool connPool = DBConnectionPool.getInstance();
344
			logMetacat.debug("MetaCatServlet.initSecondHalf - DBConnection pool initialized: " + connPool.toString());
345
			
346
			// register the XML schema service
347
			ServiceService.registerService("XMLSchemaService", XMLSchemaService.getInstance());
348
			
349
			// check if eml201 document were corrected or not. if not, correct eml201 documents.
350
			// Before Metacat 1.8.1, metacat uses tag RELEASE_EML_2_0_1_UPDATE_6 as eml
351
			// schema, which accidentily points to wrong version of eml-resource.xsd.
352
			String correctedEML201Doc = PropertyService.getProperty("document.eml201DocumentCorrected");
353
			if (correctedEML201Doc != null && correctedEML201Doc.equals(FALSE)) {
354
				logMetacat.info("MetaCatServlet.initSecondHalf - Start to correct eml201 documents");
355
				EML201DocumentCorrector correct = new EML201DocumentCorrector();
356
				boolean success = correct.run();
357
				if (success) {
358
					PropertyService.setProperty("document.eml201DocumentCorrected", TRUE);
359
				}
360
				logMetacat.info("MetaCatServlet.initSecondHalf - Finish to correct eml201 documents");
361
			}
362

    
363
			// Index the paths specified in the metacat.properties
364
			checkIndexPaths();
365

    
366
			// initiate the indexing Queue
367
			IndexingQueue.getInstance();
368

    
369
			// start the IndexingThread if indexingTimerTaskTime more than 0.
370
			// It will index all the documents not yet indexed in the database
371
			int indexingTimerTaskTime = Integer.parseInt(PropertyService
372
					.getProperty("database.indexingTimerTaskTime"));
373
			int delayTime = Integer.parseInt(PropertyService
374
					.getProperty("database.indexingInitialDelay"));
375

    
376
			if (indexingTimerTaskTime > 0) {
377
				timer = new Timer();
378
				timer.schedule(new IndexingTimerTask(), delayTime, indexingTimerTaskTime);
379
			}
380
			
381
			/*
382
			 * If spatial option is turned on and set to regenerate the spatial
383
			 * cache on restart, trigger the harvester regeneratation method
384
			 */
385
			if (PropertyService.getProperty("spatial.runSpatialOption").equals("true") && 
386
					PropertyService.getProperty("spatial.regenerateCacheOnRestart").equals("true")) {
387

    
388
				// Begin timer
389
				long before = System.currentTimeMillis();
390

    
391
				// if either the point or polygon shape files do not exist, then regenerate the entire spatial cache
392
				// this may be expensive with many documents		
393
				SpatialHarvester sh = new SpatialHarvester();
394
				sh.regenerate();
395
				sh.destroy();
396

    
397
				// After running the first time, we want to to set
398
				// regenerateCacheOnRestart to false
399
				// so that it does not regenerate the cache every time tomcat is
400
				// restarted
401
				PropertyService.setProperty("spatial.regenerateCacheOnRestart", "false");
402

    
403
				// End timer
404
				long after = System.currentTimeMillis();
405
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial Harvester Time  " 
406
						+ (after - before) + "ms");
407

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

    
421
			if (FileUtil.getFileStatus(replicationLogPath) < FileUtil.EXISTS_READ_WRITABLE) {
422
				logMetacat.error("MetaCatServlet.initSecondHalf - Replication log file: " + replicationLogPath 
423
						+ " does not exist read/writable.");
424
			}
425
			
426
			System.setProperty("replication.logfile.name", replicationLogPath);			
427
			PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
428
			
429
			SessionService.getInstance().unRegisterAllSessions();
430
			
431
	         //Initialize Metacat Handler
432
            handler = new MetacatHandler(timer);
433

    
434
			handler.set_sitemapScheduled(false);
435
			
436
			// initialize the plugins
437
			MetacatHandlerPluginManager.getInstance();
438
			
439
			// initialize the HazelcastService
440
			ServiceService.registerService("HazelcastService", HazelcastService.getInstance());
441

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

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

    
650
		String requestEncoding = request.getCharacterEncoding();
651
		if (requestEncoding == null) {
652
			logMetacat.debug("null requestEncoding, setting to application default: " + DEFAULT_ENCODING);
653
			request.setCharacterEncoding(DEFAULT_ENCODING);
654
		}
655
		logMetacat.debug("requestEncoding: " + requestEncoding);
656
		
657
		// Update the last update time for this user if they are not new
658
		HttpSession httpSession = request.getSession(false);
659
		if (httpSession != null) {
660
		    SessionService.getInstance().touchSession(httpSession.getId());
661
		}
662
		
663
		// Each time metacat is called, check to see if metacat has been 
664
		// configured. If not then forward to the administration servlet
665
		if (!ConfigurationUtil.isMetacatConfigured()) {
666
			try {
667
				RequestUtil.forwardRequest(request, response, "/admin?action=configure", null);
668
				return;
669
			} catch (MetacatUtilException mue) {
670
				logMetacat.error("MetacatServlet.handleGetOrPost - utility error when forwarding to " + 
671
						"configuration screen: " + mue.getMessage());
672
				throw new ServletException("MetacatServlet.handleGetOrPost - utility error when forwarding to " + 
673
						"configuration screen: " + mue.getMessage());
674
			}
675
		}
676

    
677
		// if we get here, metacat is configured.  If we have not completed the 
678
		// second half of the initialization, do so now.  This allows us to initially
679
		// configure metacat without a restart.
680
		if (!_fullyInitialized) {
681
			initSecondHalf(request.getSession().getServletContext());
682
		}
683
		
684
		/*
685
		 * logMetacat.debug("Connection pool size: "
686
		 * +connPool.getSizeOfDBConnectionPool(),10); logMetacat.debug("Free
687
		 * DBConnection number: "
688
		 */
689
		// If all DBConnection in the pool are free and DBConnection pool
690
		// size is greater than initial value, shrink the connection pool
691
		// size to initial value
692
		DBConnectionPool.shrinkDBConnectionPoolSize();
693

    
694
		// Debug message to print out the method which have a busy DBConnection
695
		try {
696
			@SuppressWarnings("unused")
697
			DBConnectionPool pool = DBConnectionPool.getInstance();
698
//			pool.printMethodNameHavingBusyDBConnection();
699
		} catch (SQLException e) {
700
			logMetacat.error("MetaCatServlet.handleGetOrPost - Error in MetacatServlet.handleGetOrPost: " + e.getMessage());
701
			e.printStackTrace();
702
		}
703

    
704
		try {
705
			String ctype = request.getContentType();
706
			
707
			if (ctype != null && ctype.startsWith("multipart/form-data")) {
708
				handler.handleMultipartForm(request, response);
709
				return;
710
			} 
711

    
712
			String name = null;
713
			String[] value = null;
714
			String[] docid = new String[3];
715
			Hashtable<String, String[]> params = new Hashtable<String, String[]>();
716

    
717
			// Check if this is a simple read request that doesn't use the
718
			// "action" syntax
719
			// These URLs are of the form:
720
			// http://localhost:8180/metacat/metacat/docid/skinname
721
			// e.g., http://localhost:8180/metacat/metacat/test.1.1/knb
722
			String pathInfo = request.getPathInfo();
723
			if (pathInfo != null) {
724
				String[] path = pathInfo.split("/");
725
				if (path.length > 1) {
726
					String docidToRead = path[1];
727
					String docs[] = new String[1];
728
					docs[0] = docidToRead;
729
					logMetacat.debug("MetaCatServlet.handleGetOrPost - READING DOCID FROM PATHINFO: " + docs[0]);
730
					params.put("docid", docs);
731
					String skin = null;
732
					if (path.length > 2) {
733
						skin = path[2];
734
						String skins[] = new String[1];
735
						skins[0] = skin;
736
						params.put("qformat", skins);
737
					}
738
					handler.handleReadAction(params, request, response, "public", null, null);
739
					return;
740
				}
741
			}
742

    
743
			Enumeration<String> paramlist = 
744
				(Enumeration<String>) request.getParameterNames();
745
			while (paramlist.hasMoreElements()) {
746

    
747
				name = paramlist.nextElement();
748
				value = request.getParameterValues(name);
749

    
750
				// Decode the docid and mouse click information
751
				// THIS IS OBSOLETE -- I THINK -- REMOVE THIS BLOCK
752
				// 4/12/2007d
753
				// MBJ
754
				if (name.endsWith(".y")) {
755
					docid[0] = name.substring(0, name.length() - 2);
756
					params.put("docid", docid);
757
					name = "ypos";
758
				}
759
				if (name.endsWith(".x")) {
760
					name = "xpos";
761
				}
762

    
763
				params.put(name, value);
764
			}
765

    
766
			// handle param is emptpy
767
			if (params.isEmpty() || params == null) {
768
				return;
769
			}
770

    
771
			// if the user clicked on the input images, decode which image
772
			// was clicked then set the action.
773
			if (params.get("action") == null) {
774
				PrintWriter out = response.getWriter();
775
				response.setContentType("text/xml");
776
				out.println("<?xml version=\"1.0\"?>");
777
				out.println("<error>");
778
				out.println("Action not specified");
779
				out.println("</error>");
780
				out.close();
781
				return;
782
			}
783

    
784
			String action = (params.get("action"))[0];
785
			logMetacat.info("MetaCatServlet.handleGetOrPost - Action is: " + action);
786

    
787
			// This block handles session management for the servlet
788
			// by looking up the current session information for all actions
789
			// other than "login" and "logout"
790
			String userName = null;
791
			String password = null;
792
			String[] groupNames = null;
793
			String sessionId = null;
794
			name = null;
795

    
796
			// handle login action
797
			if (action.equals("login")) {
798
				PrintWriter out = response.getWriter();
799
				handler.handleLoginAction(out, params, request, response);
800
				out.close();
801

    
802
				// handle logout action
803
			} else if (action.equals("logout")) {
804
				PrintWriter out = response.getWriter();
805
				handler.handleLogoutAction(out, params, request, response);
806
				out.close();
807

    
808
				// handle shrink DBConnection request
809
			} else if (action.equals("validatesession")) {
810
				PrintWriter out = response.getWriter();
811
				String idToValidate = null;
812
				String idsToValidate[] = params.get("sessionid");
813
				if (idsToValidate != null) {
814
					idToValidate = idsToValidate[0];
815
				} else {
816
					// use the sessionid from the cookie
817
					SessionData sessionData = RequestUtil.getSessionData(request);
818
					if (sessionData != null) {
819
						idToValidate = sessionData.getId();
820
					}
821
				}
822
				SessionService.getInstance().validateSession(out, response, idToValidate);
823
				out.close();
824

    
825
				// handle shrink DBConnection request
826
			} else if (action.equals("shrink")) {
827
				PrintWriter out = response.getWriter();
828
				boolean success = false;
829
				// If all DBConnection in the pool are free and DBConnection
830
				// pool
831
				// size is greater than initial value, shrink the connection
832
				// pool
833
				// size to initial value
834
				success = DBConnectionPool.shrinkConnectionPoolSize();
835
				if (success) {
836
					// if successfully shrink the pool size to initial value
837
					out.println("DBConnection Pool shrunk successfully.");
838
				}// if
839
				else {
840
					out.println("DBConnection pool not shrunk successfully.");
841
				}
842
				// close out put
843
				out.close();
844

    
845
				// aware of session expiration on every request
846
			} else {
847
				SessionData sessionData = RequestUtil.getSessionData(request);
848
				
849
				if (sessionData != null) {
850
					userName = sessionData.getUserName();
851
					password = sessionData.getPassword();
852
					groupNames = sessionData.getGroupNames();
853
					sessionId = sessionData.getId();
854
				}
855

    
856
				logMetacat.info("MetaCatServlet.handleGetOrPost - The user is : " + userName);
857
			}
858
			// Now that we know the session is valid, we can delegate the
859
			// request to a particular action handler
860
			if (action.equals("query")) {
861
		        Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
862
				handler.handleQuery(out, params, response, userName, groupNames, sessionId);
863
				out.close();
864
			} else if (action.equals("squery")) {
865
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
866
				if (params.containsKey("query")) {
867
					handler.handleSQuery(out, params, response, userName, groupNames, sessionId);
868
					out.close();
869
				} else {
870
					out.write("Illegal action squery without \"query\" parameter");
871
					out.close();
872
				}
873
			} else if (action.trim().equals("spatial_query")) {
874

    
875
				logMetacat
876
						.debug("MetaCatServlet.handleGetOrPost - ******************* SPATIAL QUERY ********************");
877
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
878
				handler.handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
879
				out.close();
880

    
881
			} else if (action.trim().equals("dataquery")) {
882

    
883
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* DATA QUERY ********************");
884
				handler.handleDataquery(params, response, sessionId);
885
			} else if (action.trim().equals("editcart")) {
886
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* EDIT CART ********************");
887
				handler.handleEditCart(params, response, sessionId);
888
			} else if (action.equals("export")) {
889

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

    
1095
			} else {
1096
				//try the plugin handler if it has an entry for handling this action
1097
				MetacatHandlerPlugin handlerPlugin = MetacatHandlerPluginManager.getInstance().getHandler(action);
1098
				if (handlerPlugin != null) {
1099
					handlerPlugin.handleAction(action, params, request, response, userName, groupNames, sessionId);
1100
				} 
1101
				else {
1102
					PrintWriter out = response.getWriter();
1103
					out.println("<?xml version=\"1.0\"?>");
1104
					out.println("<error>");
1105
					out.println("Error: action: " + action + " not registered.  Please report this error.");
1106
					out.println("</error>");
1107
					out.close();
1108
				}
1109
			}
1110

    
1111
			// Schedule the sitemap generator to run periodically
1112
			handler.scheduleSitemapGeneration(request);
1113

    
1114

    
1115
		} catch (PropertyNotFoundException pnfe) {
1116
			String errorString = "Critical property not found: " + pnfe.getMessage();
1117
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1118
			throw new ServletException(errorString);
1119
		} catch (MetacatUtilException ue) {
1120
			String errorString = "Utility error: " + ue.getMessage();
1121
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1122
			throw new ServletException(errorString);
1123
		} catch (ServiceException ue) {
1124
			String errorString = "Service error: " + ue.getMessage();
1125
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1126
			throw new ServletException(errorString);
1127
		} catch (HandlerException he) {
1128
			String errorString = "Handler error: " + he.getMessage();
1129
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1130
			throw new ServletException(errorString);
1131
		} catch (ErrorSendingErrorException esee) {
1132
			String errorString = "Error sending error message: " + esee.getMessage();
1133
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1134
			throw new ServletException(errorString);
1135
		} catch (ErrorHandledException ehe) {
1136
			// Nothing to do here.  We assume if we get here, the error has been 
1137
			// written to ouput.  Continue on and let it display.
1138
		} 
1139
	}
1140
    
1141
    /**
1142
     * Reports whether the MetaCatServlet has been fully initialized
1143
     * 
1144
     * @return true if fully intialized, false otherwise
1145
     */
1146
    public static boolean isFullyInitialized() {
1147
    	return _fullyInitialized;
1148
    }
1149
}
(41-41/63)