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