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 8792 leinfelder
import org.apache.commons.lang.StringEscapeUtils;
52 2752 jones
import org.apache.log4j.Logger;
53
import org.apache.log4j.PropertyConfigurator;
54 204 jones
55 8842 tao
import edu.ucsb.nceas.metacat.common.query.EnabledQueryEngines;
56 5015 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
57
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
58
import edu.ucsb.nceas.metacat.database.DatabaseService;
59 6437 leinfelder
import edu.ucsb.nceas.metacat.dataone.hazelcast.HazelcastService;
60 5518 leinfelder
import edu.ucsb.nceas.metacat.plugin.MetacatHandlerPlugin;
61
import edu.ucsb.nceas.metacat.plugin.MetacatHandlerPluginManager;
62 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
63
import edu.ucsb.nceas.metacat.properties.SkinPropertyService;
64 5015 daigle
import edu.ucsb.nceas.metacat.replication.ReplicationService;
65 4698 daigle
import edu.ucsb.nceas.metacat.service.ServiceService;
66 4080 daigle
import edu.ucsb.nceas.metacat.service.SessionService;
67 4424 daigle
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
68 5030 daigle
import edu.ucsb.nceas.metacat.shared.BaseException;
69 5015 daigle
import edu.ucsb.nceas.metacat.shared.HandlerException;
70
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
71 5211 jones
import edu.ucsb.nceas.metacat.shared.ServiceException;
72 3241 jones
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
73 4589 daigle
import edu.ucsb.nceas.metacat.util.AuthUtil;
74 5025 daigle
import edu.ucsb.nceas.metacat.util.ConfigurationUtil;
75 5211 jones
import edu.ucsb.nceas.metacat.util.DocumentUtil;
76 4950 daigle
import edu.ucsb.nceas.metacat.util.ErrorSendingErrorException;
77 4080 daigle
import edu.ucsb.nceas.metacat.util.RequestUtil;
78 5030 daigle
import edu.ucsb.nceas.metacat.util.ResponseUtil;
79 5211 jones
import edu.ucsb.nceas.metacat.util.SessionData;
80 4139 daigle
import edu.ucsb.nceas.metacat.util.SystemUtil;
81 5030 daigle
import edu.ucsb.nceas.metacat.workflow.WorkflowSchedulerClient;
82 4132 daigle
import edu.ucsb.nceas.utilities.FileUtil;
83 4080 daigle
import edu.ucsb.nceas.utilities.GeneralPropertyException;
84
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
85 5015 daigle
import edu.ucsb.nceas.utilities.UtilException;
86 2570 jones
87 46 jones
/**
88
 * A metadata catalog server implemented as a Java Servlet
89 2169 sgarg
 *
90 5018 daigle
 * Valid actions are:
91
 *
92
 * action=login
93
 *     username
94
 *     password
95
 *     qformat
96
 * action=logout
97
 *     qformat
98
 * action=query -- query the values of all elements and attributes and return a result set of nodes
99
 *     meta_file_id --
100
 *     returndoctype --
101
 *     filterdoctype --
102
 *     returnfield --
103
 *     owner --
104
 *     site --
105
 *     operator --
106
 *     casesensitive --
107
 *     searchmode --
108
 *     anyfield --
109 4604 daigle
 * action=spatial_query -- run a spatial query.  these queries may include any of the
110 5025 daigle
 *                         queries supported by the WFS / WMS standards
111 5018 daigle
 *     xmax --
112
 *     ymax --
113
 *     xmin --
114
 *     ymin --
115
 *     skin --
116
 *     pagesize --
117
 *     pagestart --
118
 * action=squery -- structured query (see pathquery.dtd)
119
 *     query --
120
 *     pagesize --
121
 *     pagestart --
122
 * action=export -- export a zip format for data packadge
123
 *     docid --
124
 * action=read -- read any metadata/data file from Metacat and from Internet
125
 *     archiveEntryName --
126
 *     docid --
127
 *     qformat --
128
 *     metadatadocid --
129
 * action=readinlinedata -- read inline data only
130
 *     inlinedataid
131
 * action=insert -- insert an XML document into the database store
132
 *     qformat --
133
 *     docid --
134
 *     doctext --
135
 *     dtdtext --
136
 * action=insertmultipart -- insert an xml document into the database using multipart encoding
137
 *     qformat --
138
 *     docid --
139
 * action=update -- update an XML document that is in the database store
140
 *     qformat --
141
 *     docid --
142
 *     doctext --
143
 *     dtdtext --
144
 * action=delete -- delete an XML document from the database store
145
 *     docid --
146
 * action=validate -- validate the xml contained in valtext
147
 *     valtext --
148
 *     docid --
149
 * action=setaccess -- change access permissions for a user on a document.
150
 *     docid --
151
 *     principal --
152
 *     permission --
153
 *     permType --
154
 *     permOrder --
155
 * action=getaccesscontrol -- retrieve acl info for Metacat document
156
 *     docid --
157
 * action=getprincipals -- retrieve a list of principals in XML
158
 * action=getalldocids -- retrieves a list of all docids registered with the system
159
 *     scope --
160
 * action=getlastdocid --
161
 *     scope --
162
 *     username --
163
 * action=isregistered -- checks to see if the provided docid is registered
164
 *     docid --
165 4604 daigle
 * action=getrevisionanddoctype -- get a document's revision and doctype from database
166 5018 daigle
 *     docid --
167 4604 daigle
 * action=getversion --
168 5018 daigle
 * action=getdoctypes -- retrieve all doctypes (publicID)
169
 * action=getdtdschema -- retrieve a DTD or Schema file
170
 *     doctype --
171
 * action=getlog -- get a report of events that have occurred in the system
172
 *     ipAddress --  filter on one or more IP addresses>
173
 *     principal -- filter on one or more principals (LDAP DN syntax)
174
 *     docid -- filter on one or more document identifiers (with revision)
175
 *     event -- filter on event type (e.g., read, insert, update, delete)
176
 *     start -- filter out events before the start date-time
177
 *     end -- filter out events before the end date-time
178
 * action=getloggedinuserinfo -- get user info for the currently logged in user
179
 *     ipAddress --  filter on one or more IP addresses>
180
 *     principal -- filter on one or more principals (LDAP DN syntax)
181
 *     docid -- filter on one or more document identifiers (with revision)
182
 *     event -- filter on event type (e.g., read, insert, update, delete)
183
 *     start -- filter out events before the start date-time
184
 *     end -- filter out events before the end date-time
185 5025 daigle
 * action=shrink -- Shrink the database connection pool size if it has grown and
186
 *                  extra connections are no longer being used.
187 5018 daigle
 * action=buildindex --
188
 *     docid --
189
 * action=refreshServices --
190 5025 daigle
 * action=scheduleWorkflow -- Schedule a workflow to be run.  Scheduling a workflow
191
 *                            registers it with the scheduling engine and creates a row
192
 *                            in the scheduled_job table.  Note that this may be
193
 *                            extracted into a separate servlet.
194
 *     delay -- The amount of time from now before the workflow should be run.  The
195
 *              delay can be expressed in number of seconds, minutes, hours and days,
196
 *              for instance 30s, 2h, etc.
197
 *     starttime -- The time that the workflow should first run.  If both are provided
198
 *                  this takes precedence over delay.  The time should be expressed as:
199
 *                  MM/dd/yyyy HH:mm:ss with the timezone assumed to be that of the OS.
200
 *     endtime -- The time when the workflow should end. The time should be expressed as:
201
 *                  MM/dd/yyyy HH:mm:ss with the timezone assumed to be that of the OS.
202
 *     intervalvalue -- The numeric value of the interval between runs
203
 *     intervalunit -- The unit of the interval between runs.  Can be s, m, h, d for
204
 *                     seconds, minutes, hours and days respectively
205
 *     workflowid -- The lsid of the workflow that we want to schedule.  This workflow
206
 *                   must already exist in the database.
207
 *     karid -- The karid for the workflow that we want to schedule.
208
 *     workflowname -- The name of the workflow.
209
 *     forwardto -- If provided, forward to this page when processing is done.
210
 *     qformat -- If provided, render results using the stylesheets associated with
211
 *                this skin.  Default is xml.
212
 * action=unscheduleWorkflow -- Unschedule a workflow.  Unscheduling a workflow
213
 *                            removes it from the scheduling engine and changes the
214
 *                            status in the scheduled_job table to " unscheduled.  Note
215
 *                            that this may be extracted into a separate servlet.
216 5045 daigle
 *     workflowjobname -- The job ID for the workflow run that we want to unschedule.  This
217 5025 daigle
 *                      is held in the database as scheduled_job.name
218
 *     forwardto -- If provided, forward to this page when processing is done.
219
 *     qformat -- If provided, render results using the stylesheets associated with
220
 *                this skin.  Default is xml.
221
 * action=rescheduleWorkflow -- Unschedule a workflow.  Rescheduling a workflow
222
 *                            registers it with the scheduling engine and changes the
223
 *                            status in the scheduled_job table to " scheduled.  Note
224
 *                            that this may be extracted into a separate servlet.
225 5045 daigle
 *     workflowjobname -- The job ID for the workflow run that we want to reschedule.  This
226 5025 daigle
 *                      is held in the database as scheduled_job.name
227
 *     forwardto -- If provided, forward to this page when processing is done.
228
 *     qformat -- If provided, render results using the stylesheets associated with
229
 *                this skin.  Default is xml.
230
 * action=deleteScheduledWorkflow -- Delete a workflow.  Deleting a workflow
231
 *                            removes it from the scheduling engine and changes the
232
 *                            status in the scheduled_job table to " deleted.  Note
233
 *                            that this may be extracted into a separate servlet.
234 5045 daigle
 *     workflowjobname -- The job ID for the workflow run that we want to delete.  This
235 5025 daigle
 *                      is held in the database as scheduled_job.name
236
 *     forwardto -- If provided, forward to this page when processing is done.
237
 *     qformat -- If provided, render results using the stylesheets associated with
238
 *                this skin.  Default is xml.
239 8303 tao
 * action=reindex -- rebuild the solr index for the specified pids.
240
 *     pid -- the id of the document which will be rebuilt slor index.
241
 * action=reindexall -- rebuild the solr index for all objects in the systemmetadata table.
242 5018 daigle
 *
243
 * Here are some of the common parameters for actions
244
 *     doctype -- document type list returned by the query (publicID)
245
 *     qformat=xml -- display resultset from query in XML
246
 *     qformat=html -- display resultset from query in HTML
247
 *     qformat=zip -- zip resultset from query
248
 *     docid=34 -- display the document with the document ID number 34
249
 *     doctext -- XML text of the document to load into the database
250
 *     acltext -- XML access text for a document to load into the database
251
 *     dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog
252
 *     query -- actual query text (to go with 'action=query' or 'action=squery')
253
 *     valtext -- XML text to be validated
254
 *     scope --can limit the query by the scope of the id
255
 *     docid --the docid to check
256
 *     datadoc -- data document name (id)
257 46 jones
 */
258 3514 barteau
public class MetaCatServlet extends HttpServlet {
259 4080 daigle
260
	private static final long serialVersionUID = 1L;
261
	private Timer timer = null;
262 5167 daigle
    private static boolean _firstHalfInitialized = false;
263
    private static boolean _fullyInitialized = false;
264 5211 jones
    private MetacatHandler handler = null;
265 2752 jones
266
    // Constants -- these should be final in a servlet
267 2098 jones
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
268
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
269
    public static final String EML2KEYWORD = ":eml";
270 3859 tao
    private static final String FALSE = "false";
271
    private static final String TRUE  = "true";
272 5015 daigle
    private static String LOG_CONFIG_NAME = null;
273 5030 daigle
    public static final String APPLICATION_NAME = "metacat";
274 5752 leinfelder
	public static final String DEFAULT_ENCODING = "UTF-8";
275 2663 sgarg
276 2098 jones
    /**
277
     * Initialize the servlet by creating appropriate database connections
278
     */
279 3514 barteau
    public void init(ServletConfig config) throws ServletException {
280 4080 daigle
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
281
    	try {
282 5167 daigle
    		if(_firstHalfInitialized) {
283 4959 daigle
    			return;
284
    		}
285
286 2098 jones
            super.init(config);
287 3078 jones
288 2752 jones
            ServletContext context = config.getServletContext();
289 5030 daigle
            context.setAttribute("APPLICATION_NAME", APPLICATION_NAME);
290 4698 daigle
291
            ServiceService serviceService = ServiceService.getInstance(context);
292 5167 daigle
            logMetacat.debug("MetaCatServlet.init - ServiceService singleton created " + serviceService);
293 4698 daigle
294 4124 daigle
            // Initialize the properties file
295 4698 daigle
            String dirPath = ServiceService.getRealConfigDir();
296 3099 jones
297 5015 daigle
            LOG_CONFIG_NAME = dirPath + "/log4j.properties";
298 2663 sgarg
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
299
300 4698 daigle
            // Register preliminary services
301 5030 daigle
            ServiceService.registerService("PropertyService", PropertyService.getInstance(context));
302 4698 daigle
            ServiceService.registerService("SkinPropertyService", SkinPropertyService.getInstance());
303
            ServiceService.registerService("SessionService", SessionService.getInstance());
304 6088 cjones
305
            // Check to see if the user has requested to bypass configuration
306 4154 daigle
            // (dev option) and check see if metacat has been configured.
307
    		// If both are false then stop the initialization
308 5025 daigle
            if (!ConfigurationUtil.bypassConfiguration() && !ConfigurationUtil.isMetacatConfigured()) {
309 4080 daigle
            	return;
310 4203 daigle
            }
311 3081 jones
312 5167 daigle
            _firstHalfInitialized = true;
313 4959 daigle
314 4203 daigle
            initSecondHalf(context);
315 2752 jones
316 4203 daigle
    	} catch (ServiceException se) {
317 4080 daigle
        	String errorMessage =
318
        		"Service problem while intializing MetaCat Servlet: " + se.getMessage();
319 5167 daigle
            logMetacat.error("MetaCatServlet.init - " + errorMessage);
320 4080 daigle
            throw new ServletException(errorMessage);
321 5015 daigle
        } catch (MetacatUtilException mue) {
322
        	String errorMessage = "Metacat utility problem while intializing MetaCat Servlet: "
323
        		+ mue.getMessage();
324 5167 daigle
            logMetacat.error("MetaCatServlet.init - " + errorMessage);
325 4698 daigle
            throw new ServletException(errorMessage);
326 4203 daigle
        }
327 2098 jones
    }
328 4203 daigle
329
330
	/**
331
	 * Initialize the remainder of the servlet. This is the part that can only
332
	 * be initialized after metacat properties have been configured
333
	 *
334
	 * @param context
335
	 *            the servlet context of MetaCatServlet
336
	 */
337
	public void initSecondHalf(ServletContext context) throws ServletException {
338 5015 daigle
339 4203 daigle
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
340
341 4698 daigle
		try {
342
			ServiceService.registerService("DatabaseService", DatabaseService.getInstance());
343 4334 daigle
344 4203 daigle
			// initialize DBConnection pool
345
			DBConnectionPool connPool = DBConnectionPool.getInstance();
346 5167 daigle
			logMetacat.debug("MetaCatServlet.initSecondHalf - DBConnection pool initialized: " + connPool.toString());
347 4424 daigle
348 6088 cjones
			// register the XML schema service
349 4698 daigle
			ServiceService.registerService("XMLSchemaService", XMLSchemaService.getInstance());
350 6088 cjones
351 4967 daigle
			// check if eml201 document were corrected or not. if not, correct eml201 documents.
352
			// Before Metacat 1.8.1, metacat uses tag RELEASE_EML_2_0_1_UPDATE_6 as eml
353
			// schema, which accidentily points to wrong version of eml-resource.xsd.
354 5167 daigle
			String correctedEML201Doc = PropertyService.getProperty("document.eml201DocumentCorrected");
355 4203 daigle
			if (correctedEML201Doc != null && correctedEML201Doc.equals(FALSE)) {
356 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Start to correct eml201 documents");
357 4203 daigle
				EML201DocumentCorrector correct = new EML201DocumentCorrector();
358
				boolean success = correct.run();
359
				if (success) {
360 4212 daigle
					PropertyService.setProperty("document.eml201DocumentCorrected", TRUE);
361 4203 daigle
				}
362 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Finish to correct eml201 documents");
363 4203 daigle
			}
364
365
			// Index the paths specified in the metacat.properties
366
			checkIndexPaths();
367
368
			// initiate the indexing Queue
369
			IndexingQueue.getInstance();
370
371
			// start the IndexingThread if indexingTimerTaskTime more than 0.
372
			// It will index all the documents not yet indexed in the database
373
			int indexingTimerTaskTime = Integer.parseInt(PropertyService
374
					.getProperty("database.indexingTimerTaskTime"));
375
			int delayTime = Integer.parseInt(PropertyService
376
					.getProperty("database.indexingInitialDelay"));
377
378
			if (indexingTimerTaskTime > 0) {
379
				timer = new Timer();
380
				timer.schedule(new IndexingTimerTask(), delayTime, indexingTimerTaskTime);
381
			}
382 4327 leinfelder
383 4203 daigle
			/*
384
			 * If spatial option is turned on and set to regenerate the spatial
385
			 * cache on restart, trigger the harvester regeneratation method
386
			 */
387 5311 daigle
			if (PropertyService.getProperty("spatial.runSpatialOption").equals("true") &&
388
					PropertyService.getProperty("spatial.regenerateCacheOnRestart").equals("true")) {
389
390 4203 daigle
				// Begin timer
391
				long before = System.currentTimeMillis();
392
393 5311 daigle
				// if either the point or polygon shape files do not exist, then regenerate the entire spatial cache
394
				// this may be expensive with many documents
395
				SpatialHarvester sh = new SpatialHarvester();
396
				sh.regenerate();
397
				sh.destroy();
398 4203 daigle
399
				// After running the first time, we want to to set
400
				// regenerateCacheOnRestart to false
401
				// so that it does not regenerate the cache every time tomcat is
402
				// restarted
403 5311 daigle
				PropertyService.setProperty("spatial.regenerateCacheOnRestart", "false");
404 4203 daigle
405
				// End timer
406
				long after = System.currentTimeMillis();
407 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial Harvester Time  "
408 4203 daigle
						+ (after - before) + "ms");
409
410
			} else {
411 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial cache is not set to regenerate on restart");
412 4203 daigle
			}
413 5015 daigle
414
			// Set up the replication log file by setting the "replication.logfile.name"
415
			// system property and reconfiguring the log4j property configurator.
416
			String replicationLogPath = PropertyService.getProperty("replication.logdir")
417
				+ FileUtil.getFS() + ReplicationService.REPLICATION_LOG_FILE_NAME;
418
419
			if (FileUtil.getFileStatus(replicationLogPath) == FileUtil.DOES_NOT_EXIST) {
420
				FileUtil.createFile(replicationLogPath);
421
			}
422 4203 daigle
423 5015 daigle
			if (FileUtil.getFileStatus(replicationLogPath) < FileUtil.EXISTS_READ_WRITABLE) {
424 5167 daigle
				logMetacat.error("MetaCatServlet.initSecondHalf - Replication log file: " + replicationLogPath
425 5015 daigle
						+ " does not exist read/writable.");
426
			}
427
428
			System.setProperty("replication.logfile.name", replicationLogPath);
429
			PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
430
431 5374 berkley
			SessionService.getInstance().unRegisterAllSessions();
432 5311 daigle
433 5211 jones
	         //Initialize Metacat Handler
434 5337 berkley
            handler = new MetacatHandler(timer);
435 4203 daigle
436 5311 daigle
			handler.set_sitemapScheduled(false);
437 6031 leinfelder
438
			// initialize the plugins
439
			MetacatHandlerPluginManager.getInstance();
440 6437 leinfelder
441
			// initialize the HazelcastService
442
			ServiceService.registerService("HazelcastService", HazelcastService.getInstance());
443 5211 jones
444 5167 daigle
			_fullyInitialized = true;
445 4203 daigle
446 5167 daigle
			logMetacat.warn("MetaCatServlet.initSecondHalf - Metacat (" + MetacatVersion.getVersionID()
447 4203 daigle
					+ ") initialized.");
448 5015 daigle
449 4203 daigle
		} catch (SQLException e) {
450
			String errorMessage = "SQL problem while intializing MetaCat Servlet: "
451
					+ e.getMessage();
452 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
453 4203 daigle
			throw new ServletException(errorMessage);
454
		} catch (IOException ie) {
455
			String errorMessage = "IO problem while intializing MetaCat Servlet: "
456
					+ ie.getMessage();
457 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
458 4203 daigle
			throw new ServletException(errorMessage);
459
		} catch (GeneralPropertyException gpe) {
460
			String errorMessage = "Could not retrieve property while intializing MetaCat Servlet: "
461
					+ gpe.getMessage();
462 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
463 4203 daigle
			throw new ServletException(errorMessage);
464 4698 daigle
		} catch (ServiceException se) {
465
			String errorMessage = "Service problem while intializing MetaCat Servlet: "
466
				+ se.getMessage();
467 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
468 4698 daigle
			throw new ServletException(errorMessage);
469 5015 daigle
		} catch (UtilException ue) {
470
        	String errorMessage = "Utility problem while intializing MetaCat Servlet: "
471
        		+ ue.getMessage();
472 5167 daigle
            logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
473 5015 daigle
            throw new ServletException(errorMessage);
474
        }
475 4203 daigle
	}
476 3514 barteau
477 2570 jones
    /**
478 4203 daigle
	 * Close all db connections from the pool
479
	 */
480 3514 barteau
    public void destroy() {
481 4811 daigle
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
482 4981 daigle
483
    	ServiceService.stopAllServices();
484
485 2570 jones
        // Close all db connection
486 5167 daigle
        logMetacat.warn("MetaCatServlet.destroy - Destroying MetacatServlet");
487 2759 sgarg
        timer.cancel();
488 2901 sgarg
        IndexingQueue.getInstance().setMetacatRunning(false);
489 2570 jones
        DBConnectionPool.release();
490
    }
491 3514 barteau
492 2570 jones
    /** Handle "GET" method requests from HTTP clients */
493
    public void doGet(HttpServletRequest request, HttpServletResponse response)
494 3514 barteau
    throws ServletException, IOException {
495
496 2570 jones
        // Process the data and send back the response
497
        handleGetOrPost(request, response);
498
    }
499 3514 barteau
500 2570 jones
    /** Handle "POST" method requests from HTTP clients */
501
    public void doPost(HttpServletRequest request, HttpServletResponse response)
502 3514 barteau
    throws ServletException, IOException {
503
504 2570 jones
        // Process the data and send back the response
505
        handleGetOrPost(request, response);
506
    }
507 3514 barteau
508 2098 jones
    /**
509 4203 daigle
	 * Index the paths specified in the metacat.properties
510
	 */
511 2753 jones
    private void checkIndexPaths() {
512 8842 tao
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
513
    	logMetacat.debug("MetaCatServlet.checkIndexPaths - starting....");
514
    	if(!EnabledQueryEngines.getInstance().isEnabled(EnabledQueryEngines.PATHQUERYENGINE)) {
515
    		logMetacat.info("MetaCatServlet.checkIndexPaths - the pathquery is disabled and it does nothing for checking path_index");
516
            return;
517
        }
518
    	logMetacat.debug("MetaCatServlet.checkIndexPaths - after checking is the pathquery enabled or not...");
519
520 4812 daigle
521
        Vector<String> pathsForIndexing = null;
522
        try {
523
        	pathsForIndexing = SystemUtil.getPathsForIndexing();
524 4080 daigle
        }
525 4854 daigle
        catch (MetacatUtilException ue) {
526 4812 daigle
        	pathsForIndexing = null;
527 5167 daigle
            logMetacat.error("MetaCatServlet.checkIndexPaths - not find index paths.  Setting "
528 4812 daigle
            		+ "pathsForIndexing to null: " + ue.getMessage());
529 4080 daigle
        }
530
531 4812 daigle
        if (pathsForIndexing != null && !pathsForIndexing.isEmpty()) {
532 3514 barteau
533 5167 daigle
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Indexing paths specified in metacat.properties....");
534 3514 barteau
535 2521 sgarg
            DBConnection conn = null;
536
            int serialNumber = -1;
537
            PreparedStatement pstmt = null;
538
            PreparedStatement pstmt1 = null;
539
            ResultSet rs = null;
540 3514 barteau
541 4812 daigle
            for (String pathIndex : pathsForIndexing) {
542 5167 daigle
                logMetacat.debug("MetaCatServlet.checkIndexPaths - Checking if '" + pathIndex  + "' is indexed.... ");
543 3514 barteau
544 2521 sgarg
                try {
545
                    //check out DBConnection
546
                    conn = DBConnectionPool.
547 3514 barteau
                            getDBConnection("MetaCatServlet.checkIndexPaths");
548 2521 sgarg
                    serialNumber = conn.getCheckOutSerialNumber();
549 3514 barteau
550 2521 sgarg
                    pstmt = conn.prepareStatement(
551 3514 barteau
                            "SELECT * FROM xml_path_index " + "WHERE path = ?");
552 4812 daigle
                    pstmt.setString(1, pathIndex);
553 3514 barteau
554 2521 sgarg
                    pstmt.execute();
555
                    rs = pstmt.getResultSet();
556 3514 barteau
557 2521 sgarg
                    if (!rs.next()) {
558 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - not indexed yet.");
559 2521 sgarg
                        rs.close();
560
                        pstmt.close();
561
                        conn.increaseUsageCount(1);
562 3514 barteau
563 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Inserting following path in xml_path_index: "
564 4812 daigle
                                + pathIndex);
565
                        if(pathIndex.indexOf("@")<0){
566 3514 barteau
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
567 6012 leinfelder
                                    + "n.nodedata, n.nodedatanumerical, n.nodedatadate, n.parentnodeid"
568 3514 barteau
                                    + " FROM xml_nodes n, xml_index i WHERE"
569
                                    + " i.path = ? and n.parentnodeid=i.nodeid and"
570
                                    + " n.nodetype LIKE 'TEXT' order by n.parentnodeid");
571
                        } else {
572
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
573 6012 leinfelder
                                    + "n.nodedata, n.nodedatanumerical, n.nodedatadate, n.parentnodeid"
574 3514 barteau
                                    + " FROM xml_nodes n, xml_index i WHERE"
575
                                    + " i.path = ? and n.nodeid=i.nodeid and"
576
                                    + " n.nodetype LIKE 'ATTRIBUTE' order by n.parentnodeid");
577
                        }
578 4812 daigle
                        pstmt.setString(1, pathIndex);
579 2521 sgarg
                        pstmt.execute();
580
                        rs = pstmt.getResultSet();
581 3514 barteau
582 2521 sgarg
                        int count = 0;
583 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Executed the select statement for: "
584 4812 daigle
                                + pathIndex);
585 3514 barteau
586 2521 sgarg
                        try {
587
                            while (rs.next()) {
588 3514 barteau
589 2521 sgarg
                                String docid = rs.getString(1);
590
                                String nodedata = rs.getString(2);
591
                                float nodedatanumerical = rs.getFloat(3);
592 6012 leinfelder
                                Timestamp nodedatadate = rs.getTimestamp(4);
593
                                int parentnodeid = rs.getInt(5);
594 3514 barteau
595 2521 sgarg
                                if (!nodedata.trim().equals("")) {
596
                                    pstmt1 = conn.prepareStatement(
597 3514 barteau
                                            "INSERT INTO xml_path_index"
598
                                            + " (docid, path, nodedata, "
599 6012 leinfelder
                                            + "nodedatanumerical, nodedatadate, parentnodeid)"
600
                                            + " VALUES (?, ?, ?, ?, ?, ?)");
601 3514 barteau
602 2521 sgarg
                                    pstmt1.setString(1, docid);
603 4812 daigle
                                    pstmt1.setString(2, pathIndex);
604 2521 sgarg
                                    pstmt1.setString(3, nodedata);
605
                                    pstmt1.setFloat(4, nodedatanumerical);
606 6012 leinfelder
                                    pstmt1.setTimestamp(5, nodedatadate);
607
                                    pstmt1.setInt(6, parentnodeid);
608 3514 barteau
609 2521 sgarg
                                    pstmt1.execute();
610
                                    pstmt1.close();
611 3514 barteau
612 2521 sgarg
                                    count++;
613 3514 barteau
614 2521 sgarg
                                }
615
                            }
616 3514 barteau
                        } catch (Exception e) {
617 5167 daigle
                            logMetacat.error("MetaCatServlet.checkIndexPaths - Exception:" + e.getMessage());
618 2521 sgarg
                            e.printStackTrace();
619
                        }
620 3514 barteau
621 2521 sgarg
                        rs.close();
622
                        pstmt.close();
623
                        conn.increaseUsageCount(1);
624 3514 barteau
625 5167 daigle
                        logMetacat.info("MetaCatServlet.checkIndexPaths - Indexed " + count + " records from xml_nodes for '"
626 4812 daigle
                                + pathIndex + "'");
627 3514 barteau
628 2521 sgarg
                    } else {
629 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - already indexed.");
630 2521 sgarg
                    }
631 3514 barteau
632 2521 sgarg
                    rs.close();
633
                    pstmt.close();
634
                    conn.increaseUsageCount(1);
635 3514 barteau
636 2521 sgarg
                } catch (Exception e) {
637 5167 daigle
                    logMetacat.error("MetaCatServlet.checkIndexPaths - Error in MetaCatServlet.checkIndexPaths: "
638 3514 barteau
                            + e.getMessage());
639 2521 sgarg
                }finally {
640
                    //check in DBonnection
641
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
642
                }
643 3514 barteau
644
645 2521 sgarg
            }
646 3514 barteau
647 5167 daigle
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Path Indexing Completed");
648 2521 sgarg
        }
649 3514 barteau
    }
650
651 2098 jones
    /**
652 4080 daigle
	 * Control servlet response depending on the action parameter specified
653
	 */
654 5167 daigle
	@SuppressWarnings("unchecked")
655 4080 daigle
	private void handleGetOrPost(HttpServletRequest request,
656
			HttpServletResponse response) throws ServletException, IOException {
657
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
658
659 5752 leinfelder
		String requestEncoding = request.getCharacterEncoding();
660 8264 leinfelder
		if (requestEncoding == null) {
661
			logMetacat.debug("null requestEncoding, setting to application default: " + DEFAULT_ENCODING);
662
			request.setCharacterEncoding(DEFAULT_ENCODING);
663
		}
664 5767 leinfelder
		logMetacat.debug("requestEncoding: " + requestEncoding);
665 5752 leinfelder
666 4080 daigle
		// Update the last update time for this user if they are not new
667
		HttpSession httpSession = request.getSession(false);
668
		if (httpSession != null) {
669 5374 berkley
		    SessionService.getInstance().touchSession(httpSession.getId());
670 4080 daigle
		}
671
672 4154 daigle
		// Each time metacat is called, check to see if metacat has been
673
		// configured. If not then forward to the administration servlet
674 5025 daigle
		if (!ConfigurationUtil.isMetacatConfigured()) {
675 5076 daigle
			try {
676
				RequestUtil.forwardRequest(request, response, "/admin?action=configure", null);
677
				return;
678
			} catch (MetacatUtilException mue) {
679
				logMetacat.error("MetacatServlet.handleGetOrPost - utility error when forwarding to " +
680
						"configuration screen: " + mue.getMessage());
681
				throw new ServletException("MetacatServlet.handleGetOrPost - utility error when forwarding to " +
682
						"configuration screen: " + mue.getMessage());
683
			}
684 4080 daigle
		}
685
686 4203 daigle
		// if we get here, metacat is configured.  If we have not completed the
687 4698 daigle
		// second half of the initialization, do so now.  This allows us to initially
688 4203 daigle
		// configure metacat without a restart.
689 5167 daigle
		if (!_fullyInitialized) {
690 4203 daigle
			initSecondHalf(request.getSession().getServletContext());
691
		}
692
693 4080 daigle
		/*
694
		 * logMetacat.debug("Connection pool size: "
695
		 * +connPool.getSizeOfDBConnectionPool(),10); logMetacat.debug("Free
696
		 * DBConnection number: "
697
		 */
698
		// If all DBConnection in the pool are free and DBConnection pool
699
		// size is greater than initial value, shrink the connection pool
700
		// size to initial value
701
		DBConnectionPool.shrinkDBConnectionPoolSize();
702
703
		// Debug message to print out the method which have a busy DBConnection
704
		try {
705 5167 daigle
			@SuppressWarnings("unused")
706 4080 daigle
			DBConnectionPool pool = DBConnectionPool.getInstance();
707 5167 daigle
//			pool.printMethodNameHavingBusyDBConnection();
708 4080 daigle
		} catch (SQLException e) {
709 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - Error in MetacatServlet.handleGetOrPost: " + e.getMessage());
710 4080 daigle
			e.printStackTrace();
711
		}
712
713
		try {
714
			String ctype = request.getContentType();
715 5211 jones
716 4080 daigle
			if (ctype != null && ctype.startsWith("multipart/form-data")) {
717 5211 jones
				handler.handleMultipartForm(request, response);
718 5030 daigle
				return;
719
			}
720 4080 daigle
721 5030 daigle
			String name = null;
722
			String[] value = null;
723
			String[] docid = new String[3];
724
			Hashtable<String, String[]> params = new Hashtable<String, String[]>();
725 4080 daigle
726 5030 daigle
			// Check if this is a simple read request that doesn't use the
727
			// "action" syntax
728
			// These URLs are of the form:
729 8265 leinfelder
			// http://localhost:8180/metacat/metacat/docid/skinname
730
			// e.g., http://localhost:8180/metacat/metacat/test.1.1/knb
731 5030 daigle
			String pathInfo = request.getPathInfo();
732
			if (pathInfo != null) {
733
				String[] path = pathInfo.split("/");
734
				if (path.length > 1) {
735
					String docidToRead = path[1];
736
					String docs[] = new String[1];
737
					docs[0] = docidToRead;
738 5167 daigle
					logMetacat.debug("MetaCatServlet.handleGetOrPost - READING DOCID FROM PATHINFO: " + docs[0]);
739 5030 daigle
					params.put("docid", docs);
740
					String skin = null;
741
					if (path.length > 2) {
742
						skin = path[2];
743
						String skins[] = new String[1];
744
						skins[0] = skin;
745
						params.put("qformat", skins);
746 4080 daigle
					}
747 8764 leinfelder
748
					// attempt to redirect to metacatui (#view/{pid}) if not getting the raw XML
749
					// see: https://projects.ecoinformatics.org/ecoinfo/issues/6546
750
					if (!skin.equals("xml")) {
751
						String uiContext = PropertyService.getProperty("ui.context");
752
						String docidNoRev = DocumentUtil.getDocIdFromAccessionNumber(docidToRead);
753
						int rev = DocumentUtil.getRevisionFromAccessionNumber(docidToRead);
754
						String pid = null;
755
						try {
756
							pid = IdentifierManager.getInstance().getGUID(docidNoRev, rev);
757
							response.sendRedirect(SystemUtil.getServerURL() + "/" + uiContext + "/#view/" + pid );
758
							return;
759
						} catch (McdbDocNotFoundException nfe) {
760
							logMetacat.warn("Could not locate PID for docid: " + docidToRead, nfe);
761
						}
762
					}
763
764
					// otherwise carry on as usual
765 5211 jones
					handler.handleReadAction(params, request, response, "public", null, null);
766 5030 daigle
					return;
767 4080 daigle
				}
768 5030 daigle
			}
769 4080 daigle
770 5030 daigle
			Enumeration<String> paramlist =
771
				(Enumeration<String>) request.getParameterNames();
772
			while (paramlist.hasMoreElements()) {
773 4080 daigle
774 5030 daigle
				name = paramlist.nextElement();
775
				value = request.getParameterValues(name);
776 4080 daigle
777 5030 daigle
				// Decode the docid and mouse click information
778
				// THIS IS OBSOLETE -- I THINK -- REMOVE THIS BLOCK
779
				// 4/12/2007d
780
				// MBJ
781
				if (name.endsWith(".y")) {
782
					docid[0] = name.substring(0, name.length() - 2);
783
					params.put("docid", docid);
784
					name = "ypos";
785 4080 daigle
				}
786 5030 daigle
				if (name.endsWith(".x")) {
787
					name = "xpos";
788 4080 daigle
				}
789
790 5030 daigle
				params.put(name, value);
791
			}
792 4080 daigle
793 5030 daigle
			// handle param is emptpy
794
			if (params.isEmpty() || params == null) {
795
				return;
796
			}
797 4080 daigle
798 5030 daigle
			// if the user clicked on the input images, decode which image
799
			// was clicked then set the action.
800
			if (params.get("action") == null) {
801
				PrintWriter out = response.getWriter();
802
				response.setContentType("text/xml");
803
				out.println("<?xml version=\"1.0\"?>");
804
				out.println("<error>");
805
				out.println("Action not specified");
806
				out.println("</error>");
807
				out.close();
808
				return;
809
			}
810 4080 daigle
811 5030 daigle
			String action = (params.get("action"))[0];
812 5167 daigle
			logMetacat.info("MetaCatServlet.handleGetOrPost - Action is: " + action);
813 4080 daigle
814 5030 daigle
			// This block handles session management for the servlet
815
			// by looking up the current session information for all actions
816
			// other than "login" and "logout"
817
			String userName = null;
818
			String password = null;
819
			String[] groupNames = null;
820
			String sessionId = null;
821
			name = null;
822 4080 daigle
823 5030 daigle
			// handle login action
824
			if (action.equals("login")) {
825 8588 leinfelder
				//PrintWriter out = response.getWriter();
826
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
827 5211 jones
				handler.handleLoginAction(out, params, request, response);
828 5030 daigle
				out.close();
829 4080 daigle
830 5030 daigle
				// handle logout action
831
			} else if (action.equals("logout")) {
832 8588 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
833 5211 jones
				handler.handleLogoutAction(out, params, request, response);
834 5030 daigle
				out.close();
835 4080 daigle
836 8588 leinfelder
				// handle session validate request
837 5041 daigle
			} else if (action.equals("validatesession")) {
838 8588 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
839 5041 daigle
				String idToValidate = null;
840
				String idsToValidate[] = params.get("sessionid");
841
				if (idsToValidate != null) {
842
					idToValidate = idsToValidate[0];
843 8075 leinfelder
				} else {
844
					// use the sessionid from the cookie
845
					SessionData sessionData = RequestUtil.getSessionData(request);
846
					if (sessionData != null) {
847
						idToValidate = sessionData.getId();
848
					}
849 5041 daigle
				}
850 5374 berkley
				SessionService.getInstance().validateSession(out, response, idToValidate);
851 5041 daigle
				out.close();
852
853
				// handle shrink DBConnection request
854 5030 daigle
			} else if (action.equals("shrink")) {
855
				PrintWriter out = response.getWriter();
856
				boolean success = false;
857
				// If all DBConnection in the pool are free and DBConnection
858
				// pool
859
				// size is greater than initial value, shrink the connection
860
				// pool
861
				// size to initial value
862
				success = DBConnectionPool.shrinkConnectionPoolSize();
863
				if (success) {
864
					// if successfully shrink the pool size to initial value
865
					out.println("DBConnection Pool shrunk successfully.");
866
				}// if
867
				else {
868
					out.println("DBConnection pool not shrunk successfully.");
869 4080 daigle
				}
870 5030 daigle
				// close out put
871
				out.close();
872 4080 daigle
873 5030 daigle
				// aware of session expiration on every request
874
			} else {
875
				SessionData sessionData = RequestUtil.getSessionData(request);
876 5159 daigle
877
				if (sessionData != null) {
878
					userName = sessionData.getUserName();
879
					password = sessionData.getPassword();
880
					groupNames = sessionData.getGroupNames();
881
					sessionId = sessionData.getId();
882
				}
883 4080 daigle
884 5167 daigle
				logMetacat.info("MetaCatServlet.handleGetOrPost - The user is : " + userName);
885 5030 daigle
			}
886
			// Now that we know the session is valid, we can delegate the
887
			// request to a particular action handler
888
			if (action.equals("query")) {
889 5752 leinfelder
		        Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
890 5211 jones
				handler.handleQuery(out, params, response, userName, groupNames, sessionId);
891 5030 daigle
				out.close();
892
			} else if (action.equals("squery")) {
893 5752 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
894 5030 daigle
				if (params.containsKey("query")) {
895 5211 jones
					handler.handleSQuery(out, params, response, userName, groupNames, sessionId);
896 5030 daigle
					out.close();
897
				} else {
898 5752 leinfelder
					out.write("Illegal action squery without \"query\" parameter");
899 5030 daigle
					out.close();
900 4221 leinfelder
				}
901 5030 daigle
			} else if (action.trim().equals("spatial_query")) {
902 4221 leinfelder
903 5030 daigle
				logMetacat
904 5167 daigle
						.debug("MetaCatServlet.handleGetOrPost - ******************* SPATIAL QUERY ********************");
905 5752 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
906 5211 jones
				handler.handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
907 5030 daigle
				out.close();
908
909
			} else if (action.trim().equals("dataquery")) {
910
911 5167 daigle
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* DATA QUERY ********************");
912 5211 jones
				handler.handleDataquery(params, response, sessionId);
913 5030 daigle
			} else if (action.trim().equals("editcart")) {
914 5167 daigle
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* EDIT CART ********************");
915 5211 jones
				handler.handleEditCart(params, response, sessionId);
916 5030 daigle
			} else if (action.equals("export")) {
917
918 5211 jones
				handler.handleExportAction(params, response, userName, groupNames, password);
919 5030 daigle
			} else if (action.equals("read")) {
920
				if (params.get("archiveEntryName") != null) {
921
					ArchiveHandler.getInstance().readArchiveEntry(params, request,
922
							response, userName, password, groupNames);
923
				} else {
924 5211 jones
					handler.handleReadAction(params, request, response, userName, password,
925 4295 daigle
							groupNames);
926 5030 daigle
				}
927
			} else if (action.equals("readinlinedata")) {
928 5211 jones
				handler.handleReadInlineDataAction(params, request, response, userName, password,
929 5030 daigle
						groupNames);
930
			} else if (action.equals("insert") || action.equals("update")) {
931
				PrintWriter out = response.getWriter();
932
				if ((userName != null) && !userName.equals("public")) {
933 6542 leinfelder
					handler.handleInsertOrUpdateAction(request.getRemoteAddr(), request.getHeader("User-Agent"), response, out, params, userName,
934 8948 tao
							groupNames, true, true, null);
935 5030 daigle
				} else {
936 4080 daigle
					response.setContentType("text/xml");
937
					out.println("<?xml version=\"1.0\"?>");
938 5030 daigle
					out.println("<error>");
939 8792 leinfelder
					String cleanMessage = StringEscapeUtils.escapeXml("Permission denied for user " + userName + " " + action);
940
					out.println(cleanMessage);
941 5030 daigle
					out.println("</error>");
942
				}
943
				out.close();
944
			} else if (action.equals("delete")) {
945
				PrintWriter out = response.getWriter();
946
				if ((userName != null) && !userName.equals("public")) {
947 5211 jones
					handler.handleDeleteAction(out, params, request, response, userName,
948 4295 daigle
							groupNames);
949 4950 daigle
				} else {
950 5030 daigle
					response.setContentType("text/xml");
951 4080 daigle
					out.println("<?xml version=\"1.0\"?>");
952
					out.println("<error>");
953 8792 leinfelder
					String cleanMessage = StringEscapeUtils.escapeXml("Permission denied for " + action);
954
					out.println(cleanMessage);
955 4080 daigle
					out.println("</error>");
956
				}
957 5030 daigle
				out.close();
958
			} else if (action.equals("validate")) {
959
				PrintWriter out = response.getWriter();
960 5211 jones
				handler.handleValidateAction(out, params);
961 5030 daigle
				out.close();
962
			} else if (action.equals("setaccess")) {
963
				PrintWriter out = response.getWriter();
964 5211 jones
				handler.handleSetAccessAction(out, params, userName, request, response);
965 5030 daigle
				out.close();
966
			} else if (action.equals("getaccesscontrol")) {
967
				PrintWriter out = response.getWriter();
968 5211 jones
				handler.handleGetAccessControlAction(out, params, response, userName, groupNames);
969 5030 daigle
				out.close();
970 5071 daigle
			} else if (action.equals("isauthorized")) {
971
				PrintWriter out = response.getWriter();
972
				DocumentUtil.isAuthorized(out, params, request, response);
973
				out.close();
974 5030 daigle
			} else if (action.equals("getprincipals")) {
975 8588 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
976 5211 jones
				handler.handleGetPrincipalsAction(out, userName, password);
977 5030 daigle
				out.close();
978
			} else if (action.equals("getdoctypes")) {
979
				PrintWriter out = response.getWriter();
980 5211 jones
				handler.handleGetDoctypesAction(out, params, response);
981 5030 daigle
				out.close();
982
			} else if (action.equals("getdtdschema")) {
983
				PrintWriter out = response.getWriter();
984 5211 jones
				handler.handleGetDTDSchemaAction(out, params, response);
985 5030 daigle
				out.close();
986 7695 leinfelder
			} else if (action.equals("getdocid")) {
987
				handler.handleGetDocid(params, response);
988 5030 daigle
			} else if (action.equals("getlastdocid")) {
989
				PrintWriter out = response.getWriter();
990 5211 jones
				handler.handleGetMaxDocidAction(out, params, response);
991 5030 daigle
				out.close();
992
			} else if (action.equals("getalldocids")) {
993
				PrintWriter out = response.getWriter();
994 5211 jones
				handler.handleGetAllDocidsAction(out, params, response);
995 5030 daigle
				out.close();
996
			} else if (action.equals("isregistered")) {
997
				PrintWriter out = response.getWriter();
998 5211 jones
				handler.handleIdIsRegisteredAction(out, params, response);
999 5030 daigle
				out.close();
1000
			} else if (action.equals("getrevisionanddoctype")) {
1001
				PrintWriter out = response.getWriter();
1002 5211 jones
				handler.handleGetRevisionAndDocTypeAction(out, params);
1003 5030 daigle
				out.close();
1004
			} else if (action.equals("getversion")) {
1005
				response.setContentType("text/xml");
1006
				PrintWriter out = response.getWriter();
1007
				out.println(MetacatVersion.getVersionAsXml());
1008
				out.close();
1009
			} else if (action.equals("getlog")) {
1010 7404 leinfelder
				handler.handleGetLogAction(params, request, response, userName, groupNames, sessionId);
1011 5030 daigle
			} else if (action.equals("getloggedinuserinfo")) {
1012
				PrintWriter out = response.getWriter();
1013
				response.setContentType("text/xml");
1014
				out.println("<?xml version=\"1.0\"?>");
1015
				out.println("\n<user>\n");
1016
				out.println("\n<username>\n");
1017
				out.println(userName);
1018
				out.println("\n</username>\n");
1019
				if (name != null) {
1020
					out.println("\n<name>\n");
1021
					out.println(name);
1022
					out.println("\n</name>\n");
1023
				}
1024
				if (AuthUtil.isAdministrator(userName, groupNames)) {
1025
					out.println("<isAdministrator></isAdministrator>\n");
1026
				}
1027
				if (AuthUtil.isModerator(userName, groupNames)) {
1028
					out.println("<isModerator></isModerator>\n");
1029
				}
1030
				out.println("\n</user>\n");
1031
				out.close();
1032
			} else if (action.equals("buildindex")) {
1033 5211 jones
				handler.handleBuildIndexAction(params, request, response, userName, groupNames);
1034 7843 leinfelder
			} else if (action.equals("reindex")) {
1035
				handler.handleReindexAction(params, request, response, userName, groupNames);
1036 8303 tao
			} else if (action.equals("reindexall")) {
1037
                handler.handleReindexAllAction(params, request, response, userName, groupNames);
1038
            } else if (action.equals("login") || action.equals("logout")) {
1039 5030 daigle
				/*
1040
				 * } else if (action.equals("protocoltest")) { String testURL =
1041
				 * "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9"; try { testURL =
1042
				 * ((String[]) params.get("url"))[0]; } catch (Throwable t) { }
1043
				 * String phandler = System
1044
				 * .getProperty("java.protocol.handler.pkgs");
1045
				 * response.setContentType("text/html"); PrintWriter out =
1046
				 * response.getWriter(); out.println("<body
1047
				 * bgcolor=\"white\">"); out.println("<p>Handler property:
1048
				 * <code>" + phandler + "</code></p>"); out.println("<p>Starting
1049
				 * test for:<br>"); out.println(" " + testURL + "</p>"); try {
1050
				 * URL u = new URL(testURL); out.println("<pre>");
1051
				 * out.println("Protocol: " + u.getProtocol()); out.println("
1052
				 * Host: " + u.getHost()); out.println(" Port: " + u.getPort());
1053
				 * out.println(" Path: " + u.getPath()); out.println(" Ref: " +
1054
				 * u.getRef()); String pquery = u.getQuery(); out.println("
1055
				 * Query: " + pquery); out.println(" Params: "); if (pquery !=
1056
				 * null) { Hashtable qparams =
1057
				 * MetacatUtil.parseQuery(u.getQuery()); for (Enumeration en =
1058
				 * qparams.keys(); en .hasMoreElements();) { String pname =
1059
				 * (String) en.nextElement(); String pvalue = (String)
1060
				 * qparams.get(pname); out.println(" " + pname + ": " + pvalue); } }
1061
				 * out.println("</pre>"); out.println("</body>");
1062
				 * out.close(); } catch (MalformedURLException mue) {
1063
				 * System.out.println( "bad url from
1064
				 * MetacatServlet.handleGetOrPost");
1065
				 * out.println(mue.getMessage()); mue.printStackTrace(out);
1066
				 * out.close(); }
1067
				 */
1068
			} else if (action.equals("refreshServices")) {
1069
				// TODO MCD this interface is for testing. It should go through
1070 5041 daigle
				// a ServiceService class and only work for an admin user. Move
1071
				// to the MetacatAdminServlet
1072 5030 daigle
				ServiceService.refreshService("XMLSchemaService");
1073
				return;
1074
			} else if (action.equals("scheduleWorkflow")) {
1075
				try {
1076
					WorkflowSchedulerClient.getInstance().scheduleJob(request, response,
1077
							params, userName, groupNames);
1078
					return;
1079
				} catch (BaseException be) {
1080
					ResponseUtil.sendErrorXML(response,
1081
							ResponseUtil.SCHEDULE_WORKFLOW_ERROR, be);
1082
					return;
1083
				}
1084
			} else if (action.equals("unscheduleWorkflow")) {
1085
				try {
1086
					WorkflowSchedulerClient.getInstance().unScheduleJob(request,
1087
							response, params, userName, groupNames);
1088
					return;
1089
				} catch (BaseException be) {
1090
					ResponseUtil.sendErrorXML(response,
1091
							ResponseUtil.UNSCHEDULE_WORKFLOW_ERROR, be);
1092
					return;
1093
				}
1094
			} else if (action.equals("rescheduleWorkflow")) {
1095
				try {
1096
					WorkflowSchedulerClient.getInstance().reScheduleJob(request,
1097
							response, params, userName, groupNames);
1098
					return;
1099
				} catch (BaseException be) {
1100
					ResponseUtil.sendErrorXML(response,
1101
							ResponseUtil.RESCHEDULE_WORKFLOW_ERROR, be);
1102
					return;
1103
				}
1104
			} else if (action.equals("getScheduledWorkflow")) {
1105
				try {
1106
					WorkflowSchedulerClient.getInstance().getJobs(request, response,
1107
							params, userName, groupNames);
1108
					return;
1109
				} catch (BaseException be) {
1110
					ResponseUtil.sendErrorXML(response,
1111
							ResponseUtil.GET_SCHEDULED_WORKFLOW_ERROR, be);
1112
					return;
1113
				}
1114
			} else if (action.equals("deleteScheduledWorkflow")) {
1115
				try {
1116
					WorkflowSchedulerClient.getInstance().deleteJob(request, response,
1117
							params, userName, groupNames);
1118
					return;
1119
				} catch (BaseException be) {
1120
					ResponseUtil.sendErrorXML(response,
1121
							ResponseUtil.DELETE_SCHEDULED_WORKFLOW_ERROR, be);
1122
					return;
1123
				}
1124 4080 daigle
1125 5030 daigle
			} else {
1126 5518 leinfelder
				//try the plugin handler if it has an entry for handling this action
1127
				MetacatHandlerPlugin handlerPlugin = MetacatHandlerPluginManager.getInstance().getHandler(action);
1128
				if (handlerPlugin != null) {
1129
					handlerPlugin.handleAction(action, params, request, response, userName, groupNames, sessionId);
1130
				}
1131
				else {
1132
					PrintWriter out = response.getWriter();
1133
					out.println("<?xml version=\"1.0\"?>");
1134
					out.println("<error>");
1135 8792 leinfelder
					String cleanMessage = StringEscapeUtils.escapeXml("Error: action: " + action + " not registered.  Please report this error.");
1136
					out.println(cleanMessage);
1137 5518 leinfelder
					out.println("</error>");
1138
					out.close();
1139
				}
1140 5030 daigle
			}
1141 4080 daigle
1142 5030 daigle
			// Schedule the sitemap generator to run periodically
1143 5211 jones
			handler.scheduleSitemapGeneration(request);
1144 5030 daigle
1145
1146 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
1147
			String errorString = "Critical property not found: " + pnfe.getMessage();
1148 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1149 4080 daigle
			throw new ServletException(errorString);
1150 4854 daigle
		} catch (MetacatUtilException ue) {
1151 4080 daigle
			String errorString = "Utility error: " + ue.getMessage();
1152 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1153 4080 daigle
			throw new ServletException(errorString);
1154 4698 daigle
		} catch (ServiceException ue) {
1155
			String errorString = "Service error: " + ue.getMessage();
1156 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1157 4698 daigle
			throw new ServletException(errorString);
1158 4950 daigle
		} catch (HandlerException he) {
1159
			String errorString = "Handler error: " + he.getMessage();
1160 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1161 4950 daigle
			throw new ServletException(errorString);
1162
		} catch (ErrorSendingErrorException esee) {
1163
			String errorString = "Error sending error message: " + esee.getMessage();
1164 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1165 4950 daigle
			throw new ServletException(errorString);
1166
		} catch (ErrorHandledException ehe) {
1167
			// Nothing to do here.  We assume if we get here, the error has been
1168
			// written to ouput.  Continue on and let it display.
1169 4959 daigle
		}
1170 4080 daigle
	}
1171 3514 barteau
1172 2912 harris
    /**
1173 4203 daigle
     * Reports whether the MetaCatServlet has been fully initialized
1174
     *
1175
     * @return true if fully intialized, false otherwise
1176
     */
1177
    public static boolean isFullyInitialized() {
1178 5167 daigle
    	return _fullyInitialized;
1179 4203 daigle
    }
1180 46 jones
}