Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements a metadata catalog as a java Servlet
4
 *  Copyright: 2006 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones, Dan Higgins, Jivka Bojilova, Chad Berkley, Matthew Perry
7
 *
8
 *   '$Author: jones $'
9
 *     '$Date: 2010-04-19 16:51:13 -0700 (Mon, 19 Apr 2010) $'
10
 * '$Revision: 5319 $'
11
 *
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
 */
26

    
27
package edu.ucsb.nceas.metacat;
28

    
29
import java.io.IOException;
30
import java.io.PrintWriter;
31
import java.sql.PreparedStatement;
32
import java.sql.ResultSet;
33
import java.sql.SQLException;
34
import java.util.Enumeration;
35
import java.util.Hashtable;
36
import java.util.Timer;
37
import java.util.Vector;
38

    
39
import javax.servlet.ServletConfig;
40
import javax.servlet.ServletContext;
41
import javax.servlet.ServletException;
42
import javax.servlet.ServletOutputStream;
43
import javax.servlet.http.HttpServlet;
44
import javax.servlet.http.HttpServletRequest;
45
import javax.servlet.http.HttpServletResponse;
46
import javax.servlet.http.HttpSession;
47

    
48
import org.apache.log4j.Logger;
49
import org.apache.log4j.PropertyConfigurator;
50

    
51
import edu.ucsb.nceas.metacat.database.DBConnection;
52
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
53
import edu.ucsb.nceas.metacat.database.DatabaseService;
54
import edu.ucsb.nceas.metacat.properties.PropertyService;
55
import edu.ucsb.nceas.metacat.properties.SkinPropertyService;
56
import edu.ucsb.nceas.metacat.replication.ReplicationService;
57
import edu.ucsb.nceas.metacat.service.ServiceService;
58
import edu.ucsb.nceas.metacat.service.SessionService;
59
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
60
import edu.ucsb.nceas.metacat.shared.BaseException;
61
import edu.ucsb.nceas.metacat.shared.HandlerException;
62
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
63
import edu.ucsb.nceas.metacat.shared.ServiceException;
64
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
65
import edu.ucsb.nceas.metacat.util.AuthUtil;
66
import edu.ucsb.nceas.metacat.util.ConfigurationUtil;
67
import edu.ucsb.nceas.metacat.util.DocumentUtil;
68
import edu.ucsb.nceas.metacat.util.ErrorSendingErrorException;
69
import edu.ucsb.nceas.metacat.util.RequestUtil;
70
import edu.ucsb.nceas.metacat.util.ResponseUtil;
71
import edu.ucsb.nceas.metacat.util.SessionData;
72
import edu.ucsb.nceas.metacat.util.SystemUtil;
73
import edu.ucsb.nceas.metacat.workflow.WorkflowSchedulerClient;
74
import edu.ucsb.nceas.utilities.FileUtil;
75
import edu.ucsb.nceas.utilities.GeneralPropertyException;
76
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
77
import edu.ucsb.nceas.utilities.UtilException;
78

    
79
/**
80
 * A metadata catalog server implemented as a Java Servlet
81
 *
82
 * Valid actions are:
83
 * 
84
 * action=login
85
 *     username
86
 *     password
87
 *     qformat
88
 * action=logout
89
 *     qformat
90
 * action=query -- query the values of all elements and attributes and return a result set of nodes
91
 *     meta_file_id --
92
 *     returndoctype --
93
 *     filterdoctype --
94
 *     returnfield --
95
 *     owner --
96
 *     site --
97
 *     operator --
98
 *     casesensitive --
99
 *     searchmode --
100
 *     anyfield --
101
 * action=spatial_query -- run a spatial query.  these queries may include any of the
102
 *                         queries supported by the WFS / WMS standards
103
 *     xmax --
104
 *     ymax --
105
 *     xmin --
106
 *     ymin --
107
 *     skin --
108
 *     pagesize --
109
 *     pagestart --
110
 * action=squery -- structured query (see pathquery.dtd)
111
 *     query --
112
 *     pagesize --
113
 *     pagestart --
114
 * action=export -- export a zip format for data packadge
115
 *     docid -- 
116
 * action=read -- read any metadata/data file from Metacat and from Internet
117
 *     archiveEntryName --
118
 *     docid --
119
 *     qformat --
120
 *     metadatadocid --
121
 * action=readinlinedata -- read inline data only
122
 *     inlinedataid
123
 * action=insert -- insert an XML document into the database store
124
 *     qformat -- 
125
 *     docid --
126
 *     doctext --
127
 *     dtdtext --
128
 * action=insertmultipart -- insert an xml document into the database using multipart encoding
129
 *     qformat -- 
130
 *     docid --
131
 * action=update -- update an XML document that is in the database store
132
 *     qformat -- 
133
 *     docid --
134
 *     doctext --
135
 *     dtdtext --
136
 * action=delete -- delete an XML document from the database store
137
 *     docid --
138
 * action=validate -- validate the xml contained in valtext
139
 *     valtext --
140
 *     docid --
141
 * action=setaccess -- change access permissions for a user on a document.
142
 *     docid --
143
 *     principal --
144
 *     permission --
145
 *     permType --
146
 *     permOrder --
147
 * action=getaccesscontrol -- retrieve acl info for Metacat document
148
 *     docid -- 
149
 * action=getprincipals -- retrieve a list of principals in XML
150
 * action=getalldocids -- retrieves a list of all docids registered with the system
151
 *     scope --
152
 * action=getlastdocid --
153
 *     scope --
154
 *     username --
155
 * action=isregistered -- checks to see if the provided docid is registered
156
 *     docid --
157
 * action=getrevisionanddoctype -- get a document's revision and doctype from database 
158
 *     docid --
159
 * action=getversion -- 
160
 * action=getdoctypes -- retrieve all doctypes (publicID) 
161
 * action=getdtdschema -- retrieve a DTD or Schema file
162
 *     doctype --
163
 * action=getlog -- get a report of events that have occurred in the system
164
 *     ipAddress --  filter on one or more IP addresses>
165
 *     principal -- filter on one or more principals (LDAP DN syntax)
166
 *     docid -- filter on one or more document identifiers (with revision)
167
 *     event -- filter on event type (e.g., read, insert, update, delete)
168
 *     start -- filter out events before the start date-time
169
 *     end -- filter out events before the end date-time
170
 * action=getloggedinuserinfo -- get user info for the currently logged in user
171
 *     ipAddress --  filter on one or more IP addresses>
172
 *     principal -- filter on one or more principals (LDAP DN syntax)
173
 *     docid -- filter on one or more document identifiers (with revision)
174
 *     event -- filter on event type (e.g., read, insert, update, delete)
175
 *     start -- filter out events before the start date-time
176
 *     end -- filter out events before the end date-time
177
 * action=shrink -- Shrink the database connection pool size if it has grown and 
178
 *                  extra connections are no longer being used.
179
 * action=buildindex --
180
 *     docid --
181
 * action=refreshServices --
182
 * action=scheduleWorkflow -- Schedule a workflow to be run.  Scheduling a workflow 
183
 *                            registers it with the scheduling engine and creates a row
184
 *                            in the scheduled_job table.  Note that this may be 
185
 *                            extracted into a separate servlet.
186
 *     delay -- The amount of time from now before the workflow should be run.  The 
187
 *              delay can be expressed in number of seconds, minutes, hours and days, 
188
 *              for instance 30s, 2h, etc.
189
 *     starttime -- The time that the workflow should first run.  If both are provided
190
 *                  this takes precedence over delay.  The time should be expressed as: 
191
 *                  MM/dd/yyyy HH:mm:ss with the timezone assumed to be that of the OS.
192
 *     endtime -- The time when the workflow should end. The time should be expressed as: 
193
 *                  MM/dd/yyyy HH:mm:ss with the timezone assumed to be that of the OS.
194
 *     intervalvalue -- The numeric value of the interval between runs
195
 *     intervalunit -- The unit of the interval between runs.  Can be s, m, h, d for 
196
 *                     seconds, minutes, hours and days respectively
197
 *     workflowid -- The lsid of the workflow that we want to schedule.  This workflow
198
 *                   must already exist in the database.
199
 *     karid -- The karid for the workflow that we want to schedule.
200
 *     workflowname -- The name of the workflow.
201
 *     forwardto -- If provided, forward to this page when processing is done.
202
 *     qformat -- If provided, render results using the stylesheets associated with
203
 *                this skin.  Default is xml.
204
 * action=unscheduleWorkflow -- Unschedule a workflow.  Unscheduling a workflow 
205
 *                            removes it from the scheduling engine and changes the 
206
 *                            status in the scheduled_job table to " unscheduled.  Note 
207
 *                            that this may be extracted into a separate servlet.
208
 *     workflowjobname -- The job ID for the workflow run that we want to unschedule.  This
209
 *                      is held in the database as scheduled_job.name
210
 *     forwardto -- If provided, forward to this page when processing is done.
211
 *     qformat -- If provided, render results using the stylesheets associated with
212
 *                this skin.  Default is xml.
213
 * action=rescheduleWorkflow -- Unschedule a workflow.  Rescheduling a workflow 
214
 *                            registers it with the scheduling engine and changes the 
215
 *                            status in the scheduled_job table to " scheduled.  Note 
216
 *                            that this may be extracted into a separate servlet.
217
 *     workflowjobname -- The job ID for the workflow run that we want to reschedule.  This
218
 *                      is held in the database as scheduled_job.name
219
 *     forwardto -- If provided, forward to this page when processing is done.
220
 *     qformat -- If provided, render results using the stylesheets associated with
221
 *                this skin.  Default is xml.
222
 * action=deleteScheduledWorkflow -- Delete a workflow.  Deleting a workflow 
223
 *                            removes it from the scheduling engine and changes the 
224
 *                            status in the scheduled_job table to " deleted.  Note 
225
 *                            that this may be extracted into a separate servlet.
226
 *     workflowjobname -- The job ID for the workflow run that we want to delete.  This
227
 *                      is held in the database as scheduled_job.name
228
 *     forwardto -- If provided, forward to this page when processing is done.
229
 *     qformat -- If provided, render results using the stylesheets associated with
230
 *                this skin.  Default is xml.
231
 *     
232
 *     
233
 * Here are some of the common parameters for actions
234
 *     doctype -- document type list returned by the query (publicID) 
235
 *     qformat=xml -- display resultset from query in XML 
236
 *     qformat=html -- display resultset from query in HTML 
237
 *     qformat=zip -- zip resultset from query
238
 *     docid=34 -- display the document with the document ID number 34 
239
 *     doctext -- XML text of the document to load into the database 
240
 *     acltext -- XML access text for a document to load into the database 
241
 *     dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog 
242
 *     query -- actual query text (to go with 'action=query' or 'action=squery')
243
 *     valtext -- XML text to be validated 
244
 *     scope --can limit the query by the scope of the id
245
 *     docid --the docid to check
246
 *     datadoc -- data document name (id)
247
 */
248
public class MetaCatServlet extends HttpServlet {
249

    
250
	private static final long serialVersionUID = 1L;
251
	private Timer timer = null;
252
    private static boolean _firstHalfInitialized = false;
253
    private static boolean _fullyInitialized = false;
254
    private MetacatHandler handler = null;
255
    
256
    // Constants -- these should be final in a servlet
257
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
258
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
259
    public static final String EML2KEYWORD = ":eml";
260
    private static final String FALSE = "false";
261
    private static final String TRUE  = "true";
262
    private static String LOG_CONFIG_NAME = null;
263
    public static final String APPLICATION_NAME = "metacat";
264
    
265
    /**
266
     * Initialize the servlet by creating appropriate database connections
267
     */
268
    public void init(ServletConfig config) throws ServletException {
269
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
270
    	try {
271
    		if(_firstHalfInitialized) {
272
    			return;
273
    		}
274
    		
275
            super.init(config);
276
            
277
            ServletContext context = config.getServletContext();
278
            context.setAttribute("APPLICATION_NAME", APPLICATION_NAME);
279
            
280
            ServiceService serviceService = ServiceService.getInstance(context);
281
            logMetacat.debug("MetaCatServlet.init - ServiceService singleton created " + serviceService);
282
            
283
            // Initialize the properties file
284
            String dirPath = ServiceService.getRealConfigDir();
285
            
286
            LOG_CONFIG_NAME = dirPath + "/log4j.properties";
287
            PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
288
            
289
            // Register preliminary services
290
            ServiceService.registerService("PropertyService", PropertyService.getInstance(context));         
291
            ServiceService.registerService("SkinPropertyService", SkinPropertyService.getInstance());
292
            ServiceService.registerService("SessionService", SessionService.getInstance()); 
293
            
294
    		// Check to see if the user has requested to bypass configuration 
295
            // (dev option) and check see if metacat has been configured.
296
    		// If both are false then stop the initialization
297
            if (!ConfigurationUtil.bypassConfiguration() && !ConfigurationUtil.isMetacatConfigured()) {
298
            	return;
299
            }  
300
            
301
            _firstHalfInitialized = true;
302
            
303
            initSecondHalf(context);
304
            
305
    	} catch (ServiceException se) {
306
        	String errorMessage = 
307
        		"Service problem while intializing MetaCat Servlet: " + se.getMessage();
308
            logMetacat.error("MetaCatServlet.init - " + errorMessage);
309
            throw new ServletException(errorMessage);
310
        } catch (MetacatUtilException mue) {
311
        	String errorMessage = "Metacat utility problem while intializing MetaCat Servlet: " 
312
        		+ mue.getMessage();
313
            logMetacat.error("MetaCatServlet.init - " + errorMessage);
314
            throw new ServletException(errorMessage);
315
        } 
316
    }
317

    
318
            
319
	/**
320
	 * Initialize the remainder of the servlet. This is the part that can only
321
	 * be initialized after metacat properties have been configured
322
	 * 
323
	 * @param context
324
	 *            the servlet context of MetaCatServlet
325
	 */
326
	public void initSecondHalf(ServletContext context) throws ServletException {
327
		
328
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
329

    
330
		try {			
331
			ServiceService.registerService("DatabaseService", DatabaseService.getInstance());
332
			
333
			// initialize DBConnection pool
334
			DBConnectionPool connPool = DBConnectionPool.getInstance();
335
			logMetacat.debug("MetaCatServlet.initSecondHalf - DBConnection pool initialized: " + connPool.toString());
336
			
337
			ServiceService.registerService("XMLSchemaService", XMLSchemaService.getInstance());
338

    
339
			// check if eml201 document were corrected or not. if not, correct eml201 documents.
340
			// Before Metacat 1.8.1, metacat uses tag RELEASE_EML_2_0_1_UPDATE_6 as eml
341
			// schema, which accidentily points to wrong version of eml-resource.xsd.
342
			String correctedEML201Doc = PropertyService.getProperty("document.eml201DocumentCorrected");
343
			if (correctedEML201Doc != null && correctedEML201Doc.equals(FALSE)) {
344
				logMetacat.info("MetaCatServlet.initSecondHalf - Start to correct eml201 documents");
345
				EML201DocumentCorrector correct = new EML201DocumentCorrector();
346
				boolean success = correct.run();
347
				if (success) {
348
					PropertyService.setProperty("document.eml201DocumentCorrected", TRUE);
349
				}
350
				logMetacat.info("MetaCatServlet.initSecondHalf - Finish to correct eml201 documents");
351
			}
352

    
353
			// Index the paths specified in the metacat.properties
354
			checkIndexPaths();
355

    
356
			// initiate the indexing Queue
357
			IndexingQueue.getInstance();
358

    
359
			// start the IndexingThread if indexingTimerTaskTime more than 0.
360
			// It will index all the documents not yet indexed in the database
361
			int indexingTimerTaskTime = Integer.parseInt(PropertyService
362
					.getProperty("database.indexingTimerTaskTime"));
363
			int delayTime = Integer.parseInt(PropertyService
364
					.getProperty("database.indexingInitialDelay"));
365

    
366
			if (indexingTimerTaskTime > 0) {
367
				timer = new Timer();
368
				timer.schedule(new IndexingTimerTask(), delayTime, indexingTimerTaskTime);
369
			}
370
			
371
			/*
372
			 * If spatial option is turned on and set to regenerate the spatial
373
			 * cache on restart, trigger the harvester regeneratation method
374
			 */
375
			if (PropertyService.getProperty("spatial.runSpatialOption").equals("true") && 
376
					PropertyService.getProperty("spatial.regenerateCacheOnRestart").equals("true")) {
377

    
378
				// Begin timer
379
				long before = System.currentTimeMillis();
380

    
381
				// if either the point or polygon shape files do not exist, then regenerate the entire spatial cache
382
				// this may be expensive with many documents		
383
				SpatialHarvester sh = new SpatialHarvester();
384
				sh.regenerate();
385
				sh.destroy();
386

    
387
				// After running the first time, we want to to set
388
				// regenerateCacheOnRestart to false
389
				// so that it does not regenerate the cache every time tomcat is
390
				// restarted
391
				PropertyService.setProperty("spatial.regenerateCacheOnRestart", "false");
392

    
393
				// End timer
394
				long after = System.currentTimeMillis();
395
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial Harvester Time  " 
396
						+ (after - before) + "ms");
397

    
398
			} else {
399
				logMetacat.info("MetaCatServlet.initSecondHalf - Spatial cache is not set to regenerate on restart");
400
			}
401
		
402
			// Set up the replication log file by setting the "replication.logfile.name" 
403
			// system property and reconfiguring the log4j property configurator.
404
			String replicationLogPath = PropertyService.getProperty("replication.logdir") 
405
				+ FileUtil.getFS() + ReplicationService.REPLICATION_LOG_FILE_NAME;				
406
			
407
			if (FileUtil.getFileStatus(replicationLogPath) == FileUtil.DOES_NOT_EXIST) {
408
				FileUtil.createFile(replicationLogPath);
409
			}
410

    
411
			if (FileUtil.getFileStatus(replicationLogPath) < FileUtil.EXISTS_READ_WRITABLE) {
412
				logMetacat.error("MetaCatServlet.initSecondHalf - Replication log file: " + replicationLogPath 
413
						+ " does not exist read/writable.");
414
			}
415
			
416
			System.setProperty("replication.logfile.name", replicationLogPath);			
417
			PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
418
			
419
			SessionService.unRegisterAllSessions();
420
			
421
	         //Initialize Metacat Handler
422
            handler = new MetacatHandler(getServletContext(), timer);
423

    
424
			handler.set_sitemapScheduled(false);
425

    
426
			_fullyInitialized = true;
427
			
428
			logMetacat.warn("MetaCatServlet.initSecondHalf - Metacat (" + MetacatVersion.getVersionID()
429
					+ ") initialized.");
430
			
431
		} catch (SQLException e) {
432
			String errorMessage = "SQL problem while intializing MetaCat Servlet: "
433
					+ e.getMessage();
434
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
435
			throw new ServletException(errorMessage);
436
		} catch (IOException ie) {
437
			String errorMessage = "IO problem while intializing MetaCat Servlet: "
438
					+ ie.getMessage();
439
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
440
			throw new ServletException(errorMessage);
441
		} catch (GeneralPropertyException gpe) {
442
			String errorMessage = "Could not retrieve property while intializing MetaCat Servlet: "
443
					+ gpe.getMessage();
444
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
445
			throw new ServletException(errorMessage);
446
		} catch (ServiceException se) {
447
			String errorMessage = "Service problem while intializing MetaCat Servlet: "
448
				+ se.getMessage();
449
			logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
450
			throw new ServletException(errorMessage);
451
		} catch (UtilException ue) {
452
        	String errorMessage = "Utility problem while intializing MetaCat Servlet: " 
453
        		+ ue.getMessage();
454
            logMetacat.error("MetaCatServlet.initSecondHalf - " + errorMessage);
455
            throw new ServletException(errorMessage);
456
        } 
457
	}
458
    
459
    /**
460
	 * Close all db connections from the pool
461
	 */
462
    public void destroy() {
463
    	Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
464
    	
465
    	ServiceService.stopAllServices();
466
    	
467
        // Close all db connection
468
        logMetacat.warn("MetaCatServlet.destroy - Destroying MetacatServlet");
469
        timer.cancel();
470
        IndexingQueue.getInstance().setMetacatRunning(false);
471
        DBConnectionPool.release();
472
    }
473
    
474
    /** Handle "GET" method requests from HTTP clients */
475
    public void doGet(HttpServletRequest request, HttpServletResponse response)
476
    throws ServletException, IOException {
477
        
478
        // Process the data and send back the response
479
        handleGetOrPost(request, response);
480
    }
481
    
482
    /** Handle "POST" method requests from HTTP clients */
483
    public void doPost(HttpServletRequest request, HttpServletResponse response)
484
    throws ServletException, IOException {
485
        
486
        // Process the data and send back the response
487
        handleGetOrPost(request, response);
488
    }
489
    
490
    /**
491
	 * Index the paths specified in the metacat.properties
492
	 */
493
    private void checkIndexPaths() {
494
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
495

    
496
        Vector<String> pathsForIndexing = null;
497
        try {  
498
        	pathsForIndexing = SystemUtil.getPathsForIndexing();
499
        }
500
        catch (MetacatUtilException ue) {
501
        	pathsForIndexing = null;
502
            logMetacat.error("MetaCatServlet.checkIndexPaths - not find index paths.  Setting " 
503
            		+ "pathsForIndexing to null: " + ue.getMessage());
504
        }
505
        
506
        if (pathsForIndexing != null && !pathsForIndexing.isEmpty()) {
507
            
508
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Indexing paths specified in metacat.properties....");
509
            
510
            DBConnection conn = null;
511
            int serialNumber = -1;
512
            PreparedStatement pstmt = null;
513
            PreparedStatement pstmt1 = null;
514
            ResultSet rs = null;
515
            
516
            for (String pathIndex : pathsForIndexing) {
517
                logMetacat.debug("MetaCatServlet.checkIndexPaths - Checking if '" + pathIndex  + "' is indexed.... ");
518
                
519
                try {
520
                    //check out DBConnection
521
                    conn = DBConnectionPool.
522
                            getDBConnection("MetaCatServlet.checkIndexPaths");
523
                    serialNumber = conn.getCheckOutSerialNumber();
524
                    
525
                    pstmt = conn.prepareStatement(
526
                            "SELECT * FROM xml_path_index " + "WHERE path = ?");
527
                    pstmt.setString(1, pathIndex);
528
                    
529
                    pstmt.execute();
530
                    rs = pstmt.getResultSet();
531
                    
532
                    if (!rs.next()) {
533
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - not indexed yet.");
534
                        rs.close();
535
                        pstmt.close();
536
                        conn.increaseUsageCount(1);
537
                        
538
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Inserting following path in xml_path_index: "
539
                                + pathIndex);
540
                        if(pathIndex.indexOf("@")<0){
541
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
542
                                    + "n.nodedata, n.nodedatanumerical, n.parentnodeid"
543
                                    + " FROM xml_nodes n, xml_index i WHERE"
544
                                    + " i.path = ? and n.parentnodeid=i.nodeid and"
545
                                    + " n.nodetype LIKE 'TEXT' order by n.parentnodeid");
546
                        } else {
547
                            pstmt = conn.prepareStatement("SELECT DISTINCT n.docid, "
548
                                    + "n.nodedata, n.nodedatanumerical, n.parentnodeid"
549
                                    + " FROM xml_nodes n, xml_index i WHERE"
550
                                    + " i.path = ? and n.nodeid=i.nodeid and"
551
                                    + " n.nodetype LIKE 'ATTRIBUTE' order by n.parentnodeid");
552
                        }
553
                        pstmt.setString(1, pathIndex);
554
                        pstmt.execute();
555
                        rs = pstmt.getResultSet();
556
                        
557
                        int count = 0;
558
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - Executed the select statement for: "
559
                                + pathIndex);
560
                        
561
                        try {
562
                            while (rs.next()) {
563
                                
564
                                String docid = rs.getString(1);
565
                                String nodedata = rs.getString(2);
566
                                float nodedatanumerical = rs.getFloat(3);
567
                                int parentnodeid = rs.getInt(4);
568
                                
569
                                if (!nodedata.trim().equals("")) {
570
                                    pstmt1 = conn.prepareStatement(
571
                                            "INSERT INTO xml_path_index"
572
                                            + " (docid, path, nodedata, "
573
                                            + "nodedatanumerical, parentnodeid)"
574
                                            + " VALUES (?, ?, ?, ?, ?)");
575
                                    
576
                                    pstmt1.setString(1, docid);
577
                                    pstmt1.setString(2, pathIndex);
578
                                    pstmt1.setString(3, nodedata);
579
                                    pstmt1.setFloat(4, nodedatanumerical);
580
                                    pstmt1.setInt(5, parentnodeid);
581
                                    
582
                                    pstmt1.execute();
583
                                    pstmt1.close();
584
                                    
585
                                    count++;
586
                                    
587
                                }
588
                            }
589
                        } catch (Exception e) {
590
                            logMetacat.error("MetaCatServlet.checkIndexPaths - Exception:" + e.getMessage());
591
                            e.printStackTrace();
592
                        }
593
                        
594
                        rs.close();
595
                        pstmt.close();
596
                        conn.increaseUsageCount(1);
597
                        
598
                        logMetacat.info("MetaCatServlet.checkIndexPaths - Indexed " + count + " records from xml_nodes for '"
599
                                + pathIndex + "'");
600
                        
601
                    } else {
602
                        logMetacat.debug("MetaCatServlet.checkIndexPaths - already indexed.");
603
                    }
604
                    
605
                    rs.close();
606
                    pstmt.close();
607
                    conn.increaseUsageCount(1);
608
                    
609
                } catch (Exception e) {
610
                    logMetacat.error("MetaCatServlet.checkIndexPaths - Error in MetaCatServlet.checkIndexPaths: "
611
                            + e.getMessage());
612
                }finally {
613
                    //check in DBonnection
614
                    DBConnectionPool.returnDBConnection(conn, serialNumber);
615
                }
616
                
617
                
618
            }
619
            
620
            logMetacat.debug("MetaCatServlet.checkIndexPaths - Path Indexing Completed");
621
        }
622
    }
623
    
624
    /**
625
	 * Control servlet response depending on the action parameter specified
626
	 */
627
	@SuppressWarnings("unchecked")
628
	private void handleGetOrPost(HttpServletRequest request,
629
			HttpServletResponse response) throws ServletException, IOException {
630
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
631

    
632
		// Update the last update time for this user if they are not new
633
		HttpSession httpSession = request.getSession(false);
634
		if (httpSession != null) {
635
			SessionService.touchSession(httpSession.getId());
636
		}
637
		
638
		// Each time metacat is called, check to see if metacat has been 
639
		// configured. If not then forward to the administration servlet
640
		if (!ConfigurationUtil.isMetacatConfigured()) {
641
			try {
642
				RequestUtil.forwardRequest(request, response, "/admin?action=configure", null);
643
				return;
644
			} catch (MetacatUtilException mue) {
645
				logMetacat.error("MetacatServlet.handleGetOrPost - utility error when forwarding to " + 
646
						"configuration screen: " + mue.getMessage());
647
				throw new ServletException("MetacatServlet.handleGetOrPost - utility error when forwarding to " + 
648
						"configuration screen: " + mue.getMessage());
649
			}
650
		}
651

    
652
		// if we get here, metacat is configured.  If we have not completed the 
653
		// second half of the initialization, do so now.  This allows us to initially
654
		// configure metacat without a restart.
655
		if (!_fullyInitialized) {
656
			initSecondHalf(request.getSession().getServletContext());
657
		}
658
		
659
		/*
660
		 * logMetacat.debug("Connection pool size: "
661
		 * +connPool.getSizeOfDBConnectionPool(),10); logMetacat.debug("Free
662
		 * DBConnection number: "
663
		 */
664
		// If all DBConnection in the pool are free and DBConnection pool
665
		// size is greater than initial value, shrink the connection pool
666
		// size to initial value
667
		DBConnectionPool.shrinkDBConnectionPoolSize();
668

    
669
		// Debug message to print out the method which have a busy DBConnection
670
		try {
671
			@SuppressWarnings("unused")
672
			DBConnectionPool pool = DBConnectionPool.getInstance();
673
//			pool.printMethodNameHavingBusyDBConnection();
674
		} catch (SQLException e) {
675
			logMetacat.error("MetaCatServlet.handleGetOrPost - Error in MetacatServlet.handleGetOrPost: " + e.getMessage());
676
			e.printStackTrace();
677
		}
678

    
679
		try {
680
			String ctype = request.getContentType();
681
			
682
			if (ctype != null && ctype.startsWith("multipart/form-data")) {
683
				handler.handleMultipartForm(request, response);
684
				return;
685
			} 
686

    
687
			String name = null;
688
			String[] value = null;
689
			String[] docid = new String[3];
690
			Hashtable<String, String[]> params = new Hashtable<String, String[]>();
691

    
692
			// Check if this is a simple read request that doesn't use the
693
			// "action" syntax
694
			// These URLs are of the form:
695
			// http://localhost:8180/knb/metacat/docid/skinname
696
			// e.g., http://localhost:8180/knb/metacat/test.1.1/knb
697
			String pathInfo = request.getPathInfo();
698
			if (pathInfo != null) {
699
				String[] path = pathInfo.split("/");
700
				if (path.length > 1) {
701
					String docidToRead = path[1];
702
					String docs[] = new String[1];
703
					docs[0] = docidToRead;
704
					logMetacat.debug("MetaCatServlet.handleGetOrPost - READING DOCID FROM PATHINFO: " + docs[0]);
705
					params.put("docid", docs);
706
					String skin = null;
707
					if (path.length > 2) {
708
						skin = path[2];
709
						String skins[] = new String[1];
710
						skins[0] = skin;
711
						params.put("qformat", skins);
712
					}
713
					handler.handleReadAction(params, request, response, "public", null, null);
714
					return;
715
				}
716
			}
717

    
718
			Enumeration<String> paramlist = 
719
				(Enumeration<String>) request.getParameterNames();
720
			while (paramlist.hasMoreElements()) {
721

    
722
				name = paramlist.nextElement();
723
				value = request.getParameterValues(name);
724

    
725
				// Decode the docid and mouse click information
726
				// THIS IS OBSOLETE -- I THINK -- REMOVE THIS BLOCK
727
				// 4/12/2007d
728
				// MBJ
729
				if (name.endsWith(".y")) {
730
					docid[0] = name.substring(0, name.length() - 2);
731
					params.put("docid", docid);
732
					name = "ypos";
733
				}
734
				if (name.endsWith(".x")) {
735
					name = "xpos";
736
				}
737

    
738
				params.put(name, value);
739
			}
740

    
741
			// handle param is emptpy
742
			if (params.isEmpty() || params == null) {
743
				return;
744
			}
745

    
746
			// if the user clicked on the input images, decode which image
747
			// was clicked then set the action.
748
			if (params.get("action") == null) {
749
				PrintWriter out = response.getWriter();
750
				response.setContentType("text/xml");
751
				out.println("<?xml version=\"1.0\"?>");
752
				out.println("<error>");
753
				out.println("Action not specified");
754
				out.println("</error>");
755
				out.close();
756
				return;
757
			}
758

    
759
			String action = (params.get("action"))[0];
760
			logMetacat.info("MetaCatServlet.handleGetOrPost - Action is: " + action);
761

    
762
			// This block handles session management for the servlet
763
			// by looking up the current session information for all actions
764
			// other than "login" and "logout"
765
			String userName = null;
766
			String password = null;
767
			String[] groupNames = null;
768
			String sessionId = null;
769
			name = null;
770

    
771
			// handle login action
772
			if (action.equals("login")) {
773
				PrintWriter out = response.getWriter();
774
				handler.handleLoginAction(out, params, request, response);
775
				out.close();
776

    
777
				// handle logout action
778
			} else if (action.equals("logout")) {
779
				PrintWriter out = response.getWriter();
780
				handler.handleLogoutAction(out, params, request, response);
781
				out.close();
782

    
783
				// handle shrink DBConnection request
784
			} else if (action.equals("validatesession")) {
785
				PrintWriter out = response.getWriter();
786
				String idToValidate = null;
787
				String idsToValidate[] = params.get("sessionid");
788
				if (idsToValidate != null) {
789
					idToValidate = idsToValidate[0];
790
				}
791
				SessionService.validateSession(out, response, idToValidate);
792
				out.close();
793

    
794
				// handle shrink DBConnection request
795
			} else if (action.equals("shrink")) {
796
				PrintWriter out = response.getWriter();
797
				boolean success = false;
798
				// If all DBConnection in the pool are free and DBConnection
799
				// pool
800
				// size is greater than initial value, shrink the connection
801
				// pool
802
				// size to initial value
803
				success = DBConnectionPool.shrinkConnectionPoolSize();
804
				if (success) {
805
					// if successfully shrink the pool size to initial value
806
					out.println("DBConnection Pool shrunk successfully.");
807
				}// if
808
				else {
809
					out.println("DBConnection pool not shrunk successfully.");
810
				}
811
				// close out put
812
				out.close();
813

    
814
				// aware of session expiration on every request
815
			} else {
816
				SessionData sessionData = RequestUtil.getSessionData(request);
817
				
818
				if (sessionData != null) {
819
					userName = sessionData.getUserName();
820
					password = sessionData.getPassword();
821
					groupNames = sessionData.getGroupNames();
822
					sessionId = sessionData.getId();
823
				}
824

    
825
				logMetacat.info("MetaCatServlet.handleGetOrPost - The user is : " + userName);
826
			}
827
			// Now that we know the session is valid, we can delegate the
828
			// request to a particular action handler
829
			if (action.equals("query")) {
830
				ServletOutputStream streamOut = response.getOutputStream();
831
				PrintWriter out = new PrintWriter(streamOut);
832
				handler.handleQuery(out, params, response, userName, groupNames, sessionId);
833
				out.close();
834
			} else if (action.equals("squery")) {
835
				ServletOutputStream streamOut = response.getOutputStream();
836
				PrintWriter out = new PrintWriter(streamOut);
837
				if (params.containsKey("query")) {
838
					handler.handleSQuery(out, params, response, userName, groupNames, sessionId);
839
					out.close();
840
				} else {
841
					out.println("Illegal action squery without \"query\" parameter");
842
					out.close();
843
				}
844
			} else if (action.trim().equals("spatial_query")) {
845

    
846
				logMetacat
847
						.debug("MetaCatServlet.handleGetOrPost - ******************* SPATIAL QUERY ********************");
848
				ServletOutputStream streamOut = response.getOutputStream();
849
				PrintWriter out = new PrintWriter(streamOut);
850
				handler.handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
851
				out.close();
852

    
853
			} else if (action.trim().equals("dataquery")) {
854

    
855
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* DATA QUERY ********************");
856
				handler.handleDataquery(params, response, sessionId);
857
			} else if (action.trim().equals("editcart")) {
858
				logMetacat.debug("MetaCatServlet.handleGetOrPost - ******************* EDIT CART ********************");
859
				handler.handleEditCart(params, response, sessionId);
860
			} else if (action.equals("export")) {
861

    
862
				handler.handleExportAction(params, response, userName, groupNames, password);
863
			} else if (action.equals("read")) {
864
				if (params.get("archiveEntryName") != null) {
865
					ArchiveHandler.getInstance().readArchiveEntry(params, request,
866
							response, userName, password, groupNames);
867
				} else {
868
					handler.handleReadAction(params, request, response, userName, password,
869
							groupNames);
870
				}
871
			} else if (action.equals("readinlinedata")) {
872
				handler.handleReadInlineDataAction(params, request, response, userName, password,
873
						groupNames);
874
			} else if (action.equals("insert") || action.equals("update")) {
875
				PrintWriter out = response.getWriter();
876
				if ((userName != null) && !userName.equals("public")) {
877
					handler.handleInsertOrUpdateAction(request.getRemoteAddr(), response, out, params, userName,
878
							groupNames);
879
				} else {
880
					response.setContentType("text/xml");
881
					out.println("<?xml version=\"1.0\"?>");
882
					out.println("<error>");
883
					out.println("Permission denied for user " + userName + " " + action);
884
					out.println("</error>");
885
				}
886
				out.close();
887
			} else if (action.equals("delete")) {
888
				PrintWriter out = response.getWriter();
889
				if ((userName != null) && !userName.equals("public")) {
890
					handler.handleDeleteAction(out, params, request, response, userName,
891
							groupNames);
892
				} else {
893
					response.setContentType("text/xml");
894
					out.println("<?xml version=\"1.0\"?>");
895
					out.println("<error>");
896
					out.println("Permission denied for " + action);
897
					out.println("</error>");
898
				}
899
				out.close();
900
			} else if (action.equals("validate")) {
901
				PrintWriter out = response.getWriter();
902
				handler.handleValidateAction(out, params);
903
				out.close();
904
			} else if (action.equals("setaccess")) {
905
				PrintWriter out = response.getWriter();
906
				handler.handleSetAccessAction(out, params, userName, request, response);
907
				out.close();
908
			} else if (action.equals("getaccesscontrol")) {
909
				PrintWriter out = response.getWriter();
910
				handler.handleGetAccessControlAction(out, params, response, userName, groupNames);
911
				out.close();
912
			} else if (action.equals("isauthorized")) {
913
				PrintWriter out = response.getWriter();
914
				DocumentUtil.isAuthorized(out, params, request, response);
915
				out.close();
916
			} else if (action.equals("getprincipals")) {
917
				PrintWriter out = response.getWriter();
918
				handler.handleGetPrincipalsAction(out, userName, password);
919
				out.close();
920
			} else if (action.equals("getdoctypes")) {
921
				PrintWriter out = response.getWriter();
922
				handler.handleGetDoctypesAction(out, params, response);
923
				out.close();
924
			} else if (action.equals("getdtdschema")) {
925
				PrintWriter out = response.getWriter();
926
				handler.handleGetDTDSchemaAction(out, params, response);
927
				out.close();
928
			} else if (action.equals("getlastdocid")) {
929
				PrintWriter out = response.getWriter();
930
				handler.handleGetMaxDocidAction(out, params, response);
931
				out.close();
932
			} else if (action.equals("getalldocids")) {
933
				PrintWriter out = response.getWriter();
934
				handler.handleGetAllDocidsAction(out, params, response);
935
				out.close();
936
			} else if (action.equals("isregistered")) {
937
				PrintWriter out = response.getWriter();
938
				handler.handleIdIsRegisteredAction(out, params, response);
939
				out.close();
940
			} else if (action.equals("getrevisionanddoctype")) {
941
				PrintWriter out = response.getWriter();
942
				handler.handleGetRevisionAndDocTypeAction(out, params);
943
				out.close();
944
			} else if (action.equals("getversion")) {
945
				response.setContentType("text/xml");
946
				PrintWriter out = response.getWriter();
947
				out.println(MetacatVersion.getVersionAsXml());
948
				out.close();
949
			} else if (action.equals("getlog")) {
950
				handler.handleGetLogAction(params, request, response, userName, groupNames);
951
			} else if (action.equals("getloggedinuserinfo")) {
952
				PrintWriter out = response.getWriter();
953
				response.setContentType("text/xml");
954
				out.println("<?xml version=\"1.0\"?>");
955
				out.println("\n<user>\n");
956
				out.println("\n<username>\n");
957
				out.println(userName);
958
				out.println("\n</username>\n");
959
				if (name != null) {
960
					out.println("\n<name>\n");
961
					out.println(name);
962
					out.println("\n</name>\n");
963
				}
964
				if (AuthUtil.isAdministrator(userName, groupNames)) {
965
					out.println("<isAdministrator></isAdministrator>\n");
966
				}
967
				if (AuthUtil.isModerator(userName, groupNames)) {
968
					out.println("<isModerator></isModerator>\n");
969
				}
970
				out.println("\n</user>\n");
971
				out.close();
972
			} else if (action.equals("buildindex")) {
973
				handler.handleBuildIndexAction(params, request, response, userName, groupNames);
974
			} else if (action.equals("login") || action.equals("logout")) {
975
				/*
976
				 * } else if (action.equals("protocoltest")) { String testURL =
977
				 * "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9"; try { testURL =
978
				 * ((String[]) params.get("url"))[0]; } catch (Throwable t) { }
979
				 * String phandler = System
980
				 * .getProperty("java.protocol.handler.pkgs");
981
				 * response.setContentType("text/html"); PrintWriter out =
982
				 * response.getWriter(); out.println("<body
983
				 * bgcolor=\"white\">"); out.println("<p>Handler property:
984
				 * <code>" + phandler + "</code></p>"); out.println("<p>Starting
985
				 * test for:<br>"); out.println(" " + testURL + "</p>"); try {
986
				 * URL u = new URL(testURL); out.println("<pre>");
987
				 * out.println("Protocol: " + u.getProtocol()); out.println("
988
				 * Host: " + u.getHost()); out.println(" Port: " + u.getPort());
989
				 * out.println(" Path: " + u.getPath()); out.println(" Ref: " +
990
				 * u.getRef()); String pquery = u.getQuery(); out.println("
991
				 * Query: " + pquery); out.println(" Params: "); if (pquery !=
992
				 * null) { Hashtable qparams =
993
				 * MetacatUtil.parseQuery(u.getQuery()); for (Enumeration en =
994
				 * qparams.keys(); en .hasMoreElements();) { String pname =
995
				 * (String) en.nextElement(); String pvalue = (String)
996
				 * qparams.get(pname); out.println(" " + pname + ": " + pvalue); } }
997
				 * out.println("</pre>"); out.println("</body>");
998
				 * out.close(); } catch (MalformedURLException mue) {
999
				 * System.out.println( "bad url from
1000
				 * MetacatServlet.handleGetOrPost");
1001
				 * out.println(mue.getMessage()); mue.printStackTrace(out);
1002
				 * out.close(); }
1003
				 */
1004
			} else if (action.equals("refreshServices")) {
1005
				// TODO MCD this interface is for testing. It should go through
1006
				// a ServiceService class and only work for an admin user. Move 
1007
				// to the MetacatAdminServlet
1008
				ServiceService.refreshService("XMLSchemaService");
1009
				return;
1010
			} else if (action.equals("scheduleWorkflow")) {
1011
				try {
1012
					WorkflowSchedulerClient.getInstance().scheduleJob(request, response,
1013
							params, userName, groupNames);
1014
					return;
1015
				} catch (BaseException be) {
1016
					ResponseUtil.sendErrorXML(response,
1017
							ResponseUtil.SCHEDULE_WORKFLOW_ERROR, be);
1018
					return;
1019
				}
1020
			} else if (action.equals("unscheduleWorkflow")) {
1021
				try {
1022
					WorkflowSchedulerClient.getInstance().unScheduleJob(request,
1023
							response, params, userName, groupNames);
1024
					return;
1025
				} catch (BaseException be) {
1026
					ResponseUtil.sendErrorXML(response,
1027
							ResponseUtil.UNSCHEDULE_WORKFLOW_ERROR, be);
1028
					return;
1029
				}
1030
			} else if (action.equals("rescheduleWorkflow")) {
1031
				try {
1032
					WorkflowSchedulerClient.getInstance().reScheduleJob(request,
1033
							response, params, userName, groupNames);
1034
					return;
1035
				} catch (BaseException be) {
1036
					ResponseUtil.sendErrorXML(response,
1037
							ResponseUtil.RESCHEDULE_WORKFLOW_ERROR, be);
1038
					return;
1039
				}
1040
			} else if (action.equals("getScheduledWorkflow")) {
1041
				try {
1042
					WorkflowSchedulerClient.getInstance().getJobs(request, response,
1043
							params, userName, groupNames);
1044
					return;
1045
				} catch (BaseException be) {
1046
					ResponseUtil.sendErrorXML(response,
1047
							ResponseUtil.GET_SCHEDULED_WORKFLOW_ERROR, be);
1048
					return;
1049
				}
1050
			} else if (action.equals("deleteScheduledWorkflow")) {
1051
				try {
1052
					WorkflowSchedulerClient.getInstance().deleteJob(request, response,
1053
							params, userName, groupNames);
1054
					return;
1055
				} catch (BaseException be) {
1056
					ResponseUtil.sendErrorXML(response,
1057
							ResponseUtil.DELETE_SCHEDULED_WORKFLOW_ERROR, be);
1058
					return;
1059
				}
1060

    
1061
			} else {
1062
				PrintWriter out = response.getWriter();
1063
				out.println("<?xml version=\"1.0\"?>");
1064
				out.println("<error>");
1065
				out.println("Error: action: " + action + " not registered.  Please report this error.");
1066
				out.println("</error>");
1067
				out.close();
1068
			}
1069

    
1070
			// Schedule the sitemap generator to run periodically
1071
			handler.scheduleSitemapGeneration(request);
1072

    
1073

    
1074
		} catch (PropertyNotFoundException pnfe) {
1075
			String errorString = "Critical property not found: " + pnfe.getMessage();
1076
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1077
			throw new ServletException(errorString);
1078
		} catch (MetacatUtilException ue) {
1079
			String errorString = "Utility error: " + ue.getMessage();
1080
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1081
			throw new ServletException(errorString);
1082
		} catch (ServiceException ue) {
1083
			String errorString = "Service error: " + ue.getMessage();
1084
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1085
			throw new ServletException(errorString);
1086
		} catch (HandlerException he) {
1087
			String errorString = "Handler error: " + he.getMessage();
1088
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1089
			throw new ServletException(errorString);
1090
		} catch (ErrorSendingErrorException esee) {
1091
			String errorString = "Error sending error message: " + esee.getMessage();
1092
			logMetacat.error("MetaCatServlet.handleGetOrPost - " + errorString);
1093
			throw new ServletException(errorString);
1094
		} catch (ErrorHandledException ehe) {
1095
			// Nothing to do here.  We assume if we get here, the error has been 
1096
			// written to ouput.  Continue on and let it display.
1097
		} 
1098
	}
1099
    
1100
    /**
1101
     * Reports whether the MetaCatServlet has been fully initialized
1102
     * 
1103
     * @return true if fully intialized, false otherwise
1104
     */
1105
    public static boolean isFullyInitialized() {
1106
    	return _fullyInitialized;
1107
    }
1108
}
(42-42/62)