Project

General

Profile

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