Project

General

Profile

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