Project

General

Profile

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