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