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