Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements database configuration methods
4
 *  Copyright: 2008 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Michael Daigle
7
 * 
8
 *   '$Author: daigle $'
9
 *     '$Date: 2009-08-14 14:26:08 -0700 (Fri, 14 Aug 2009) $'
10
 * '$Revision: 5027 $'
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.admin;
28

    
29
import java.sql.Connection;
30
import java.sql.PreparedStatement;
31
import java.sql.SQLException;
32
import java.sql.ResultSet;
33
import java.sql.Statement;
34
import java.sql.Timestamp;
35

    
36
import java.io.BufferedReader;
37
import java.io.FileInputStream;
38
import java.io.IOException;
39
import java.io.InputStreamReader;
40

    
41
import java.util.Date;
42
import java.util.HashMap;
43
import java.util.HashSet;
44
import java.util.Map;
45
import java.util.TreeSet;
46
import java.util.Vector;
47

    
48
import javax.servlet.ServletException;
49
import javax.servlet.http.HttpServletRequest;
50
import javax.servlet.http.HttpServletResponse;
51
import javax.servlet.http.HttpSession;
52

    
53
import edu.ucsb.nceas.metacat.MetacatVersion;
54
import edu.ucsb.nceas.metacat.database.DBConnection;
55
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
56
import edu.ucsb.nceas.metacat.database.DBVersion;
57
import edu.ucsb.nceas.metacat.service.PropertyService;
58
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
59
import edu.ucsb.nceas.metacat.util.DatabaseUtil;
60
import edu.ucsb.nceas.metacat.util.RequestUtil;
61
import edu.ucsb.nceas.metacat.util.SystemUtil;
62

    
63
import edu.ucsb.nceas.utilities.DBUtil;
64
import edu.ucsb.nceas.utilities.FileUtil;
65
import edu.ucsb.nceas.utilities.GeneralPropertyException;
66
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
67

    
68
import org.apache.log4j.Logger;
69

    
70
/**
71
 * Control the display of the database configuration page and the processing
72
 * of the configuration values.
73
 */
74
public class DBAdmin extends MetacatAdmin {
75
	// db statuses used by discovery code
76
	public static final int DB_DOES_NOT_EXIST = 0;
77
	public static final int TABLES_DO_NOT_EXIST = 1;
78
	public static final int TABLES_EXIST = 2;
79

    
80
	// db version statuses. This allows us to keep version history
81
	// in the db. Only the latest version record should be active.
82
	public static final int VERSION_INACTIVE = 0;
83
	public static final int VERSION_ACTIVE = 1;
84

    
85
	private TreeSet<DBVersion> versionSet = null;
86

    
87
	private static DBAdmin dbAdmin = null;
88
	private Logger logMetacat = Logger.getLogger(DBAdmin.class);
89
	private HashSet<String> sqlCommandSet = new HashSet<String>();
90
	private Map<String, String> scriptSuffixMap = new HashMap<String, String>();
91
	private static DBVersion databaseVersion = null;
92

    
93
	/**
94
	 * private constructor since this is a singleton
95
	 */
96
	private DBAdmin() throws AdminException {
97
		sqlCommandSet.add("INSERT");
98
		sqlCommandSet.add("UPDATE");
99
		sqlCommandSet.add("DELETE");
100
		sqlCommandSet.add("ALTER");
101
		sqlCommandSet.add("CREATE");
102
		sqlCommandSet.add("DROP");
103
		sqlCommandSet.add("BEGIN");
104
		sqlCommandSet.add("COMMIT");
105

    
106
		// gets all the upgrade version objects
107
		try {
108
			versionSet = DatabaseUtil.getUpgradeVersions();
109
			scriptSuffixMap = DatabaseUtil.getScriptSuffixes();
110
		} catch (PropertyNotFoundException pnfe) {
111
			throw new AdminException("Could not retrieve database upgrade " 
112
					+ "versions during instantiation" + pnfe.getMessage());
113
		} catch (NumberFormatException nfe) {
114
			throw new AdminException("Bad version format numbering: "
115
					+ nfe.getMessage());
116
		}
117
	}
118

    
119
	/**
120
	 * Get the single instance of DBAdmin.
121
	 * 
122
	 * @return the single instance of DBAdmin
123
	 */
124
	public static DBAdmin getInstance() throws AdminException {
125
		if (dbAdmin == null) {
126
			dbAdmin = new DBAdmin();
127
		}
128
		return dbAdmin;
129
	}
130

    
131
	/**
132
	 * Handle configuration of the database the first time that Metacat starts
133
	 * or when it is explicitly called. Collect necessary update information
134
	 * from the administrator.
135
	 * 
136
	 * @param request
137
	 *            the http request information
138
	 * @param response
139
	 *            the http response to be sent back to the client
140
	 */
141
	public void configureDatabase(HttpServletRequest request,
142
			HttpServletResponse response) throws AdminException {
143

    
144
		String processForm = request.getParameter("processForm");
145
		String formErrors = (String) request.getAttribute("formErrors");
146
		HttpSession session = request.getSession();
147

    
148
		if (processForm == null || !processForm.equals("true") || formErrors != null) {
149
			// The servlet configuration parameters have not been set, or there
150
			// were form errors on the last attempt to configure, so redirect to
151
			// the web form for configuring metacat
152

    
153
			try {
154
				// get the current metacat version and the database version. If
155
				// the database version is older that the metacat version, run
156
				// the appropriate scripts to get them synchronized.
157

    
158
				databaseVersion = discoverDBVersion();
159
				MetacatVersion metacatVersion = SystemUtil.getMetacatVersion();
160
				
161
				session.setAttribute("metacatVersion", MetacatVersion.getVersionID());
162

    
163
				// if the db version is already the same as the metacat
164
				// version, update metacat.properties
165
				if (databaseVersion.compareTo(metacatVersion) == 0) {
166
					PropertyService.setProperty("configutil.databaseConfigured",
167
							PropertyService.CONFIGURED);
168
				}
169
				
170
				MetacatVersion metaCatVersion = SystemUtil.getMetacatVersion();
171
				request.setAttribute("metacatVersion", metaCatVersion);
172
				DBVersion dbVersionString = getDBVersion();
173
				request.setAttribute("databaseVersion", dbVersionString);
174
				Vector<String> updateScriptList = getUpdateScripts();
175
				request.setAttribute("updateScriptList", updateScriptList);
176
				String supportEmail = PropertyService.getProperty("email.recipient");
177
				request.setAttribute("supportEmail", supportEmail);
178

    
179
				// Forward the request to the JSP page
180
				RequestUtil.clearRequestMessages(request);
181
				RequestUtil.forwardRequest(request, response,
182
						"/admin/database-configuration.jsp", null);
183
			} catch (GeneralPropertyException gpe) {
184
				throw new AdminException("Problem getting or setting property while " 
185
						+ "initializing system properties page: " + gpe.getMessage());
186
			} catch (IOException ioe) {
187
				throw new AdminException("IO problem while initializing "
188
						+ "system properties page:" + ioe.getMessage());
189
			} catch (ServletException se) {
190
				throw new AdminException("problem forwarding request while "
191
						+ "initializing system properties page: " + se.getMessage());
192
			}  
193
		} else {
194
			// The configuration form is being submitted and needs to be
195
			// processed, setting the properties in the configuration file
196
			// then restart metacat
197

    
198
			// The configuration form is being submitted and needs to be
199
			// processed.
200
			Vector<String> validationErrors = new Vector<String>();
201
			Vector<String> processingSuccess = new Vector<String>();
202

    
203
			try {
204
				// Validate that the options provided are legitimate. Note that
205
				// we've allowed them to persist their entries. As of this point
206
				// there is no other easy way to go back to the configure form
207
				// and
208
				// preserve their entries.
209
				validationErrors.addAll(validateOptions(request));
210

    
211
				upgradeDatabase();
212

    
213
				// Now that the options have been set, change the
214
				// 'databaseConfigured' option to 'true' so that normal metacat
215
				// requests will go through
216
				PropertyService.setProperty("configutil.databaseConfigured",
217
						PropertyService.CONFIGURED);
218

    
219
				// Reload the main metacat configuration page
220
				processingSuccess.add("Database successfully upgraded");
221
				RequestUtil.clearRequestMessages(request);
222
				RequestUtil.setRequestSuccess(request, processingSuccess);
223
				RequestUtil.forwardRequest(request, response,
224
						"/admin?configureType=configure&processForm=false", null);
225
				// Write out the configurable properties to a backup file
226
				// outside the install directory.
227

    
228
				PropertyService.persistMainBackupProperties(request.getSession()
229
						.getServletContext());
230
			} catch (GeneralPropertyException gpe) {
231
				throw new AdminException("Problem getting or setting property while "
232
						+ "upgrading database: " + gpe.getMessage());
233
			}  catch (IOException ioe) {
234
				throw new AdminException("IO problem while upgrading database: "
235
						 + ioe.getMessage());
236
			} catch (ServletException se) {
237
				throw new AdminException("problem forwarding request while "
238
						+ "upgrading database: " + se.getMessage());
239
			}
240
		}
241
	}
242

    
243

    
244
	/**
245
	 * Performs a status check on the database.
246
	 * 
247
	 * @returns integer representing the status of the database. These can be: 
248
	 * 		-- DB_DOES_NOT_EXIST = 0; 
249
	 *      -- TABLES_DO_NOT_EXIST = 1; 
250
	 *      -- TABLES_EXIST = 2;
251
	 */
252
	public int getDBStatus() throws SQLException, PropertyNotFoundException {
253
		Connection connection = DBUtil.getConnection(PropertyService
254
				.getProperty("database.connectionURI"), PropertyService
255
				.getProperty("database.user"), PropertyService
256
				.getProperty("database.password"));
257

    
258
		if (DBUtil.tableExists(connection, "xml_documents")) {
259
			return TABLES_EXIST;
260
		}
261

    
262
		return TABLES_DO_NOT_EXIST;
263
	}
264

    
265
	/**
266
	 * Get the version of the database as a string
267
	 * 
268
	 * @returns string representing the version of the database.
269
	 */
270
	public DBVersion getDBVersion() throws AdminException {
271

    
272
		// don't even try to search for a database version until system
273
		// properties have been configured
274
		try {
275
			if (!PropertyService.arePropertiesConfigured()) {
276
				throw new AdminException("An attempt was made to get the database version "
277
								+ "before system properties were configured");
278
			}
279
		} catch (MetacatUtilException ue) {
280
			throw new AdminException("Could not determine the database version: "
281
					+ ue.getMessage());
282
		}
283
		if (databaseVersion == null) {
284
			databaseVersion = discoverDBVersion();
285
		}
286

    
287
		if (databaseVersion == null) {
288
			throw new AdminException("Could not find database version");
289
		}
290

    
291
		return databaseVersion;
292
	}
293

    
294
	/**
295
	 * Try to discover the database version, first by calling
296
	 * getRegisteredDBVersion() to see if the database version is in a table in
297
	 * the database. If not, getUnRegisteredDBVersion() is called to see if we
298
	 * can devine the version by looking for unique changes made by scripts for
299
	 * each version update.
300
	 * 
301
	 * @returns string representing the version of the database, null if none
302
	 *          could be found.
303
	 */
304
	private DBVersion discoverDBVersion() throws AdminException {
305
		try {
306
			int dbStatus = getDBStatus();
307
			if (dbStatus == DB_DOES_NOT_EXIST) {
308
				throw new AdminException(
309
						"Database does not exist for connection"
310
						+ PropertyService.getProperty("database.connectionURI"));
311
			} else if (dbStatus == TABLES_DO_NOT_EXIST) {
312
				databaseVersion = new DBVersion("0.0.0");
313
				return databaseVersion;
314
			}
315

    
316
			databaseVersion = getRegisteredDBVersion();
317
			if (databaseVersion != null) {
318
				return databaseVersion;
319
			}
320

    
321
			databaseVersion = getUnRegisteredDBVersion();
322
			
323
		} catch (SQLException sqle) {
324
			String errorMessage = "SQL error during  database version discovery: "
325
				+ sqle.getMessage();
326
			logMetacat.error(errorMessage);
327
			throw new AdminException(errorMessage);
328
		} catch (PropertyNotFoundException pnfe) {
329
			String errorMessage = "Property not found during  database version discovery: "
330
					+ pnfe.getMessage();
331
			logMetacat.error(errorMessage);
332
			throw new AdminException(errorMessage);
333
		} catch (NumberFormatException nfe) {
334
			throw new AdminException("Bad version format numbering: "
335
					+ nfe.getMessage());
336
		}
337
		
338
		if (databaseVersion == null) {
339
			throw new AdminException("Database version discovery returned null");
340
		}
341
		return databaseVersion;
342
	}
343

    
344
	/**
345
	 * Gets the version of the database from the db_version table. Usually this
346
	 * is the same as the version of the product, however the db version could
347
	 * be more granular if we applied a maintenance patch for instance.
348
	 * 
349
	 * @returns string representing the version of the database.
350
	 */
351
	private DBVersion getRegisteredDBVersion() throws AdminException, SQLException {
352
		String dbVersionString = null;
353
		PreparedStatement pstmt = null;
354

    
355
		try {
356
			// check out DBConnection
357
			Connection connection = 
358
				DBUtil.getConnection(
359
						PropertyService.getProperty("database.connectionURI"),
360
						PropertyService.getProperty("database.user"),
361
						PropertyService.getProperty("database.password"));
362

    
363
			if (!DBUtil.tableExists(connection, "db_version")) {
364
				return null;
365
			}
366

    
367
			pstmt = 
368
				connection.prepareStatement("SELECT version FROM db_version WHERE status = ?");
369

    
370
			// Bind the values to the query
371
			pstmt.setInt(1, VERSION_ACTIVE);
372
			pstmt.execute();
373
			ResultSet rs = pstmt.getResultSet();
374
			boolean hasRows = rs.next();
375
			if (hasRows) {
376
				dbVersionString = rs.getString(1);
377
			}
378
			
379
			if (dbVersionString == null) {
380
				return null;
381
			} 
382
				
383
			return new DBVersion(dbVersionString);
384
			
385
		} catch (SQLException sqle) {
386
			throw new AdminException("Could not run SQL to get registered db version: " 
387
					+ sqle.getMessage());			
388
		} catch (PropertyNotFoundException pnfe) {
389
			throw new AdminException("Could not get property for registered db version: " 
390
					+ pnfe.getMessage());		
391
		} catch (NumberFormatException nfe) {
392
			throw new AdminException("Bad version format numbering: "
393
					+ nfe.getMessage());
394
		} finally {
395
			if (pstmt != null) {
396
				pstmt.close();
397
			}
398
		}
399
	}
400

    
401
	/**
402
	 * Finds the version of the database for a database that does not have a
403
	 * dbVersion table yet. Work backwards with various clues found in update
404
	 * scripts to find the version.
405
	 * 
406
	 * @returns string representing the version of the database.
407
	 */
408
	public DBVersion getUnRegisteredDBVersion() throws AdminException, SQLException {
409
		Connection connection = null;
410
		try {
411
			connection = DBUtil.getConnection(PropertyService
412
					.getProperty("database.connectionURI"), PropertyService
413
					.getProperty("database.user"), PropertyService
414
					.getProperty("database.password"));
415

    
416
			String dbVersionString = null;
417

    
418
			if (is1_9_1(connection)) {
419
				dbVersionString = "1.9.1";
420
			} else if (is1_9_0(connection)) {
421
				dbVersionString = "1.9.0";
422
			} else if (is1_8_0(connection)) {
423
				dbVersionString = "1.8.0";
424
			} else if (is1_7_0(connection)) {
425
				dbVersionString = "1.7.0";
426
			} else if (is1_6_0(connection)) {
427
				dbVersionString = "1.6.0";
428
			} else if (is1_5_0(connection)) {
429
				dbVersionString = "1.5.0";
430
			} else if (is1_4_0(connection)) {
431
				dbVersionString = "1.4.0";
432
			} else if (is1_3_0(connection)) {
433
				dbVersionString = "1.3.0";
434
			} else if (is1_2_0(connection)) {
435
				dbVersionString = "1.2.0";
436
			}
437

    
438
			if (dbVersionString == null) {
439
				return null;
440
			} else {
441
				return new DBVersion(dbVersionString);
442
			}
443
		} catch (PropertyNotFoundException pnfe) {
444
			throw new AdminException(
445
					"Could not get property for unregistered db version: "
446
							+ pnfe.getMessage());
447
		} catch (NumberFormatException nfe) {
448
			throw new AdminException("Bad version format numbering: "
449
					+ nfe.getMessage());
450
		}
451
	}
452

    
453
	/**
454
	 * Updates the version of the database. Typically this is done in the update
455
	 * scripts that get run when we upgrade the application. This method can be
456
	 * used if you are automating a patch on the database internally.
457
	 * 
458
	 * @returns string representing the version of the database.
459
	 */
460
	public void updateDBVersion() throws SQLException {
461
		DBConnection conn = null;
462
		PreparedStatement pstmt = null;
463
		int serialNumber = -1;
464
		try {
465

    
466
			// check out DBConnection
467
			conn = DBConnectionPool
468
					.getDBConnection("DBAdmin.updateDBVersion()");
469
			serialNumber = conn.getCheckOutSerialNumber();
470
			conn.setAutoCommit(false);
471

    
472
			pstmt = conn.prepareStatement("UPDATE db_version SET status = ?");
473
			pstmt.setInt(1, VERSION_INACTIVE);
474
			pstmt.execute();
475
			pstmt.close();
476

    
477
			pstmt = conn.prepareStatement("INSERT INTO db_version "
478
					+ "(version, status, date_created) VALUES (?,?,?)");
479
			pstmt.setString(1, MetacatVersion.getVersionID());
480
			pstmt.setInt(2, VERSION_ACTIVE);
481
			pstmt.setTimestamp(3, new Timestamp(new Date().getTime()));
482
			pstmt.execute();
483

    
484
			conn.commit();
485
		} catch (SQLException e) {
486
			conn.rollback();
487
			throw new SQLException("DBAdmin.getDBVersion(). " + e.getMessage());
488
		} catch (PropertyNotFoundException pnfe) {
489
			conn.rollback();
490
			throw new SQLException("DBAdmin.getDBVersion(). " + pnfe.getMessage());
491
		}
492
		finally {
493
			try {
494
				pstmt.close();
495
			} finally {
496
				DBConnectionPool.returnDBConnection(conn, serialNumber);
497
			}
498
		}
499
	}
500

    
501
	/**
502
	 * Validate connectivity to the database. Validation methods return a string
503
	 * error message if there is an issue. This allows the calling code to run
504
	 * several validations and compile the errors into a list that can be
505
	 * displayed on a web page if desired.
506
	 * 
507
	 * @param dbDriver
508
	 *            the database driver
509
	 * @param connection
510
	 *            the jdbc connection string
511
	 * @param user
512
	 *            the user name
513
	 * @param password
514
	 *            the login password
515
	 * @return a string holding error message if validation fails.
516
	 */
517
	public String validateDBConnectivity(String dbDriver, String connection,
518
			String user, String password) {
519
		try {
520
			DBConnection.testConnection(dbDriver, connection, user, password);
521
		} catch (SQLException se) {
522
			return "Invalid database credential was provided: "
523
					+ se.getMessage();
524
		}
525

    
526
		return null;
527
	}
528

    
529
	/**
530
	 * Checks to see if this is a 1.9.0 database schema by looking for the
531
	 * db_version table which was created for 1.9.0. Note, there is no guarantee
532
	 * that this table will not be removed in subsequent versions. You should
533
	 * search for db versions from newest to oldest, only getting to this
534
	 * function when newer versions have not been matched.
535
	 * 
536
	 * @param dbMetaData
537
	 *            the meta data for this database.
538
	 * @returns boolean which is true if table is found, false otherwise
539
	 */
540
	private boolean is1_9_0(Connection connection) throws SQLException {
541
		return DBUtil.tableExists(connection, "db_version");
542
	}
543
	
544
	/**
545
	 * Checks to see if this is a 1.9.1 database schema by looking for the
546
	 * scheduled_job table which was created for 1.9.0. Note, there is no guarantee
547
	 * that this table will not be removed in subsequent versions. You should
548
	 * search for db versions from newest to oldest, only getting to this
549
	 * function when newer versions have not been matched.
550
	 * 
551
	 * @param dbMetaData
552
	 *            the meta data for this database.
553
	 * @returns boolean which is true if table is found, false otherwise
554
	 */
555
	private boolean is1_9_1(Connection connection) throws SQLException {
556
		return DBUtil.tableExists(connection, "db_version");
557
	}
558

    
559
	/**
560
	 * Checks to see if this is a 1.8.0 database schema by looking for the
561
	 * xml_nodes_idx4 index which was created for 1.8.0. Note, there is no
562
	 * guarantee that this index will not be removed in subsequent versions. You
563
	 * should search for db versions from newest to oldest, only getting to this
564
	 * function when newer versions have not been matched.
565
	 * 
566
	 * @param dbMetaData
567
	 *            the meta data for this database.
568
	 * @returns boolean which is true if index is found, false otherwise
569
	 */
570
	private boolean is1_8_0(Connection connection) throws SQLException, PropertyNotFoundException {
571
		String tableName = "xml_nodes";
572
		String dbType = PropertyService.getProperty("database.type");
573
			
574
		boolean isOracle = dbType.equals("oracle");		
575
		if(isOracle) {
576
			tableName = "XML_NODES";
577
		}
578
		return DBUtil.indexExists(connection, tableName, "xml_nodes_idx4");
579
	}
580

    
581
	/**
582
	 * Checks to see if this is a 1.7.0 database schema by looking for the
583
	 * xml_documents_idx2 index which was created for 1.7.0. Note, there is no
584
	 * guarantee that this index will not be removed in subsequent versions. You
585
	 * should search for db versions from newest to oldest, only getting to this
586
	 * function when newer versions have not been matched.
587
	 * 
588
	 * @param dbMetaData
589
	 *            the meta data for this database.
590
	 * @returns boolean which is true if index is found, false otherwise
591
	 */
592
	private boolean is1_7_0(Connection connection) throws SQLException, PropertyNotFoundException {
593
		String tableName = "xml_documents";
594
		String dbType = PropertyService.getProperty("database.type");
595
			
596
		boolean isOracle = dbType.equals("oracle");		
597
		if(isOracle) {
598
			tableName = "XML_DOCUMENTS";
599
		}
600
	
601
		return DBUtil.indexExists(connection, tableName, "xml_documents_idx2");
602
	}
603

    
604
	/**
605
	 * Checks to see if this is a 1.6.0 database schema by looking for the
606
	 * identifier table which was created for 1.6.0. Note, there is no guarantee
607
	 * that this table will not be removed in subsequent versions. You should
608
	 * search for db versions from newest to oldest, only getting to this
609
	 * function when newer versions have not been matched.
610
	 * 
611
	 * @param dbMetaData
612
	 *            the meta data for this database.
613
	 * @returns boolean which is true if table is found, false otherwise
614
	 */
615
	private boolean is1_6_0(Connection connection) throws SQLException {
616
		return DBUtil.tableExists(connection, "identifier");
617
	}
618

    
619
	/**
620
	 * Checks to see if this is a 1.5.0 database schema by looking for the
621
	 * xml_returnfield table which was created for 1.5.0. Note, there is no
622
	 * guarantee that this table will not be removed in subsequent versions. You
623
	 * should search for db versions from newest to oldest, only getting to this
624
	 * function when newer versions have not been matched.
625
	 * 
626
	 * @param dbMetaData
627
	 *            the meta data for this database.
628
	 * @returns boolean which is true if table is found, false otherwise
629
	 */
630
	private boolean is1_5_0(Connection connection) throws SQLException {
631
		return DBUtil.tableExists(connection, "xml_returnfield");
632
	}
633

    
634
	/**
635
	 * Checks to see if this is a 1.4.0 database schema by looking for the
636
	 * access_log table which was created for 1.4.0. Note, there is no guarantee
637
	 * that this table will not be removed in subsequent versions. You should
638
	 * search for db versions from newest to oldest, only getting to this
639
	 * function when newer versions have not been matched.
640
	 * 
641
	 * @param dbMetaData
642
	 *            the meta data for this database.
643
	 * @returns boolean which is true if table is found, false otherwise
644
	 */
645
	private boolean is1_4_0(Connection connection) throws SQLException {
646
		return DBUtil.tableExists(connection, "access_log");
647
	}
648

    
649
	/**
650
	 * Checks to see if this is a 1.3.0 database schema by looking for the
651
	 * xml_accesssubtree table which was created for 1.3.0. Note, there is no
652
	 * guarantee that this table will not be removed in subsequent versions. You
653
	 * should search for db versions from newest to oldest, only getting to this
654
	 * function when newer versions have not been matched.
655
	 * 
656
	 * @param dbMetaData
657
	 *            the meta data for this database.
658
	 * @returns boolean which is true if table is found, false otherwise
659
	 */
660
	private boolean is1_3_0(Connection connection) throws SQLException {
661
		return DBUtil.tableExists(connection, "xml_accesssubtree");
662
	}
663

    
664
	/**
665
	 * Checks to see if this is a 1.2.0 database schema by looking for the
666
	 * datareplicate column which was created on the xml_replication table for
667
	 * 1.2.0. Note, there is no guarantee that this column will not be removed
668
	 * in subsequent versions. You should search for db versions from newest to
669
	 * oldest, only getting to this function when newer versions have not been
670
	 * matched.
671
	 * 
672
	 * @param dbMetaData
673
	 *            the meta data for this database.
674
	 * @returns boolean which is true if column is found, false otherwise
675
	 */
676
	private boolean is1_2_0(Connection connection) throws SQLException {
677
		return DBUtil.columnExists(connection, "xml_replication",
678
				"datareplicate");
679
	}
680

    
681
	/**
682
	 * Creates a list of database update script names by looking at the database
683
	 * version and the metacat version and then getting any script that is
684
	 * inbetween the two (inclusive of metacat version).
685
	 * 
686
	 * @returns a Vector of Strings holding the names of scripts that need to be
687
	 *          run to get the database updated to this version of metacat
688
	 * 
689
	 */
690
	public Vector<String> getUpdateScripts() throws AdminException {
691
		Vector<String> updateScriptList = new Vector<String>();
692
		String sqlFileLocation = null;
693
		String databaseType = null;
694
		MetacatVersion metaCatVersion = null; 
695
		
696
		// get the location of sql scripts
697
		try {
698
			metaCatVersion = SystemUtil.getMetacatVersion();
699
			sqlFileLocation = SystemUtil.getSQLDir();
700
			databaseType = PropertyService.getProperty("database.type");
701
		} catch (PropertyNotFoundException pnfe) {
702
			throw new AdminException("Could not get property while trying " 
703
					+ "to retrieve database update scripts: " + pnfe.getMessage());
704
		}
705
		
706
		// Each type of db has it's own set of scripts.  For instance, Oracle
707
		// scripts end in -oracle.sql.  Postges end in -postgres.sql, etc
708
		String sqlSuffix = "-" + scriptSuffixMap.get("database.scriptsuffix." + databaseType);
709
		
710
		// if either of these is null, we don't want to do anything.  Just 
711
		// return an empty list.
712
		if (metaCatVersion == null || databaseVersion == null) {
713
			return updateScriptList;
714
		}
715

    
716
		// go through all the versions that the the software went through and 
717
		// figure out which ones need to be applied to the database	
718
		for (DBVersion nextVersion : versionSet) {
719
			Vector<String> versionUpdateScripts = nextVersion
720
					.getUpdateScripts();
721
			
722
			// if the database version is 0.0.0, it is new.
723
			// apply all scripts.
724
			if (databaseVersion.getVersionString().equals("0.0.0")
725
					&& nextVersion.getVersionString().equals("0.0.0")) {
726
				for (String versionUpdateScript : versionUpdateScripts) {
727
					updateScriptList.add(sqlFileLocation + FileUtil.getFS()
728
							+ versionUpdateScript + sqlSuffix);
729
				}
730
				return updateScriptList;
731
			}
732

    
733
			// add every update script that is > than the db version
734
			// but <= to the metacat version to the update list.
735
			if (nextVersion.compareTo(databaseVersion) > 0
736
					&& nextVersion.compareTo(metaCatVersion) <= 0
737
					&& nextVersion.getUpdateScripts() != null) {
738
				for (String versionUpdateScript : versionUpdateScripts) {
739
					updateScriptList.add(sqlFileLocation + FileUtil.getFS()
740
							+ versionUpdateScript + sqlSuffix);
741
				}
742
			}
743
		}
744

    
745
		// this should now hold all the script names that need to be run
746
		// to bring the database up to date with this version of metacat
747
		return updateScriptList;
748
	}
749

    
750
	/**
751
	 * Iterates through the list of scripts that need to be run to upgrade
752
	 * the database and calls runSQLFile on each.
753
	 */
754
	public void upgradeDatabase() throws AdminException {
755
		try {
756
			// get a list of the script names that need to be run
757
			Vector<String> updateScriptList = getUpdateScripts();
758

    
759
			// call runSQLFile on each
760
			for (String updateScript : updateScriptList) {
761
				runSQLFile(updateScript);
762
			}
763

    
764
			// update the db version to be the metacat version
765
			databaseVersion = new DBVersion(SystemUtil.getMetacatVersion().getVersionString());
766
		} catch (SQLException sqle) {
767
			throw new AdminException("SQL error when running upgrade scripts: "
768
					+ sqle.getMessage());
769
		} catch (PropertyNotFoundException pnfe) {
770
			throw new AdminException("SQL error when running upgrade scripts: "
771
					+ pnfe.getMessage());
772
		}catch (NumberFormatException nfe) {
773
			throw new AdminException("Bad version format numbering: "
774
					+ nfe.getMessage());
775
		}
776
	}
777

    
778
	/**
779
	 * Runs the commands in a sql script. Individual commands are loaded into a
780
	 * string vector and run one at a time.
781
	 * 
782
	 * @param sqlFileName
783
	 *            the name of the file holding the sql statements that need to
784
	 *            get run.
785
	 */
786
	public void runSQLFile(String sqlFileName) throws AdminException, SQLException {
787

    
788
		// if update file does not exist, do not do the update.
789
		if (FileUtil.getFileStatus(sqlFileName) < FileUtil.EXISTS_READABLE) {
790
			throw new AdminException("Could not read sql update file: "
791
					+ sqlFileName);
792
		}
793

    
794
		Connection connection = null;
795
		try {
796
			connection = DBUtil.getConnection(PropertyService
797
					.getProperty("database.connectionURI"), PropertyService
798
					.getProperty("database.user"), PropertyService
799
					.getProperty("database.password"));
800
			connection.setAutoCommit(false);
801

    
802
			// load the sql from the file into a vector of individual statements
803
			// and execute them.
804
			logMetacat.debug("processing File: " + sqlFileName);
805
			Vector<String> sqlCommands = loadSQLFromFile(sqlFileName);
806
			for (String sqlStatement : sqlCommands) {
807
				Statement statement = connection.createStatement();
808
				logMetacat.debug("executing sql: " + sqlStatement);
809
				try {
810
					statement.execute(sqlStatement);
811
				} catch (SQLException sqle) {
812
					// Oracle complains if we try and drop a sequence (ORA-02289) or a 
813
					// trigger (ORA-04098/ORA-04080) or a table/view (ORA-00942) or and index (ORA-01418) 
814
					// that does not exist.  We don't care if this happens.
815
					if (sqlStatement.toUpperCase().startsWith("DROP") && 
816
							(sqle.getMessage().contains("ORA-02289") ||
817
							 sqle.getMessage().contains("ORA-04098") ||
818
							 sqle.getMessage().contains("ORA-04080") ||
819
							 sqle.getMessage().contains("ORA-00942"))) {
820
						logMetacat.warn("did not process sql drop statement: " + sqle.getMessage());
821
					} else {
822
						throw sqle;
823
					}
824
				}
825
			}
826
			connection.commit();
827
			
828
		} catch (IOException ioe) {
829
			throw new AdminException("Could not read SQL file" 
830
					+ ioe.getMessage());
831
		} catch (PropertyNotFoundException pnfe) {
832
			throw new AdminException("Could not find property to run SQL file" 
833
					+ pnfe.getMessage());
834
		} catch (SQLException sqle) {
835
			if (connection != null) {
836
				connection.rollback();
837
			}
838
			throw sqle;
839
		} finally {
840
			if (connection != null) {
841
				connection.close();
842
			}
843
		}
844
	}
845

    
846
	/**
847
	 * Very basic utility to read sql from a file and return a vector of the
848
	 * individual sql statements. This ignores any line that starts with /* or *.
849
	 * It strips anything following --. Sql is parsed by looking for lines that
850
	 * start with one of the following identifiers: INSERT, UPDATE, ALTER,
851
	 * CREATE, DROP, BEGIN and COMMIT. It then assumes that everything until the
852
	 * line that ends with ; is part of the sql, excluding comments.
853
	 * 
854
	 * @param sqlFileName
855
	 *            the name of the file to read.
856
	 * @return a vector holding the individual sql statements.
857
	 */
858
	public Vector<String> loadSQLFromFile(String sqlFileName)
859
			throws IOException {
860

    
861
		// this will end up holding individual sql statements
862
		Vector<String> sqlCommands = new Vector<String>();
863

    
864
		FileInputStream fin = null;
865
		try {
866
			fin = new FileInputStream(sqlFileName);
867

    
868
			BufferedReader reader = new BufferedReader(new InputStreamReader(
869
					fin));
870

    
871
			// Read in file
872
			String fileLine;
873
			while ((fileLine = reader.readLine()) != null) {
874
				String endChar = ";";
875
				String trimmedLine = fileLine.trim();
876

    
877
				// get the first word on the line
878
				String firstWord = trimmedLine;
879
				if (trimmedLine.indexOf(' ') > 0) {
880
					firstWord = trimmedLine.substring(0, trimmedLine
881
							.indexOf(' '));
882
				}
883
				if (firstWord.endsWith(endChar)) {
884
					firstWord = firstWord.substring(0, firstWord.indexOf(endChar));
885
				}
886

    
887
				// if the first word is a known sql command, start creating a
888
				// sql statement.
889
				if (sqlCommandSet.contains(firstWord.toUpperCase())) {
890
					String sqlStatement = "";
891

    
892
					// keep reading lines until we find one that is not a
893
					// comment and ends with endChar
894
					do {
895
						String trimmedInnerLine = fileLine.trim();
896
						
897
						// if there is a BEGIN or DECLARE statement, we are now in plsql and we're 
898
						// using the '/' character as our sql end delimiter.
899
						if (trimmedInnerLine.toUpperCase().equals("BEGIN")  ||
900
								trimmedInnerLine.toUpperCase().startsWith("BEGIN ")  ||
901
								trimmedInnerLine.toUpperCase().equals("DECLARE")  ||
902
								trimmedInnerLine.toUpperCase().startsWith("DECLARE ")) {
903
							endChar = "/";
904
						}
905
						
906
						// ignore comments and empty lines
907
						if (trimmedInnerLine.matches("^$")
908
								|| trimmedInnerLine.matches("^\\*.*")
909
								|| trimmedInnerLine.matches("/\\*.*")) {
910
							continue;
911
						}
912

    
913
						// get rid of any "--" comments at the end of the line
914
						if (trimmedInnerLine.indexOf("--") >= 0) {
915
							trimmedInnerLine = trimmedInnerLine.substring(0,
916
									trimmedInnerLine.indexOf("--")).trim();
917
						}
918
						if (sqlStatement.length() > 0) {
919
							sqlStatement += " ";
920
						}
921
						sqlStatement += trimmedInnerLine;
922
						if (trimmedInnerLine.endsWith(endChar)) {
923
							sqlStatement = 
924
								sqlStatement.substring(0, sqlStatement.length() - 1);
925
							sqlCommands.add(sqlStatement);
926
							break;
927
						}
928
					} while ((fileLine = reader.readLine()) != null);
929
				}
930
			}
931
		} finally {
932
			// Close our input stream
933
			fin.close();
934
		}
935

    
936
		return sqlCommands;
937
	}
938

    
939
	/**
940
	 * Validate the most important configuration options submitted by the user.
941
	 * 
942
	 * @return a vector holding error message for any fields that fail
943
	 *         validation.
944
	 */
945
	protected Vector<String> validateOptions(HttpServletRequest request) {
946
		Vector<String> errorVector = new Vector<String>();
947

    
948
		// TODO MCD validate options.
949

    
950
		return errorVector;
951
	}
952
}
(4-4/10)