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 3514 barteau
300 4154 daigle
    		// Check to see if the user has requested to bypass configuration
301
            // (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 4698 daigle
			ServiceService.registerService("XMLSchemaService", XMLSchemaService.getInstance());
344 4203 daigle
345 4967 daigle
			// check if eml201 document were corrected or not. if not, correct eml201 documents.
346
			// Before Metacat 1.8.1, metacat uses tag RELEASE_EML_2_0_1_UPDATE_6 as eml
347
			// schema, which accidentily points to wrong version of eml-resource.xsd.
348 5167 daigle
			String correctedEML201Doc = PropertyService.getProperty("document.eml201DocumentCorrected");
349 4203 daigle
			if (correctedEML201Doc != null && correctedEML201Doc.equals(FALSE)) {
350 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Start to correct eml201 documents");
351 4203 daigle
				EML201DocumentCorrector correct = new EML201DocumentCorrector();
352
				boolean success = correct.run();
353
				if (success) {
354 4212 daigle
					PropertyService.setProperty("document.eml201DocumentCorrected", TRUE);
355 4203 daigle
				}
356 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Finish to correct eml201 documents");
357 4203 daigle
			}
358
359
			// Index the paths specified in the metacat.properties
360
			checkIndexPaths();
361
362
			// initiate the indexing Queue
363
			IndexingQueue.getInstance();
364
365
			// start the IndexingThread if indexingTimerTaskTime more than 0.
366
			// It will index all the documents not yet indexed in the database
367
			int indexingTimerTaskTime = Integer.parseInt(PropertyService
368
					.getProperty("database.indexingTimerTaskTime"));
369
			int delayTime = Integer.parseInt(PropertyService
370
					.getProperty("database.indexingInitialDelay"));
371
372
			if (indexingTimerTaskTime > 0) {
373
				timer = new Timer();
374
				timer.schedule(new IndexingTimerTask(), delayTime, indexingTimerTaskTime);
375
			}
376 4327 leinfelder
377 4203 daigle
			/*
378
			 * If spatial option is turned on and set to regenerate the spatial
379
			 * cache on restart, trigger the harvester regeneratation method
380
			 */
381 5311 daigle
			if (PropertyService.getProperty("spatial.runSpatialOption").equals("true") &&
382
					PropertyService.getProperty("spatial.regenerateCacheOnRestart").equals("true")) {
383
384 4203 daigle
				// Begin timer
385
				long before = System.currentTimeMillis();
386
387 5311 daigle
				// if either the point or polygon shape files do not exist, then regenerate the entire spatial cache
388
				// this may be expensive with many documents
389
				SpatialHarvester sh = new SpatialHarvester();
390
				sh.regenerate();
391
				sh.destroy();
392 4203 daigle
393
				// After running the first time, we want to to set
394
				// regenerateCacheOnRestart to false
395
				// so that it does not regenerate the cache every time tomcat is
396
				// restarted
397 5311 daigle
				PropertyService.setProperty("spatial.regenerateCacheOnRestart", "false");
398 4203 daigle
399
				// End timer
400
				long after = System.currentTimeMillis();
401 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial Harvester Time  "
402 4203 daigle
						+ (after - before) + "ms");
403
404
			} else {
405 5167 daigle
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial cache is not set to regenerate on restart");
406 4203 daigle
			}
407 5015 daigle
408
			// Set up the replication log file by setting the "replication.logfile.name"
409
			// system property and reconfiguring the log4j property configurator.
410
			String replicationLogPath = PropertyService.getProperty("replication.logdir")
411
				+ FileUtil.getFS() + ReplicationService.REPLICATION_LOG_FILE_NAME;
412
413
			if (FileUtil.getFileStatus(replicationLogPath) == FileUtil.DOES_NOT_EXIST) {
414
				FileUtil.createFile(replicationLogPath);
415
			}
416 4203 daigle
417 5015 daigle
			if (FileUtil.getFileStatus(replicationLogPath) < FileUtil.EXISTS_READ_WRITABLE) {
418 5167 daigle
				logMetacat.error("MetaCatServlet.initSecondHalf - Replication log file: " + replicationLogPath
419 5015 daigle
						+ " does not exist read/writable.");
420
			}
421
422
			System.setProperty("replication.logfile.name", replicationLogPath);
423
			PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
424
425 5374 berkley
			SessionService.getInstance().unRegisterAllSessions();
426 5311 daigle
427 5211 jones
	         //Initialize Metacat Handler
428 5337 berkley
            handler = new MetacatHandler(timer);
429 4203 daigle
430 5311 daigle
			handler.set_sitemapScheduled(false);
431 5211 jones
432 5167 daigle
			_fullyInitialized = true;
433 4203 daigle
434 5167 daigle
			logMetacat.warn("MetaCatServlet.initSecondHalf - Metacat (" + MetacatVersion.getVersionID()
435 4203 daigle
					+ ") initialized.");
436 5015 daigle
437 4203 daigle
		} catch (SQLException e) {
438
			String errorMessage = "SQL problem while intializing MetaCat Servlet: "
439
					+ e.getMessage();
440 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
441 4203 daigle
			throw new ServletException(errorMessage);
442
		} catch (IOException ie) {
443
			String errorMessage = "IO problem while intializing MetaCat Servlet: "
444
					+ ie.getMessage();
445 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
446 4203 daigle
			throw new ServletException(errorMessage);
447
		} catch (GeneralPropertyException gpe) {
448
			String errorMessage = "Could not retrieve property while intializing MetaCat Servlet: "
449
					+ gpe.getMessage();
450 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
451 4203 daigle
			throw new ServletException(errorMessage);
452 4698 daigle
		} catch (ServiceException se) {
453
			String errorMessage = "Service problem while intializing MetaCat Servlet: "
454
				+ se.getMessage();
455 5167 daigle
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
456 4698 daigle
			throw new ServletException(errorMessage);
457 5015 daigle
		} catch (UtilException ue) {
458
        	String errorMessage = "Utility problem while intializing MetaCat Servlet: "
459
        		+ ue.getMessage();
460 5167 daigle
            logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
461 5015 daigle
            throw new ServletException(errorMessage);
462
        }
463 4203 daigle
	}
464 3514 barteau
465 2570 jones
    /**
466 4203 daigle
	 * Close all db connections from the pool
467
	 */
468 3514 barteau
    public void destroy() {
469 4811 daigle
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
470 4981 daigle
471
    	ServiceService.stopAllServices();
472
473 2570 jones
        // Close all db connection
474 5167 daigle
        logMetacat.warn("MetaCatServlet.destroy - Destroying MetacatServlet");
475 2759 sgarg
        timer.cancel();
476 2901 sgarg
        IndexingQueue.getInstance().setMetacatRunning(false);
477 2570 jones
        DBConnectionPool.release();
478
    }
479 3514 barteau
480 2570 jones
    /** Handle "GET" method requests from HTTP clients */
481
    public void doGet(HttpServletRequest request, HttpServletResponse response)
482 3514 barteau
    throws ServletException, IOException {
483
484 2570 jones
        // Process the data and send back the response
485
        handleGetOrPost(request, response);
486
    }
487 3514 barteau
488 2570 jones
    /** Handle "POST" method requests from HTTP clients */
489
    public void doPost(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 2098 jones
    /**
497 4203 daigle
	 * Index the paths specified in the metacat.properties
498
	 */
499 2753 jones
    private void checkIndexPaths() {
500
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
501 4812 daigle
502
        Vector<String> pathsForIndexing = null;
503
        try {
504
        	pathsForIndexing = SystemUtil.getPathsForIndexing();
505 4080 daigle
        }
506 4854 daigle
        catch (MetacatUtilException ue) {
507 4812 daigle
        	pathsForIndexing = null;
508 5167 daigle
            logMetacat.error("MetaCatServlet.checkIndexPaths - not find index paths.  Setting "
509 4812 daigle
            		+ "pathsForIndexing to null: " + ue.getMessage());
510 4080 daigle
        }
511
512 4812 daigle
        if (pathsForIndexing != null && !pathsForIndexing.isEmpty()) {
513 3514 barteau
514 5167 daigle
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Indexing paths specified in metacat.properties....");
515 3514 barteau
516 2521 sgarg
            DBConnection conn = null;
517
            int serialNumber = -1;
518
            PreparedStatement pstmt = null;
519
            PreparedStatement pstmt1 = null;
520
            ResultSet rs = null;
521 3514 barteau
522 4812 daigle
            for (String pathIndex : pathsForIndexing) {
523 5167 daigle
                logMetacat.debug("MetaCatServlet.checkIndexPaths - Checking if '" + pathIndex  + "' is indexed.... ");
524 3514 barteau
525 2521 sgarg
                try {
526
                    //check out DBConnection
527
                    conn = DBConnectionPool.
528 3514 barteau
                            getDBConnection("MetaCatServlet.checkIndexPaths");
529 2521 sgarg
                    serialNumber = conn.getCheckOutSerialNumber();
530 3514 barteau
531 2521 sgarg
                    pstmt = conn.prepareStatement(
532 3514 barteau
                            "SELECT * FROM xml_path_index " + "WHERE path = ?");
533 4812 daigle
                    pstmt.setString(1, pathIndex);
534 3514 barteau
535 2521 sgarg
                    pstmt.execute();
536
                    rs = pstmt.getResultSet();
537 3514 barteau
538 2521 sgarg
                    if (!rs.next()) {
539 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - not indexed yet.");
540 2521 sgarg
                        rs.close();
541
                        pstmt.close();
542
                        conn.increaseUsageCount(1);
543 3514 barteau
544 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Inserting following path in xml_path_index: "
545 4812 daigle
                                + pathIndex);
546
                        if(pathIndex.indexOf("@")<0){
547 3514 barteau
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
548 6012 leinfelder
                                    + "n.nodedata, n.nodedatanumerical, n.nodedatadate, n.parentnodeid"
549 3514 barteau
                                    + " FROM xml_nodes n, xml_index i WHERE"
550
                                    + " i.path = ? and n.parentnodeid=i.nodeid and"
551
                                    + " n.nodetype LIKE 'TEXT' order by n.parentnodeid");
552
                        } else {
553
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
554 6012 leinfelder
                                    + "n.nodedata, n.nodedatanumerical, n.nodedatadate, n.parentnodeid"
555 3514 barteau
                                    + " FROM xml_nodes n, xml_index i WHERE"
556
                                    + " i.path = ? and n.nodeid=i.nodeid and"
557
                                    + " n.nodetype LIKE 'ATTRIBUTE' order by n.parentnodeid");
558
                        }
559 4812 daigle
                        pstmt.setString(1, pathIndex);
560 2521 sgarg
                        pstmt.execute();
561
                        rs = pstmt.getResultSet();
562 3514 barteau
563 2521 sgarg
                        int count = 0;
564 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Executed the select statement for: "
565 4812 daigle
                                + pathIndex);
566 3514 barteau
567 2521 sgarg
                        try {
568
                            while (rs.next()) {
569 3514 barteau
570 2521 sgarg
                                String docid = rs.getString(1);
571
                                String nodedata = rs.getString(2);
572
                                float nodedatanumerical = rs.getFloat(3);
573 6012 leinfelder
                                Timestamp nodedatadate = rs.getTimestamp(4);
574
                                int parentnodeid = rs.getInt(5);
575 3514 barteau
576 2521 sgarg
                                if (!nodedata.trim().equals("")) {
577
                                    pstmt1 = conn.prepareStatement(
578 3514 barteau
                                            "INSERT INTO xml_path_index"
579
                                            + " (docid, path, nodedata, "
580 6012 leinfelder
                                            + "nodedatanumerical, nodedatadate, parentnodeid)"
581
                                            + " VALUES (?, ?, ?, ?, ?, ?)");
582 3514 barteau
583 2521 sgarg
                                    pstmt1.setString(1, docid);
584 4812 daigle
                                    pstmt1.setString(2, pathIndex);
585 2521 sgarg
                                    pstmt1.setString(3, nodedata);
586
                                    pstmt1.setFloat(4, nodedatanumerical);
587 6012 leinfelder
                                    pstmt1.setTimestamp(5, nodedatadate);
588
                                    pstmt1.setInt(6, parentnodeid);
589 3514 barteau
590 2521 sgarg
                                    pstmt1.execute();
591
                                    pstmt1.close();
592 3514 barteau
593 2521 sgarg
                                    count++;
594 3514 barteau
595 2521 sgarg
                                }
596
                            }
597 3514 barteau
                        } catch (Exception e) {
598 5167 daigle
                            logMetacat.error("MetaCatServlet.checkIndexPaths - Exception:" + e.getMessage());
599 2521 sgarg
                            e.printStackTrace();
600
                        }
601 3514 barteau
602 2521 sgarg
                        rs.close();
603
                        pstmt.close();
604
                        conn.increaseUsageCount(1);
605 3514 barteau
606 5167 daigle
                        logMetacat.info("MetaCatServlet.checkIndexPaths - Indexed " + count + " records from xml_nodes for '"
607 4812 daigle
                                + pathIndex + "'");
608 3514 barteau
609 2521 sgarg
                    } else {
610 5167 daigle
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - already indexed.");
611 2521 sgarg
                    }
612 3514 barteau
613 2521 sgarg
                    rs.close();
614
                    pstmt.close();
615
                    conn.increaseUsageCount(1);
616 3514 barteau
617 2521 sgarg
                } catch (Exception e) {
618 5167 daigle
                    logMetacat.error("MetaCatServlet.checkIndexPaths - Error in MetaCatServlet.checkIndexPaths: "
619 3514 barteau
                            + e.getMessage());
620 2521 sgarg
                }finally {
621
                    //check in DBonnection
622
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
623
                }
624 3514 barteau
625
626 2521 sgarg
            }
627 3514 barteau
628 5167 daigle
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Path Indexing Completed");
629 2521 sgarg
        }
630 3514 barteau
    }
631
632 2098 jones
    /**
633 4080 daigle
	 * Control servlet response depending on the action parameter specified
634
	 */
635 5167 daigle
	@SuppressWarnings("unchecked")
636 4080 daigle
	private void handleGetOrPost(HttpServletRequest request,
637
			HttpServletResponse response) throws ServletException, IOException {
638
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
639
640 5752 leinfelder
		String requestEncoding = request.getCharacterEncoding();
641 5767 leinfelder
		logMetacat.debug("requestEncoding: " + requestEncoding);
642 5752 leinfelder
643 4080 daigle
		// Update the last update time for this user if they are not new
644
		HttpSession httpSession = request.getSession(false);
645
		if (httpSession != null) {
646 5374 berkley
		    SessionService.getInstance().touchSession(httpSession.getId());
647 4080 daigle
		}
648
649 4154 daigle
		// Each time metacat is called, check to see if metacat has been
650
		// configured. If not then forward to the administration servlet
651 5025 daigle
		if (!ConfigurationUtil.isMetacatConfigured()) {
652 5076 daigle
			try {
653
				RequestUtil.forwardRequest(request, response, "/admin?action=configure", null);
654
				return;
655
			} catch (MetacatUtilException mue) {
656
				logMetacat.error("MetacatServlet.handleGetOrPost - utility error when forwarding to " +
657
						"configuration screen: " + mue.getMessage());
658
				throw new ServletException("MetacatServlet.handleGetOrPost - utility error when forwarding to " +
659
						"configuration screen: " + mue.getMessage());
660
			}
661 4080 daigle
		}
662
663 4203 daigle
		// if we get here, metacat is configured.  If we have not completed the
664 4698 daigle
		// second half of the initialization, do so now.  This allows us to initially
665 4203 daigle
		// configure metacat without a restart.
666 5167 daigle
		if (!_fullyInitialized) {
667 4203 daigle
			initSecondHalf(request.getSession().getServletContext());
668
		}
669
670 4080 daigle
		/*
671
		 * logMetacat.debug("Connection pool size: "
672
		 * +connPool.getSizeOfDBConnectionPool(),10); logMetacat.debug("Free
673
		 * DBConnection number: "
674
		 */
675
		// If all DBConnection in the pool are free and DBConnection pool
676
		// size is greater than initial value, shrink the connection pool
677
		// size to initial value
678
		DBConnectionPool.shrinkDBConnectionPoolSize();
679
680
		// Debug message to print out the method which have a busy DBConnection
681
		try {
682 5167 daigle
			@SuppressWarnings("unused")
683 4080 daigle
			DBConnectionPool pool = DBConnectionPool.getInstance();
684 5167 daigle
//			pool.printMethodNameHavingBusyDBConnection();
685 4080 daigle
		} catch (SQLException e) {
686 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - Error in MetacatServlet.handleGetOrPost: " + e.getMessage());
687 4080 daigle
			e.printStackTrace();
688
		}
689
690
		try {
691
			String ctype = request.getContentType();
692 5211 jones
693 4080 daigle
			if (ctype != null && ctype.startsWith("multipart/form-data")) {
694 5211 jones
				handler.handleMultipartForm(request, response);
695 5030 daigle
				return;
696
			}
697 4080 daigle
698 5030 daigle
			String name = null;
699
			String[] value = null;
700
			String[] docid = new String[3];
701
			Hashtable<String, String[]> params = new Hashtable<String, String[]>();
702 4080 daigle
703 5030 daigle
			// Check if this is a simple read request that doesn't use the
704
			// "action" syntax
705
			// These URLs are of the form:
706
			// http://localhost:8180/knb/metacat/docid/skinname
707
			// e.g., http://localhost:8180/knb/metacat/test.1.1/knb
708
			String pathInfo = request.getPathInfo();
709
			if (pathInfo != null) {
710
				String[] path = pathInfo.split("/");
711
				if (path.length > 1) {
712
					String docidToRead = path[1];
713
					String docs[] = new String[1];
714
					docs[0] = docidToRead;
715 5167 daigle
					logMetacat.debug("MetaCatServlet.handleGetOrPost - READING DOCID FROM PATHINFO: " + docs[0]);
716 5030 daigle
					params.put("docid", docs);
717
					String skin = null;
718
					if (path.length > 2) {
719
						skin = path[2];
720
						String skins[] = new String[1];
721
						skins[0] = skin;
722
						params.put("qformat", skins);
723 4080 daigle
					}
724 5211 jones
					handler.handleReadAction(params, request, response, "public", null, null);
725 5030 daigle
					return;
726 4080 daigle
				}
727 5030 daigle
			}
728 4080 daigle
729 5030 daigle
			Enumeration<String> paramlist =
730
				(Enumeration<String>) request.getParameterNames();
731
			while (paramlist.hasMoreElements()) {
732 4080 daigle
733 5030 daigle
				name = paramlist.nextElement();
734
				value = request.getParameterValues(name);
735 4080 daigle
736 5030 daigle
				// Decode the docid and mouse click information
737
				// THIS IS OBSOLETE -- I THINK -- REMOVE THIS BLOCK
738
				// 4/12/2007d
739
				// MBJ
740
				if (name.endsWith(".y")) {
741
					docid[0] = name.substring(0, name.length() - 2);
742
					params.put("docid", docid);
743
					name = "ypos";
744 4080 daigle
				}
745 5030 daigle
				if (name.endsWith(".x")) {
746
					name = "xpos";
747 4080 daigle
				}
748
749 5030 daigle
				params.put(name, value);
750
			}
751 4080 daigle
752 5030 daigle
			// handle param is emptpy
753
			if (params.isEmpty() || params == null) {
754
				return;
755
			}
756 4080 daigle
757 5030 daigle
			// if the user clicked on the input images, decode which image
758
			// was clicked then set the action.
759
			if (params.get("action") == null) {
760
				PrintWriter out = response.getWriter();
761
				response.setContentType("text/xml");
762
				out.println("<?xml version=\"1.0\"?>");
763
				out.println("<error>");
764
				out.println("Action not specified");
765
				out.println("</error>");
766
				out.close();
767
				return;
768
			}
769 4080 daigle
770 5030 daigle
			String action = (params.get("action"))[0];
771 5167 daigle
			logMetacat.info("MetaCatServlet.handleGetOrPost - Action is: " + action);
772 4080 daigle
773 5030 daigle
			// This block handles session management for the servlet
774
			// by looking up the current session information for all actions
775
			// other than "login" and "logout"
776
			String userName = null;
777
			String password = null;
778
			String[] groupNames = null;
779
			String sessionId = null;
780
			name = null;
781 4080 daigle
782 5030 daigle
			// handle login action
783
			if (action.equals("login")) {
784
				PrintWriter out = response.getWriter();
785 5211 jones
				handler.handleLoginAction(out, params, request, response);
786 5030 daigle
				out.close();
787 4080 daigle
788 5030 daigle
				// handle logout action
789
			} else if (action.equals("logout")) {
790
				PrintWriter out = response.getWriter();
791 5211 jones
				handler.handleLogoutAction(out, params, request, response);
792 5030 daigle
				out.close();
793 4080 daigle
794 5030 daigle
				// handle shrink DBConnection request
795 5041 daigle
			} else if (action.equals("validatesession")) {
796
				PrintWriter out = response.getWriter();
797
				String idToValidate = null;
798
				String idsToValidate[] = params.get("sessionid");
799
				if (idsToValidate != null) {
800
					idToValidate = idsToValidate[0];
801
				}
802 5374 berkley
				SessionService.getInstance().validateSession(out, response, idToValidate);
803 5041 daigle
				out.close();
804
805
				// handle shrink DBConnection request
806 5030 daigle
			} else if (action.equals("shrink")) {
807
				PrintWriter out = response.getWriter();
808
				boolean success = false;
809
				// If all DBConnection in the pool are free and DBConnection
810
				// pool
811
				// size is greater than initial value, shrink the connection
812
				// pool
813
				// size to initial value
814
				success = DBConnectionPool.shrinkConnectionPoolSize();
815
				if (success) {
816
					// if successfully shrink the pool size to initial value
817
					out.println("DBConnection Pool shrunk successfully.");
818
				}// if
819
				else {
820
					out.println("DBConnection pool not shrunk successfully.");
821 4080 daigle
				}
822 5030 daigle
				// close out put
823
				out.close();
824 4080 daigle
825 5030 daigle
				// aware of session expiration on every request
826
			} else {
827
				SessionData sessionData = RequestUtil.getSessionData(request);
828 5159 daigle
829
				if (sessionData != null) {
830
					userName = sessionData.getUserName();
831
					password = sessionData.getPassword();
832
					groupNames = sessionData.getGroupNames();
833
					sessionId = sessionData.getId();
834
				}
835 4080 daigle
836 5167 daigle
				logMetacat.info("MetaCatServlet.handleGetOrPost - The user is : " + userName);
837 5030 daigle
			}
838
			// Now that we know the session is valid, we can delegate the
839
			// request to a particular action handler
840
			if (action.equals("query")) {
841 5752 leinfelder
		        Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
842 5211 jones
				handler.handleQuery(out, params, response, userName, groupNames, sessionId);
843 5030 daigle
				out.close();
844
			} else if (action.equals("squery")) {
845 5752 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
846 5030 daigle
				if (params.containsKey("query")) {
847 5211 jones
					handler.handleSQuery(out, params, response, userName, groupNames, sessionId);
848 5030 daigle
					out.close();
849
				} else {
850 5752 leinfelder
					out.write("Illegal action squery without \"query\" parameter");
851 5030 daigle
					out.close();
852 4221 leinfelder
				}
853 5030 daigle
			} else if (action.trim().equals("spatial_query")) {
854 4221 leinfelder
855 5030 daigle
				logMetacat
856 5167 daigle
						.debug("MetaCatServlet.handleGetOrPost - ******************* SPATIAL QUERY ********************");
857 5752 leinfelder
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
858 5211 jones
				handler.handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
859 5030 daigle
				out.close();
860
861
			} else if (action.trim().equals("dataquery")) {
862
863 5167 daigle
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* DATA QUERY ********************");
864 5211 jones
				handler.handleDataquery(params, response, sessionId);
865 5030 daigle
			} else if (action.trim().equals("editcart")) {
866 5167 daigle
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* EDIT CART ********************");
867 5211 jones
				handler.handleEditCart(params, response, sessionId);
868 5030 daigle
			} else if (action.equals("export")) {
869
870 5211 jones
				handler.handleExportAction(params, response, userName, groupNames, password);
871 5030 daigle
			} else if (action.equals("read")) {
872
				if (params.get("archiveEntryName") != null) {
873
					ArchiveHandler.getInstance().readArchiveEntry(params, request,
874
							response, userName, password, groupNames);
875
				} else {
876 5211 jones
					handler.handleReadAction(params, request, response, userName, password,
877 4295 daigle
							groupNames);
878 5030 daigle
				}
879
			} else if (action.equals("readinlinedata")) {
880 5211 jones
				handler.handleReadInlineDataAction(params, request, response, userName, password,
881 5030 daigle
						groupNames);
882
			} else if (action.equals("insert") || action.equals("update")) {
883
				PrintWriter out = response.getWriter();
884
				if ((userName != null) && !userName.equals("public")) {
885 5319 jones
					handler.handleInsertOrUpdateAction(request.getRemoteAddr(), response, out, params, userName,
886 5030 daigle
							groupNames);
887
				} else {
888 4080 daigle
					response.setContentType("text/xml");
889
					out.println("<?xml version=\"1.0\"?>");
890 5030 daigle
					out.println("<error>");
891
					out.println("Permission denied for user " + userName + " " + action);
892
					out.println("</error>");
893
				}
894
				out.close();
895
			} else if (action.equals("delete")) {
896
				PrintWriter out = response.getWriter();
897
				if ((userName != null) && !userName.equals("public")) {
898 5211 jones
					handler.handleDeleteAction(out, params, request, response, userName,
899 4295 daigle
							groupNames);
900 4950 daigle
				} else {
901 5030 daigle
					response.setContentType("text/xml");
902 4080 daigle
					out.println("<?xml version=\"1.0\"?>");
903
					out.println("<error>");
904 5030 daigle
					out.println("Permission denied for " + action);
905 4080 daigle
					out.println("</error>");
906
				}
907 5030 daigle
				out.close();
908
			} else if (action.equals("validate")) {
909
				PrintWriter out = response.getWriter();
910 5211 jones
				handler.handleValidateAction(out, params);
911 5030 daigle
				out.close();
912
			} else if (action.equals("setaccess")) {
913
				PrintWriter out = response.getWriter();
914 5211 jones
				handler.handleSetAccessAction(out, params, userName, request, response);
915 5030 daigle
				out.close();
916
			} else if (action.equals("getaccesscontrol")) {
917
				PrintWriter out = response.getWriter();
918 5211 jones
				handler.handleGetAccessControlAction(out, params, response, userName, groupNames);
919 5030 daigle
				out.close();
920 5071 daigle
			} else if (action.equals("isauthorized")) {
921
				PrintWriter out = response.getWriter();
922
				DocumentUtil.isAuthorized(out, params, request, response);
923
				out.close();
924 5030 daigle
			} else if (action.equals("getprincipals")) {
925
				PrintWriter out = response.getWriter();
926 5211 jones
				handler.handleGetPrincipalsAction(out, userName, password);
927 5030 daigle
				out.close();
928
			} else if (action.equals("getdoctypes")) {
929
				PrintWriter out = response.getWriter();
930 5211 jones
				handler.handleGetDoctypesAction(out, params, response);
931 5030 daigle
				out.close();
932
			} else if (action.equals("getdtdschema")) {
933
				PrintWriter out = response.getWriter();
934 5211 jones
				handler.handleGetDTDSchemaAction(out, params, response);
935 5030 daigle
				out.close();
936
			} else if (action.equals("getlastdocid")) {
937
				PrintWriter out = response.getWriter();
938 5211 jones
				handler.handleGetMaxDocidAction(out, params, response);
939 5030 daigle
				out.close();
940
			} else if (action.equals("getalldocids")) {
941
				PrintWriter out = response.getWriter();
942 5211 jones
				handler.handleGetAllDocidsAction(out, params, response);
943 5030 daigle
				out.close();
944
			} else if (action.equals("isregistered")) {
945
				PrintWriter out = response.getWriter();
946 5211 jones
				handler.handleIdIsRegisteredAction(out, params, response);
947 5030 daigle
				out.close();
948
			} else if (action.equals("getrevisionanddoctype")) {
949
				PrintWriter out = response.getWriter();
950 5211 jones
				handler.handleGetRevisionAndDocTypeAction(out, params);
951 5030 daigle
				out.close();
952
			} else if (action.equals("getversion")) {
953
				response.setContentType("text/xml");
954
				PrintWriter out = response.getWriter();
955
				out.println(MetacatVersion.getVersionAsXml());
956
				out.close();
957
			} else if (action.equals("getlog")) {
958 5211 jones
				handler.handleGetLogAction(params, request, response, userName, groupNames);
959 5030 daigle
			} else if (action.equals("getloggedinuserinfo")) {
960
				PrintWriter out = response.getWriter();
961
				response.setContentType("text/xml");
962
				out.println("<?xml version=\"1.0\"?>");
963
				out.println("\n<user>\n");
964
				out.println("\n<username>\n");
965
				out.println(userName);
966
				out.println("\n</username>\n");
967
				if (name != null) {
968
					out.println("\n<name>\n");
969
					out.println(name);
970
					out.println("\n</name>\n");
971
				}
972
				if (AuthUtil.isAdministrator(userName, groupNames)) {
973
					out.println("<isAdministrator></isAdministrator>\n");
974
				}
975
				if (AuthUtil.isModerator(userName, groupNames)) {
976
					out.println("<isModerator></isModerator>\n");
977
				}
978
				out.println("\n</user>\n");
979
				out.close();
980
			} else if (action.equals("buildindex")) {
981 5211 jones
				handler.handleBuildIndexAction(params, request, response, userName, groupNames);
982 5030 daigle
			} else if (action.equals("login") || action.equals("logout")) {
983
				/*
984
				 * } else if (action.equals("protocoltest")) { String testURL =
985
				 * "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9"; try { testURL =
986
				 * ((String[]) params.get("url"))[0]; } catch (Throwable t) { }
987
				 * String phandler = System
988
				 * .getProperty("java.protocol.handler.pkgs");
989
				 * response.setContentType("text/html"); PrintWriter out =
990
				 * response.getWriter(); out.println("<body
991
				 * bgcolor=\"white\">"); out.println("<p>Handler property:
992
				 * <code>" + phandler + "</code></p>"); out.println("<p>Starting
993
				 * test for:<br>"); out.println(" " + testURL + "</p>"); try {
994
				 * URL u = new URL(testURL); out.println("<pre>");
995
				 * out.println("Protocol: " + u.getProtocol()); out.println("
996
				 * Host: " + u.getHost()); out.println(" Port: " + u.getPort());
997
				 * out.println(" Path: " + u.getPath()); out.println(" Ref: " +
998
				 * u.getRef()); String pquery = u.getQuery(); out.println("
999
				 * Query: " + pquery); out.println(" Params: "); if (pquery !=
1000
				 * null) { Hashtable qparams =
1001
				 * MetacatUtil.parseQuery(u.getQuery()); for (Enumeration en =
1002
				 * qparams.keys(); en .hasMoreElements();) { String pname =
1003
				 * (String) en.nextElement(); String pvalue = (String)
1004
				 * qparams.get(pname); out.println(" " + pname + ": " + pvalue); } }
1005
				 * out.println("</pre>"); out.println("</body>");
1006
				 * out.close(); } catch (MalformedURLException mue) {
1007
				 * System.out.println( "bad url from
1008
				 * MetacatServlet.handleGetOrPost");
1009
				 * out.println(mue.getMessage()); mue.printStackTrace(out);
1010
				 * out.close(); }
1011
				 */
1012
			} else if (action.equals("refreshServices")) {
1013
				// TODO MCD this interface is for testing. It should go through
1014 5041 daigle
				// a ServiceService class and only work for an admin user. Move
1015
				// to the MetacatAdminServlet
1016 5030 daigle
				ServiceService.refreshService("XMLSchemaService");
1017
				return;
1018
			} else if (action.equals("scheduleWorkflow")) {
1019
				try {
1020
					WorkflowSchedulerClient.getInstance().scheduleJob(request, response,
1021
							params, userName, groupNames);
1022
					return;
1023
				} catch (BaseException be) {
1024
					ResponseUtil.sendErrorXML(response,
1025
							ResponseUtil.SCHEDULE_WORKFLOW_ERROR, be);
1026
					return;
1027
				}
1028
			} else if (action.equals("unscheduleWorkflow")) {
1029
				try {
1030
					WorkflowSchedulerClient.getInstance().unScheduleJob(request,
1031
							response, params, userName, groupNames);
1032
					return;
1033
				} catch (BaseException be) {
1034
					ResponseUtil.sendErrorXML(response,
1035
							ResponseUtil.UNSCHEDULE_WORKFLOW_ERROR, be);
1036
					return;
1037
				}
1038
			} else if (action.equals("rescheduleWorkflow")) {
1039
				try {
1040
					WorkflowSchedulerClient.getInstance().reScheduleJob(request,
1041
							response, params, userName, groupNames);
1042
					return;
1043
				} catch (BaseException be) {
1044
					ResponseUtil.sendErrorXML(response,
1045
							ResponseUtil.RESCHEDULE_WORKFLOW_ERROR, be);
1046
					return;
1047
				}
1048
			} else if (action.equals("getScheduledWorkflow")) {
1049
				try {
1050
					WorkflowSchedulerClient.getInstance().getJobs(request, response,
1051
							params, userName, groupNames);
1052
					return;
1053
				} catch (BaseException be) {
1054
					ResponseUtil.sendErrorXML(response,
1055
							ResponseUtil.GET_SCHEDULED_WORKFLOW_ERROR, be);
1056
					return;
1057
				}
1058
			} else if (action.equals("deleteScheduledWorkflow")) {
1059
				try {
1060
					WorkflowSchedulerClient.getInstance().deleteJob(request, response,
1061
							params, userName, groupNames);
1062
					return;
1063
				} catch (BaseException be) {
1064
					ResponseUtil.sendErrorXML(response,
1065
							ResponseUtil.DELETE_SCHEDULED_WORKFLOW_ERROR, be);
1066
					return;
1067
				}
1068 4080 daigle
1069 5030 daigle
			} else {
1070 5518 leinfelder
				//try the plugin handler if it has an entry for handling this action
1071
				MetacatHandlerPlugin handlerPlugin = MetacatHandlerPluginManager.getInstance().getHandler(action);
1072
				if (handlerPlugin != null) {
1073
					handlerPlugin.handleAction(action, params, request, response, userName, groupNames, sessionId);
1074
				}
1075
				else {
1076
					PrintWriter out = response.getWriter();
1077
					out.println("<?xml version=\"1.0\"?>");
1078
					out.println("<error>");
1079
					out.println("Error: action: " + action + " not registered.  Please report this error.");
1080
					out.println("</error>");
1081
					out.close();
1082
				}
1083 5030 daigle
			}
1084 4080 daigle
1085 5030 daigle
			// Schedule the sitemap generator to run periodically
1086 5211 jones
			handler.scheduleSitemapGeneration(request);
1087 5030 daigle
1088
1089 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
1090
			String errorString = "Critical property not found: " + pnfe.getMessage();
1091 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1092 4080 daigle
			throw new ServletException(errorString);
1093 4854 daigle
		} catch (MetacatUtilException ue) {
1094 4080 daigle
			String errorString = "Utility error: " + ue.getMessage();
1095 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1096 4080 daigle
			throw new ServletException(errorString);
1097 4698 daigle
		} catch (ServiceException ue) {
1098
			String errorString = "Service error: " + ue.getMessage();
1099 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1100 4698 daigle
			throw new ServletException(errorString);
1101 4950 daigle
		} catch (HandlerException he) {
1102
			String errorString = "Handler error: " + he.getMessage();
1103 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1104 4950 daigle
			throw new ServletException(errorString);
1105
		} catch (ErrorSendingErrorException esee) {
1106
			String errorString = "Error sending error message: " + esee.getMessage();
1107 5167 daigle
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1108 4950 daigle
			throw new ServletException(errorString);
1109
		} catch (ErrorHandledException ehe) {
1110
			// Nothing to do here.  We assume if we get here, the error has been
1111
			// written to ouput.  Continue on and let it display.
1112 4959 daigle
		}
1113 4080 daigle
	}
1114 3514 barteau
1115 2912 harris
    /**
1116 4203 daigle
     * Reports whether the MetaCatServlet has been fully initialized
1117
     *
1118
     * @return true if fully intialized, false otherwise
1119
     */
1120
    public static boolean isFullyInitialized() {
1121 5167 daigle
    	return _fullyInitialized;
1122 4203 daigle
    }
1123 46 jones
}