Project

General

Profile

1 4091 daigle
/**
2 203 jones
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4 3099 jones
 *  Copyright: 2006 Regents of the University of California and the
5 203 jones
 *             National Center for Ecological Analysis and Synthesis
6 3028 perry
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley, Matthew Perry
7 154 jones
 *
8 203 jones
 *   '$Author$'
9
 *     '$Date$'
10
 * '$Revision$'
11 669 jones
 *
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 51 jones
 */
26
27
package edu.ucsb.nceas.metacat;
28
29 2098 jones
import java.io.IOException;
30 5752 leinfelder
import java.io.OutputStreamWriter;
31 46 jones
import java.io.PrintWriter;
32 5752 leinfelder
import java.io.Writer;
33 2098 jones
import java.sql.PreparedStatement;
34
import java.sql.ResultSet;
35
import java.sql.SQLException;
36 6012 leinfelder
import java.sql.Timestamp;
37 46 jones
import java.util.Enumeration;
38
import java.util.Hashtable;
39 2752 jones
import java.util.Timer;
40 1369 tao
import java.util.Vector;
41 46 jones
42
import javax.servlet.ServletConfig;
43
import javax.servlet.ServletContext;
44
import javax.servlet.ServletException;
45 2098 jones
import javax.servlet.ServletOutputStream;
46 46 jones
import javax.servlet.http.HttpServlet;
47
import javax.servlet.http.HttpServletRequest;
48
import javax.servlet.http.HttpServletResponse;
49 210 bojilova
import javax.servlet.http.HttpSession;
50 46 jones
51 2752 jones
import org.apache.log4j.Logger;
52
import org.apache.log4j.PropertyConfigurator;
53 204 jones
54 5015 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
55
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
56
import edu.ucsb.nceas.metacat.database.DatabaseService;
57 6437 leinfelder
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
58 5518 leinfelder
import edu.ucsb.nceas.metacat.plugin.MetacatHandlerPlugin;
59
import edu.ucsb.nceas.metacat.plugin.MetacatHandlerPluginManager;
60 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
61
import edu.ucsb.nceas.metacat.properties.SkinPropertyService;
62 5015 daigle
import edu.ucsb.nceas.metacat.replication.ReplicationService;
63 4698 daigle
import edu.ucsb.nceas.metacat.service.ServiceService;
64 4080 daigle
import edu.ucsb.nceas.metacat.service.SessionService;
65 4424 daigle
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
66 5030 daigle
import edu.ucsb.nceas.metacat.shared.BaseException;
67 5015 daigle
import edu.ucsb.nceas.metacat.shared.HandlerException;
68
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
69 5211 jones
import edu.ucsb.nceas.metacat.shared.ServiceException;
70 3241 jones
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
71 4589 daigle
import edu.ucsb.nceas.metacat.util.AuthUtil;
72 5025 daigle
import edu.ucsb.nceas.metacat.util.ConfigurationUtil;
73 5211 jones
import edu.ucsb.nceas.metacat.util.DocumentUtil;
74 4950 daigle
import edu.ucsb.nceas.metacat.util.ErrorSendingErrorException;
75 4080 daigle
import edu.ucsb.nceas.metacat.util.RequestUtil;
76 5030 daigle
import edu.ucsb.nceas.metacat.util.ResponseUtil;
77 5211 jones
import edu.ucsb.nceas.metacat.util.SessionData;
78 4139 daigle
import edu.ucsb.nceas.metacat.util.SystemUtil;
79 5030 daigle
import edu.ucsb.nceas.metacat.workflow.WorkflowSchedulerClient;
80 4132 daigle
import edu.ucsb.nceas.utilities.FileUtil;
81 4080 daigle
import edu.ucsb.nceas.utilities.GeneralPropertyException;
82
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
83 5015 daigle
import edu.ucsb.nceas.utilities.UtilException;
84 2570 jones
85 46 jones
/**
86
 * A metadata catalog server implemented as a Java Servlet
87 2169 sgarg
 *
88 5018 daigle
 * 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 4604 daigle
 * action=spatial_query -- run a spatial query.  these queries may include any of the
108 5025 daigle
 *                         queries supported by the WFS / WMS standards
109 5018 daigle
 *     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 4604 daigle
 * action=getrevisionanddoctype -- get a document's revision and doctype from database
164 5018 daigle
 *     docid --
165 4604 daigle
 * action=getversion --
166 5018 daigle
 * 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 5025 daigle
 * action=shrink -- Shrink the database connection pool size if it has grown and
184
 *                  extra connections are no longer being used.
185 5018 daigle
 * action=buildindex --
186
 *     docid --
187
 * action=refreshServices --
188 5025 daigle
 * 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 5045 daigle
 *     workflowjobname -- The job ID for the workflow run that we want to unschedule.  This
215 5025 daigle
 *                      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 5045 daigle
 *     workflowjobname -- The job ID for the workflow run that we want to reschedule.  This
224 5025 daigle
 *                      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 5045 daigle
 *     workflowjobname -- The job ID for the workflow run that we want to delete.  This
233 5025 daigle
 *                      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 8303 tao
 * 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 5018 daigle
 *
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 46 jones
 */
256 3514 barteau
public class MetaCatServlet extends HttpServlet {
257 4080 daigle
258
	private static final long serialVersionUID = 1L;
259
	private Timer timer = null;
260 5167 daigle
    private static boolean _firstHalfInitialized = false;
261
    private static boolean _fullyInitialized = false;
262 5211 jones
    private MetacatHandler handler = null;
263 2752 jones
264
    // Constants -- these should be final in a servlet
265 2098 jones
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
266
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
267
    public static final String EML2KEYWORD = ":eml";
268 3859 tao
    private static final String FALSE = "false";
269
    private static final String TRUE  = "true";
270 5015 daigle
    private static String LOG_CONFIG_NAME = null;
271 5030 daigle
    public static final String APPLICATION_NAME = "metacat";
272 5752 leinfelder
	public static final String DEFAULT_ENCODING = "UTF-8";
273 2663 sgarg
274 2098 jones
    /**
275
     * Initialize the servlet by creating appropriate database connections
276
     */
277 3514 barteau
    public void init(ServletConfig config) throws ServletException {
278 4080 daigle
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
279
    	try {
280 5167 daigle
    		if(_firstHalfInitialized) {
281 4959 daigle
    			return;
282
    		}
283
284 2098 jones
            super.init(config);
285 3078 jones
286 2752 jones
            ServletContext context = config.getServletContext();
287 5030 daigle
            context.setAttribute("APPLICATION_NAME", APPLICATION_NAME);
288 4698 daigle
289
            ServiceService serviceService = ServiceService.getInstance(context);
290 5167 daigle
            logMetacat.debug("MetaCatServlet.init - ServiceService singleton created " + serviceService);
291 4698 daigle
292 4124 daigle
            // Initialize the properties file
293 4698 daigle
            String dirPath = ServiceService.getRealConfigDir();
294 3099 jones
295 5015 daigle
            LOG_CONFIG_NAME = dirPath + "/log4j.properties";
296 2663 sgarg
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
297
298 4698 daigle
            // Register preliminary services
299 5030 daigle
            ServiceService.registerService("PropertyService", PropertyService.getInstance(context));
300 4698 daigle
            ServiceService.registerService("SkinPropertyService", SkinPropertyService.getInstance());
301
            ServiceService.registerService("SessionService", SessionService.getInstance());
302 6088 cjones
303
            // Check to see if the user has requested to bypass configuration
304 4154 daigle
            // (dev option) and check see if metacat has been configured.
305
    		// If both are false then stop the initialization
306 5025 daigle
            if (!ConfigurationUtil.bypassConfiguration() && !ConfigurationUtil.isMetacatConfigured()) {
307 4080 daigle
            	return;
308 4203 daigle
            }
309 3081 jones
310 5167 daigle
            _firstHalfInitialized = true;
311 4959 daigle
312 4203 daigle
            initSecondHalf(context);
313 2752 jones
314 4203 daigle
    	} catch (ServiceException se) {
315 4080 daigle
        	String errorMessage =
316
        		"Service problem while intializing MetaCat Servlet: " + se.getMessage();
317 5167 daigle
            logMetacat.error("MetaCatServlet.init - " + errorMessage);
318 4080 daigle
            throw new ServletException(errorMessage);
319 5015 daigle
        } catch (MetacatUtilException mue) {
320
        	String errorMessage = "Metacat utility problem while intializing MetaCat Servlet: "
321
        		+ mue.getMessage();
322 5167 daigle
            logMetacat.error("MetaCatServlet.init - " + errorMessage);
323 4698 daigle
            throw new ServletException(errorMessage);
324 4203 daigle
        }
325 2098 jones
    }
326 4203 daigle
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 5015 daigle
337 4203 daigle
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
338
339 4698 daigle
		try {
340
			ServiceService.registerService("DatabaseService", DatabaseService.getInstance());
341 4334 daigle
342 4203 daigle
			// initialize DBConnection pool
343
			DBConnectionPool connPool = DBConnectionPool.getInstance();
344 5167 daigle
			logMetacat.debug("MetaCatServlet.initSecondHalf - DBConnection pool initialized: " + connPool.toString());
345 4424 daigle
346 6088 cjones
			// register the XML schema service
347 4698 daigle
			ServiceService.registerService("XMLSchemaService", XMLSchemaService.getInstance());
348 6088 cjones
349 4967 daigle
			// 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 5167 daigle
			String correctedEML201Doc = PropertyService.getProperty("document.eml201DocumentCorrected");
353 4203 daigle
			if (correctedEML201Doc != null && correctedEML201Doc.equals(FALSE)) {
354 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Start to correct eml201 documents");
355 4203 daigle
				EML201DocumentCorrector correct = new EML201DocumentCorrector();
356
				boolean success = correct.run();
357
				if (success) {
358 4212 daigle
					PropertyService.setProperty("document.eml201DocumentCorrected", TRUE);
359 4203 daigle
				}
360 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Finish to correct eml201 documents");
361 4203 daigle
			}
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 4327 leinfelder
381 4203 daigle
			/*
382
			 * If spatial option is turned on and set to regenerate the spatial
383
			 * cache on restart, trigger the harvester regeneratation method
384
			 */
385 5311 daigle
			if (PropertyService.getProperty("spatial.runSpatialOption").equals("true") &&
386
					PropertyService.getProperty("spatial.regenerateCacheOnRestart").equals("true")) {
387
388 4203 daigle
				// Begin timer
389
				long before = System.currentTimeMillis();
390
391 5311 daigle
				// 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 4203 daigle
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 5311 daigle
				PropertyService.setProperty("spatial.regenerateCacheOnRestart", "false");
402 4203 daigle
403
				// End timer
404
				long after = System.currentTimeMillis();
405 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial Harvester Time  "
406 4203 daigle
						+ (after - before) + "ms");
407
408
			} else {
409 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial cache is not set to regenerate on restart");
410 4203 daigle
			}
411 5015 daigle
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 4203 daigle
421 5015 daigle
			if (FileUtil.getFileStatus(replicationLogPath) < FileUtil.EXISTS_READ_WRITABLE) {
422 5167 daigle
				logMetacat.error("MetaCatServlet.initSecondHalf - Replication log file: " + replicationLogPath
423 5015 daigle
						+ " does not exist read/writable.");
424
			}
425
426
			System.setProperty("replication.logfile.name", replicationLogPath);
427
			PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
428
429 5374 berkley
			SessionService.getInstance().unRegisterAllSessions();
430 5311 daigle
431 5211 jones
	         //Initialize Metacat Handler
432 5337 berkley
            handler = new MetacatHandler(timer);
433 4203 daigle
434 5311 daigle
			handler.set_sitemapScheduled(false);
435 6031 leinfelder
436
			// initialize the plugins
437
			MetacatHandlerPluginManager.getInstance();
438 6437 leinfelder
439
			// initialize the HazelcastService
440
			ServiceService.registerService("HazelcastService", HazelcastService.getInstance());
441 5211 jones
442 5167 daigle
			_fullyInitialized = true;
443 4203 daigle
444 5167 daigle
			logMetacat.warn("MetaCatServlet.initSecondHalf - Metacat (" + MetacatVersion.getVersionID()
445 4203 daigle
					+ ") initialized.");
446 5015 daigle
447 4203 daigle
		} catch (SQLException e) {
448
			String errorMessage = "SQL problem while intializing MetaCat Servlet: "
449
					+ e.getMessage();
450 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
451 4203 daigle
			throw new ServletException(errorMessage);
452
		} catch (IOException ie) {
453
			String errorMessage = "IO problem while intializing MetaCat Servlet: "
454
					+ ie.getMessage();
455 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
456 4203 daigle
			throw new ServletException(errorMessage);
457
		} catch (GeneralPropertyException gpe) {
458
			String errorMessage = "Could not retrieve property while intializing MetaCat Servlet: "
459
					+ gpe.getMessage();
460 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
461 4203 daigle
			throw new ServletException(errorMessage);
462 4698 daigle
		} catch (ServiceException se) {
463
			String errorMessage = "Service problem while intializing MetaCat Servlet: "
464
				+ se.getMessage();
465 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
466 4698 daigle
			throw new ServletException(errorMessage);
467 5015 daigle
		} catch (UtilException ue) {
468
        	String errorMessage = "Utility problem while intializing MetaCat Servlet: "
469
        		+ ue.getMessage();
470 5167 daigle
            logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
471 5015 daigle
            throw new ServletException(errorMessage);
472
        }
473 4203 daigle
	}
474 3514 barteau
475 2570 jones
    /**
476 4203 daigle
	 * Close all db connections from the pool
477
	 */
478 3514 barteau
    public void destroy() {
479 4811 daigle
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
480 4981 daigle
481
    	ServiceService.stopAllServices();
482
483 2570 jones
        // Close all db connection
484 5167 daigle
        logMetacat.warn("MetaCatServlet.destroy - Destroying MetacatServlet");
485 2759 sgarg
        timer.cancel();
486 2901 sgarg
        IndexingQueue.getInstance().setMetacatRunning(false);
487 2570 jones
        DBConnectionPool.release();
488
    }
489 3514 barteau
490 2570 jones
    /** Handle "GET" method requests from HTTP clients */
491
    public void doGet(HttpServletRequest request, HttpServletResponse response)
492 3514 barteau
    throws ServletException, IOException {
493
494 2570 jones
        // Process the data and send back the response
495
        handleGetOrPost(request, response);
496
    }
497 3514 barteau
498 2570 jones
    /** Handle "POST" method requests from HTTP clients */
499
    public void doPost(HttpServletRequest request, HttpServletResponse response)
500 3514 barteau
    throws ServletException, IOException {
501
502 2570 jones
        // Process the data and send back the response
503
        handleGetOrPost(request, response);
504
    }
505 3514 barteau
506 2098 jones
    /**
507 4203 daigle
	 * Index the paths specified in the metacat.properties
508
	 */
509 2753 jones
    private void checkIndexPaths() {
510
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
511 4812 daigle
512
        Vector<String> pathsForIndexing = null;
513
        try {
514
        	pathsForIndexing = SystemUtil.getPathsForIndexing();
515 4080 daigle
        }
516 4854 daigle
        catch (MetacatUtilException ue) {
517 4812 daigle
        	pathsForIndexing = null;
518 5167 daigle
            logMetacat.error("MetaCatServlet.checkIndexPaths - not find index paths.  Setting "
519 4812 daigle
            		+ "pathsForIndexing to null: " + ue.getMessage());
520 4080 daigle
        }
521
522 4812 daigle
        if (pathsForIndexing != null && !pathsForIndexing.isEmpty()) {
523 3514 barteau
524 5167 daigle
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Indexing paths specified in metacat.properties....");
525 3514 barteau
526 2521 sgarg
            DBConnection conn = null;
527
            int serialNumber = -1;
528
            PreparedStatement pstmt = null;
529
            PreparedStatement pstmt1 = null;
530
            ResultSet rs = null;
531 3514 barteau
532 4812 daigle
            for (String pathIndex : pathsForIndexing) {
533 5167 daigle
                logMetacat.debug("MetaCatServlet.checkIndexPaths - Checking if '" + pathIndex  + "' is indexed.... ");
534 3514 barteau
535 2521 sgarg
                try {
536
                    //check out DBConnection
537
                    conn = DBConnectionPool.
538 3514 barteau
                            getDBConnection("MetaCatServlet.checkIndexPaths");
539 2521 sgarg
                    serialNumber = conn.getCheckOutSerialNumber();
540 3514 barteau
541 2521 sgarg
                    pstmt = conn.prepareStatement(
542 3514 barteau
                            "SELECT * FROM xml_path_index " + "WHERE path = ?");
543 4812 daigle
                    pstmt.setString(1, pathIndex);
544 3514 barteau
545 2521 sgarg
                    pstmt.execute();
546
                    rs = pstmt.getResultSet();
547 3514 barteau
548 2521 sgarg
                    if (!rs.next()) {
549 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - not indexed yet.");
550 2521 sgarg
                        rs.close();
551
                        pstmt.close();
552
                        conn.increaseUsageCount(1);
553 3514 barteau
554 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Inserting following path in xml_path_index: "
555 4812 daigle
                                + pathIndex);
556
                        if(pathIndex.indexOf("@")<0){
557 3514 barteau
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
558 6012 leinfelder
                                    + "n.nodedata, n.nodedatanumerical, n.nodedatadate, n.parentnodeid"
559 3514 barteau
                                    + " 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 6012 leinfelder
                                    + "n.nodedata, n.nodedatanumerical, n.nodedatadate, n.parentnodeid"
565 3514 barteau
                                    + " 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 4812 daigle
                        pstmt.setString(1, pathIndex);
570 2521 sgarg
                        pstmt.execute();
571
                        rs = pstmt.getResultSet();
572 3514 barteau
573 2521 sgarg
                        int count = 0;
574 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Executed the select statement for: "
575 4812 daigle
                                + pathIndex);
576 3514 barteau
577 2521 sgarg
                        try {
578
                            while (rs.next()) {
579 3514 barteau
580 2521 sgarg
                                String docid = rs.getString(1);
581
                                String nodedata = rs.getString(2);
582
                                float nodedatanumerical = rs.getFloat(3);
583 6012 leinfelder
                                Timestamp nodedatadate = rs.getTimestamp(4);
584
                                int parentnodeid = rs.getInt(5);
585 3514 barteau
586 2521 sgarg
                                if (!nodedata.trim().equals("")) {
587
                                    pstmt1 = conn.prepareStatement(
588 3514 barteau
                                            "INSERT INTO xml_path_index"
589
                                            + " (docid, path, nodedata, "
590 6012 leinfelder
                                            + "nodedatanumerical, nodedatadate, parentnodeid)"
591
                                            + " VALUES (?, ?, ?, ?, ?, ?)");
592 3514 barteau
593 2521 sgarg
                                    pstmt1.setString(1, docid);
594 4812 daigle
                                    pstmt1.setString(2, pathIndex);
595 2521 sgarg
                                    pstmt1.setString(3, nodedata);
596
                                    pstmt1.setFloat(4, nodedatanumerical);
597 6012 leinfelder
                                    pstmt1.setTimestamp(5, nodedatadate);
598
                                    pstmt1.setInt(6, parentnodeid);
599 3514 barteau
600 2521 sgarg
                                    pstmt1.execute();
601
                                    pstmt1.close();
602 3514 barteau
603 2521 sgarg
                                    count++;
604 3514 barteau
605 2521 sgarg
                                }
606
                            }
607 3514 barteau
                        } catch (Exception e) {
608 5167 daigle
                            logMetacat.error("MetaCatServlet.checkIndexPaths - Exception:" + e.getMessage());
609 2521 sgarg
                            e.printStackTrace();
610
                        }
611 3514 barteau
612 2521 sgarg
                        rs.close();
613
                        pstmt.close();
614
                        conn.increaseUsageCount(1);
615 3514 barteau
616 5167 daigle
                        logMetacat.info("MetaCatServlet.checkIndexPaths - Indexed " + count + " records from xml_nodes for '"
617 4812 daigle
                                + pathIndex + "'");
618 3514 barteau
619 2521 sgarg
                    } else {
620 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - already indexed.");
621 2521 sgarg
                    }
622 3514 barteau
623 2521 sgarg
                    rs.close();
624
                    pstmt.close();
625
                    conn.increaseUsageCount(1);
626 3514 barteau
627 2521 sgarg
                } catch (Exception e) {
628 5167 daigle
                    logMetacat.error("MetaCatServlet.checkIndexPaths - Error in MetaCatServlet.checkIndexPaths: "
629 3514 barteau
                            + e.getMessage());
630 2521 sgarg
                }finally {
631
                    //check in DBonnection
632
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
633
                }
634 3514 barteau
635
636 2521 sgarg
            }
637 3514 barteau
638 5167 daigle
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Path Indexing Completed");
639 2521 sgarg
        }
640 3514 barteau
    }
641
642 2098 jones
    /**
643 4080 daigle
	 * Control servlet response depending on the action parameter specified
644
	 */
645 5167 daigle
	@SuppressWarnings("unchecked")
646 4080 daigle
	private void handleGetOrPost(HttpServletRequest request,
647
			HttpServletResponse response) throws ServletException, IOException {
648
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
649
650 5752 leinfelder
		String requestEncoding = request.getCharacterEncoding();
651 8264 leinfelder
		if (requestEncoding == null) {
652
			logMetacat.debug("null requestEncoding, setting to application default: " + DEFAULT_ENCODING);
653
			request.setCharacterEncoding(DEFAULT_ENCODING);
654
		}
655 5767 leinfelder
		logMetacat.debug("requestEncoding: " + requestEncoding);
656 5752 leinfelder
657 4080 daigle
		// Update the last update time for this user if they are not new
658
		HttpSession httpSession = request.getSession(false);
659
		if (httpSession != null) {
660 5374 berkley
		    SessionService.getInstance().touchSession(httpSession.getId());
661 4080 daigle
		}
662
663 4154 daigle
		// Each time metacat is called, check to see if metacat has been
664
		// configured. If not then forward to the administration servlet
665 5025 daigle
		if (!ConfigurationUtil.isMetacatConfigured()) {
666 5076 daigle
			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 4080 daigle
		}
676
677 4203 daigle
		// if we get here, metacat is configured.  If we have not completed the
678 4698 daigle
		// second half of the initialization, do so now.  This allows us to initially
679 4203 daigle
		// configure metacat without a restart.
680 5167 daigle
		if (!_fullyInitialized) {
681 4203 daigle
			initSecondHalf(request.getSession().getServletContext());
682
		}
683
684 4080 daigle
		/*
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 5167 daigle
			@SuppressWarnings("unused")
697 4080 daigle
			DBConnectionPool pool = DBConnectionPool.getInstance();
698 5167 daigle
//			pool.printMethodNameHavingBusyDBConnection();
699 4080 daigle
		} catch (SQLException e) {
700 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - Error in MetacatServlet.handleGetOrPost: " + e.getMessage());
701 4080 daigle
			e.printStackTrace();
702
		}
703
704
		try {
705
			String ctype = request.getContentType();
706 5211 jones
707 4080 daigle
			if (ctype != null && ctype.startsWith("multipart/form-data")) {
708 5211 jones
				handler.handleMultipartForm(request, response);
709 5030 daigle
				return;
710
			}
711 4080 daigle
712 5030 daigle
			String name = null;
713
			String[] value = null;
714
			String[] docid = new String[3];
715
			Hashtable<String, String[]> params = new Hashtable<String, String[]>();
716 4080 daigle
717 5030 daigle
			// Check if this is a simple read request that doesn't use the
718
			// "action" syntax
719
			// These URLs are of the form:
720 8265 leinfelder
			// http://localhost:8180/metacat/metacat/docid/skinname
721
			// e.g., http://localhost:8180/metacat/metacat/test.1.1/knb
722 5030 daigle
			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 5167 daigle
					logMetacat.debug("MetaCatServlet.handleGetOrPost - READING DOCID FROM PATHINFO: " + docs[0]);
730 5030 daigle
					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 4080 daigle
					}
738 5211 jones
					handler.handleReadAction(params, request, response, "public", null, null);
739 5030 daigle
					return;
740 4080 daigle
				}
741 5030 daigle
			}
742 4080 daigle
743 5030 daigle
			Enumeration<String> paramlist =
744
				(Enumeration<String>) request.getParameterNames();
745
			while (paramlist.hasMoreElements()) {
746 4080 daigle
747 5030 daigle
				name = paramlist.nextElement();
748
				value = request.getParameterValues(name);
749 4080 daigle
750 5030 daigle
				// 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 4080 daigle
				}
759 5030 daigle
				if (name.endsWith(".x")) {
760
					name = "xpos";
761 4080 daigle
				}
762
763 5030 daigle
				params.put(name, value);
764
			}
765 4080 daigle
766 5030 daigle
			// handle param is emptpy
767
			if (params.isEmpty() || params == null) {
768
				return;
769
			}
770 4080 daigle
771 5030 daigle
			// 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 4080 daigle
784 5030 daigle
			String action = (params.get("action"))[0];
785 5167 daigle
			logMetacat.info("MetaCatServlet.handleGetOrPost - Action is: " + action);
786 4080 daigle
787 5030 daigle
			// 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 4080 daigle
796 5030 daigle
			// handle login action
797
			if (action.equals("login")) {
798
				PrintWriter out = response.getWriter();
799 5211 jones
				handler.handleLoginAction(out, params, request, response);
800 5030 daigle
				out.close();
801 4080 daigle
802 5030 daigle
				// handle logout action
803
			} else if (action.equals("logout")) {
804
				PrintWriter out = response.getWriter();
805 5211 jones
				handler.handleLogoutAction(out, params, request, response);
806 5030 daigle
				out.close();
807 4080 daigle
808 5030 daigle
				// handle shrink DBConnection request
809 5041 daigle
			} 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 8075 leinfelder
				} else {
816
					// use the sessionid from the cookie
817
					SessionData sessionData = RequestUtil.getSessionData(request);
818
					if (sessionData != null) {
819
						idToValidate = sessionData.getId();
820
					}
821 5041 daigle
				}
822 5374 berkley
				SessionService.getInstance().validateSession(out, response, idToValidate);
823 5041 daigle
				out.close();
824
825
				// handle shrink DBConnection request
826 5030 daigle
			} 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 4080 daigle
				}
842 5030 daigle
				// close out put
843
				out.close();
844 4080 daigle
845 5030 daigle
				// aware of session expiration on every request
846
			} else {
847
				SessionData sessionData = RequestUtil.getSessionData(request);
848 5159 daigle
849
				if (sessionData != null) {
850
					userName = sessionData.getUserName();
851
					password = sessionData.getPassword();
852
					groupNames = sessionData.getGroupNames();
853
					sessionId = sessionData.getId();
854
				}
855 4080 daigle
856 5167 daigle
				logMetacat.info("MetaCatServlet.handleGetOrPost - The user is : " + userName);
857 5030 daigle
			}
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 5752 leinfelder
		        Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
862 5211 jones
				handler.handleQuery(out, params, response, userName, groupNames, sessionId);
863 5030 daigle
				out.close();
864
			} else if (action.equals("squery")) {
865 5752 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
866 5030 daigle
				if (params.containsKey("query")) {
867 5211 jones
					handler.handleSQuery(out, params, response, userName, groupNames, sessionId);
868 5030 daigle
					out.close();
869
				} else {
870 5752 leinfelder
					out.write("Illegal action squery without \"query\" parameter");
871 5030 daigle
					out.close();
872 4221 leinfelder
				}
873 5030 daigle
			} else if (action.trim().equals("spatial_query")) {
874 4221 leinfelder
875 5030 daigle
				logMetacat
876 5167 daigle
						.debug("MetaCatServlet.handleGetOrPost - ******************* SPATIAL QUERY ********************");
877 5752 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
878 5211 jones
				handler.handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
879 5030 daigle
				out.close();
880
881
			} else if (action.trim().equals("dataquery")) {
882
883 5167 daigle
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* DATA QUERY ********************");
884 5211 jones
				handler.handleDataquery(params, response, sessionId);
885 5030 daigle
			} else if (action.trim().equals("editcart")) {
886 5167 daigle
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* EDIT CART ********************");
887 5211 jones
				handler.handleEditCart(params, response, sessionId);
888 5030 daigle
			} else if (action.equals("export")) {
889
890 5211 jones
				handler.handleExportAction(params, response, userName, groupNames, password);
891 5030 daigle
			} 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 5211 jones
					handler.handleReadAction(params, request, response, userName, password,
897 4295 daigle
							groupNames);
898 5030 daigle
				}
899
			} else if (action.equals("readinlinedata")) {
900 5211 jones
				handler.handleReadInlineDataAction(params, request, response, userName, password,
901 5030 daigle
						groupNames);
902
			} else if (action.equals("insert") || action.equals("update")) {
903
				PrintWriter out = response.getWriter();
904
				if ((userName != null) && !userName.equals("public")) {
905 6542 leinfelder
					handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), response, out, params, userName,
906 7128 leinfelder
							groupNames, true, true);
907 5030 daigle
				} else {
908 4080 daigle
					response.setContentType("text/xml");
909
					out.println("<?xml version=\"1.0\"?>");
910 5030 daigle
					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 5211 jones
					handler.handleDeleteAction(out, params, request, response, userName,
919 4295 daigle
							groupNames);
920 4950 daigle
				} else {
921 5030 daigle
					response.setContentType("text/xml");
922 4080 daigle
					out.println("<?xml version=\"1.0\"?>");
923
					out.println("<error>");
924 5030 daigle
					out.println("Permission denied for " + action);
925 4080 daigle
					out.println("</error>");
926
				}
927 5030 daigle
				out.close();
928
			} else if (action.equals("validate")) {
929
				PrintWriter out = response.getWriter();
930 5211 jones
				handler.handleValidateAction(out, params);
931 5030 daigle
				out.close();
932
			} else if (action.equals("setaccess")) {
933
				PrintWriter out = response.getWriter();
934 5211 jones
				handler.handleSetAccessAction(out, params, userName, request, response);
935 5030 daigle
				out.close();
936
			} else if (action.equals("getaccesscontrol")) {
937
				PrintWriter out = response.getWriter();
938 5211 jones
				handler.handleGetAccessControlAction(out, params, response, userName, groupNames);
939 5030 daigle
				out.close();
940 5071 daigle
			} else if (action.equals("isauthorized")) {
941
				PrintWriter out = response.getWriter();
942
				DocumentUtil.isAuthorized(out, params, request, response);
943
				out.close();
944 5030 daigle
			} else if (action.equals("getprincipals")) {
945
				PrintWriter out = response.getWriter();
946 5211 jones
				handler.handleGetPrincipalsAction(out, userName, password);
947 5030 daigle
				out.close();
948
			} else if (action.equals("getdoctypes")) {
949
				PrintWriter out = response.getWriter();
950 5211 jones
				handler.handleGetDoctypesAction(out, params, response);
951 5030 daigle
				out.close();
952
			} else if (action.equals("getdtdschema")) {
953
				PrintWriter out = response.getWriter();
954 5211 jones
				handler.handleGetDTDSchemaAction(out, params, response);
955 5030 daigle
				out.close();
956 7695 leinfelder
			} else if (action.equals("getdocid")) {
957
				handler.handleGetDocid(params, response);
958 5030 daigle
			} else if (action.equals("getlastdocid")) {
959
				PrintWriter out = response.getWriter();
960 5211 jones
				handler.handleGetMaxDocidAction(out, params, response);
961 5030 daigle
				out.close();
962
			} else if (action.equals("getalldocids")) {
963
				PrintWriter out = response.getWriter();
964 5211 jones
				handler.handleGetAllDocidsAction(out, params, response);
965 5030 daigle
				out.close();
966
			} else if (action.equals("isregistered")) {
967
				PrintWriter out = response.getWriter();
968 5211 jones
				handler.handleIdIsRegisteredAction(out, params, response);
969 5030 daigle
				out.close();
970
			} else if (action.equals("getrevisionanddoctype")) {
971
				PrintWriter out = response.getWriter();
972 5211 jones
				handler.handleGetRevisionAndDocTypeAction(out, params);
973 5030 daigle
				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 7404 leinfelder
				handler.handleGetLogAction(params, request, response, userName, groupNames, sessionId);
981 5030 daigle
			} 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 5211 jones
				handler.handleBuildIndexAction(params, request, response, userName, groupNames);
1004 7843 leinfelder
			} else if (action.equals("reindex")) {
1005
				handler.handleReindexAction(params, request, response, userName, groupNames);
1006 8303 tao
			} else if (action.equals("reindexall")) {
1007
                handler.handleReindexAllAction(params, request, response, userName, groupNames);
1008
            } else if (action.equals("login") || action.equals("logout")) {
1009 5030 daigle
				/*
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 5041 daigle
				// a ServiceService class and only work for an admin user. Move
1041
				// to the MetacatAdminServlet
1042 5030 daigle
				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 4080 daigle
1095 5030 daigle
			} else {
1096 5518 leinfelder
				//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 5030 daigle
			}
1110 4080 daigle
1111 5030 daigle
			// Schedule the sitemap generator to run periodically
1112 5211 jones
			handler.scheduleSitemapGeneration(request);
1113 5030 daigle
1114
1115 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
1116
			String errorString = "Critical property not found: " + pnfe.getMessage();
1117 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1118 4080 daigle
			throw new ServletException(errorString);
1119 4854 daigle
		} catch (MetacatUtilException ue) {
1120 4080 daigle
			String errorString = "Utility error: " + ue.getMessage();
1121 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1122 4080 daigle
			throw new ServletException(errorString);
1123 4698 daigle
		} catch (ServiceException ue) {
1124
			String errorString = "Service error: " + ue.getMessage();
1125 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1126 4698 daigle
			throw new ServletException(errorString);
1127 4950 daigle
		} catch (HandlerException he) {
1128
			String errorString = "Handler error: " + he.getMessage();
1129 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1130 4950 daigle
			throw new ServletException(errorString);
1131
		} catch (ErrorSendingErrorException esee) {
1132
			String errorString = "Error sending error message: " + esee.getMessage();
1133 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1134 4950 daigle
			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 4959 daigle
		}
1139 4080 daigle
	}
1140 3514 barteau
1141 2912 harris
    /**
1142 4203 daigle
     * Reports whether the MetaCatServlet has been fully initialized
1143
     *
1144
     * @return true if fully intialized, false otherwise
1145
     */
1146
    public static boolean isFullyInitialized() {
1147 5167 daigle
    	return _fullyInitialized;
1148 4203 daigle
    }
1149 46 jones
}