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: 2008-09-29 11:08:25 -0700 (Mon, 29 Sep 2008) $'
10
 * '$Revision: 4406 $'
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.DBConnection;
54
import edu.ucsb.nceas.metacat.DBConnectionPool;
55
import edu.ucsb.nceas.metacat.DBVersion;
56
import edu.ucsb.nceas.metacat.MetaCatVersion;
57
import edu.ucsb.nceas.metacat.service.PropertyService;
58
import edu.ucsb.nceas.metacat.util.DatabaseUtil;
59
import edu.ucsb.nceas.metacat.util.RequestUtil;
60
import edu.ucsb.nceas.metacat.util.SystemUtil;
61
import edu.ucsb.nceas.metacat.util.UtilException;
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");
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");
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 (UtilException ue) {
280
			throw new AdminException("Could not determine the database version: " + ue.getMessage());
281
		}
282
		if (databaseVersion == null) {
283
			databaseVersion = discoverDBVersion();
284
		}
285

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

    
290
		return databaseVersion;
291
	}
292

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

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

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

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

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

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

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

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

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

    
415
			String dbVersionString = null;
416

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

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

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

    
463
			// check out DBConnection
464
			conn = DBConnectionPool
465
					.getDBConnection("DBAdmin.updateDBVersion()");
466
			serialNumber = conn.getCheckOutSerialNumber();
467
			conn.setAutoCommit(false);
468

    
469
			pstmt = conn.prepareStatement("UPDATE db_version SET status = ?");
470
			pstmt.setInt(1, VERSION_INACTIVE);
471
			pstmt.execute();
472
			pstmt.close();
473

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

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

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

    
523
		return null;
524
	}
525

    
526
	/**
527
	 * Checks to see if this is a 1.9.0 database schema by looking for the
528
	 * db_version table which was created for 1.9.0. Note, there is no guarantee
529
	 * that this table will not be removed in subsequent versions. You should
530
	 * search for db versions from newest to oldest, only getting to this
531
	 * function when newer versions have not been matched.
532
	 * 
533
	 * @param dbMetaData
534
	 *            the meta data for this database.
535
	 * @returns boolean which is true if table is found, false otherwise
536
	 */
537
	private boolean is1_9_0(Connection connection) throws SQLException {
538
		return DBUtil.tableExists(connection, "db_version");
539
	}
540

    
541
	/**
542
	 * Checks to see if this is a 1.8.0 database schema by looking for the
543
	 * xml_nodes_idx4 index which was created for 1.8.0. Note, there is no
544
	 * guarantee that this index will not be removed in subsequent versions. You
545
	 * should search for db versions from newest to oldest, only getting to this
546
	 * function when newer versions have not been matched.
547
	 * 
548
	 * @param dbMetaData
549
	 *            the meta data for this database.
550
	 * @returns boolean which is true if index is found, false otherwise
551
	 */
552
	private boolean is1_8_0(Connection connection) throws SQLException {
553
		return DBUtil.indexExists(connection, "xml_nodes", "xml_nodes_idx4");
554
	}
555

    
556
	/**
557
	 * Checks to see if this is a 1.7.0 database schema by looking for the
558
	 * xml_documents_idx2 index which was created for 1.7.0. Note, there is no
559
	 * guarantee that this index will not be removed in subsequent versions. You
560
	 * should search for db versions from newest to oldest, only getting to this
561
	 * function when newer versions have not been matched.
562
	 * 
563
	 * @param dbMetaData
564
	 *            the meta data for this database.
565
	 * @returns boolean which is true if index is found, false otherwise
566
	 */
567
	private boolean is1_7_0(Connection connection) throws SQLException {
568
		return DBUtil.indexExists(connection, "xml_documents",
569
				"xml_documents_idx2");
570
	}
571

    
572
	/**
573
	 * Checks to see if this is a 1.6.0 database schema by looking for the
574
	 * identifier table which was created for 1.6.0. Note, there is no guarantee
575
	 * that this table will not be removed in subsequent versions. You should
576
	 * search for db versions from newest to oldest, only getting to this
577
	 * function when newer versions have not been matched.
578
	 * 
579
	 * @param dbMetaData
580
	 *            the meta data for this database.
581
	 * @returns boolean which is true if table is found, false otherwise
582
	 */
583
	private boolean is1_6_0(Connection connection) throws SQLException {
584
		return DBUtil.tableExists(connection, "identifier");
585
	}
586

    
587
	/**
588
	 * Checks to see if this is a 1.5.0 database schema by looking for the
589
	 * xml_returnfield table which was created for 1.5.0. Note, there is no
590
	 * guarantee that this table will not be removed in subsequent versions. You
591
	 * should search for db versions from newest to oldest, only getting to this
592
	 * function when newer versions have not been matched.
593
	 * 
594
	 * @param dbMetaData
595
	 *            the meta data for this database.
596
	 * @returns boolean which is true if table is found, false otherwise
597
	 */
598
	private boolean is1_5_0(Connection connection) throws SQLException {
599
		return DBUtil.tableExists(connection, "xml_returnfield");
600
	}
601

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

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

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

    
649
	/**
650
	 * Creates a list of database update script names by looking at the database
651
	 * version and the metacat version and then getting any script that is
652
	 * inbetween the two (inclusive of metacat version).
653
	 * 
654
	 * @returns a Vector of Strings holding the names of scripts that need to be
655
	 *          run to get the database updated to this version of metacat
656
	 * 
657
	 */
658
	public Vector<String> getUpdateScripts() throws AdminException {
659
		Vector<String> updateScriptList = new Vector<String>();
660
		String sqlFileLocation = null;
661
		String databaseType = null;
662
		MetaCatVersion metaCatVersion = null; 
663
		
664
		// get the location of sql scripts
665
		try {
666
			metaCatVersion = SystemUtil.getMetacatVersion();
667
			sqlFileLocation = SystemUtil.getSQLDir();
668
			databaseType = PropertyService.getProperty("database.type");
669
		} catch (PropertyNotFoundException pnfe) {
670
			throw new AdminException("Could not get property while trying " 
671
					+ "to retrieve database update scripts: " + pnfe.getMessage());
672
		}
673
		
674
		// Each type of db has it's own set of scripts.  For instance, Oracle
675
		// scripts end in -oracle.sql.  Postges end in -postgres.sql, etc
676
		String sqlSuffix = "-" + scriptSuffixMap.get("database.scriptsuffix." + databaseType);
677
		
678
		// if either of these is null, we don't want to do anything.  Just 
679
		// return an empty list.
680
		if (metaCatVersion == null || databaseVersion == null) {
681
			return updateScriptList;
682
		}
683

    
684
		// go through all the versions that the the software went through and 
685
		// figure out which ones need to be applied to the database	
686
		for (DBVersion nextVersion : versionSet) {
687
			Vector<String> versionUpdateScripts = nextVersion
688
					.getUpdateScripts();
689
			
690
			// if the database version is 0.0.0, it is new.
691
			// apply all scripts.
692
			if (databaseVersion.getVersionString().equals("0.0.0")
693
					&& nextVersion.getVersionString().equals("0.0.0")) {
694
				for (String versionUpdateScript : versionUpdateScripts) {
695
					updateScriptList.add(sqlFileLocation + FileUtil.getFS()
696
							+ versionUpdateScript + sqlSuffix);
697
				}
698
				return updateScriptList;
699
			}
700

    
701
			// add every update script that is > than the db version
702
			// but <= to the metacat version to the update list.
703
			if (nextVersion.compareTo(databaseVersion) > 0
704
					&& nextVersion.compareTo(metaCatVersion) <= 0
705
					&& nextVersion.getUpdateScripts() != null) {
706
				for (String versionUpdateScript : versionUpdateScripts) {
707
					updateScriptList.add(sqlFileLocation + FileUtil.getFS()
708
							+ versionUpdateScript + sqlSuffix);
709
				}
710
			}
711
		}
712

    
713
		// this should now hold all the script names that need to be run
714
		// to bring the database up to date with this version of metacat
715
		return updateScriptList;
716
	}
717

    
718
	/**
719
	 * Iterates through the list of scripts that need to be run to upgrade
720
	 * the database and calls runSQLFile on each.
721
	 */
722
	public void upgradeDatabase() throws AdminException {
723
		try {
724
			// get a list of the script names that need to be run
725
			Vector<String> updateScriptList = getUpdateScripts();
726

    
727
			// call runSQLFile on each
728
			for (String updateScript : updateScriptList) {
729
				runSQLFile(updateScript);
730
			}
731

    
732
			// update the db version to be the metacat version
733
			databaseVersion = new DBVersion(SystemUtil.getMetacatVersion().getVersionString());
734
		} catch (SQLException sqle) {
735
			throw new AdminException("SQL error when running upgrade scripts: "
736
					+ sqle.getMessage());
737
		} catch (PropertyNotFoundException pnfe) {
738
			throw new AdminException("SQL error when running upgrade scripts: "
739
					+ pnfe.getMessage());
740
		}catch (NumberFormatException nfe) {
741
			throw new AdminException("Bad version format numbering: "
742
					+ nfe.getMessage());
743
		}
744
	}
745

    
746
	/**
747
	 * Runs the commands in a sql script. Individual commands are loaded into a
748
	 * string vector and run one at a time.
749
	 * 
750
	 * @param sqlFileName
751
	 *            the name of the file holding the sql statements that need to
752
	 *            get run.
753
	 */
754
	public void runSQLFile(String sqlFileName) throws AdminException, SQLException {
755

    
756
		// if update file does not exist, do not do the update.
757
		if (FileUtil.getFileStatus(sqlFileName) < FileUtil.EXISTS_READABLE) {
758
			throw new AdminException("Could not read sql update file: "
759
					+ sqlFileName);
760
		}
761

    
762
		Connection connection = null;
763
		try {
764
			connection = DBUtil.getConnection(PropertyService
765
					.getProperty("database.connectionURI"), PropertyService
766
					.getProperty("database.user"), PropertyService
767
					.getProperty("database.password"));
768
			connection.setAutoCommit(false);
769

    
770
			// load the sql from the file into a vector of individual statements
771
			// and execute them.
772
			logMetacat.debug("processing File: " + sqlFileName);
773
			Vector<String> sqlCommands = loadSQLFromFile(sqlFileName);
774
			for (String sqlStatement : sqlCommands) {
775
				Statement statement = connection.createStatement();
776
				logMetacat.debug("executing sql: " + sqlStatement);
777
				try {
778
					statement.execute(sqlStatement);
779
				} catch (SQLException sqle) {
780
					// Oracle complains if we try and drop a sequence (ORA-02289) or a 
781
					// trigger (ORA-04098/ORA-04080) or a table/view (ORA-00942) or and index (ORA-01418) 
782
					// that does not exist.  We don't care if this happens.
783
					if (sqlStatement.toUpperCase().startsWith("DROP") && 
784
							(sqle.getMessage().contains("ORA-02289") ||
785
							 sqle.getMessage().contains("ORA-04098") ||
786
							 sqle.getMessage().contains("ORA-04080") ||
787
							 sqle.getMessage().contains("ORA-00942"))) {
788
						logMetacat.warn("did not process sql drop statement: " + sqle.getMessage());
789
					} else {
790
						throw sqle;
791
					}
792
				}
793
			}
794
			connection.commit();
795
			
796
		} catch (IOException ioe) {
797
			throw new AdminException("Could not read SQL file" 
798
					+ ioe.getMessage());
799
		} catch (PropertyNotFoundException pnfe) {
800
			throw new AdminException("Could not find property to run SQL file" 
801
					+ pnfe.getMessage());
802
		} catch (SQLException sqle) {
803
			if (connection != null) {
804
				connection.rollback();
805
			}
806
			throw sqle;
807
		} finally {
808
			if (connection != null) {
809
				connection.close();
810
			}
811
		}
812
	}
813

    
814
	/**
815
	 * Very basic utility to read sql from a file and return a vector of the
816
	 * individual sql statements. This ignores any line that starts with /* or *.
817
	 * It strips anything following --. Sql is parsed by looking for lines that
818
	 * start with one of the following identifiers: INSERT, UPDATE, ALTER,
819
	 * CREATE, DROP, BEGIN and COMMIT. It then assumes that everything until the
820
	 * line that ends with ; is part of the sql, excluding comments.
821
	 * 
822
	 * @param sqlFileName
823
	 *            the name of the file to read.
824
	 * @return a vector holding the individual sql statements.
825
	 */
826
	public Vector<String> loadSQLFromFile(String sqlFileName)
827
			throws IOException {
828

    
829
		// this will end up holding individual sql statements
830
		Vector<String> sqlCommands = new Vector<String>();
831

    
832
		FileInputStream fin = null;
833
		try {
834
			fin = new FileInputStream(sqlFileName);
835

    
836
			BufferedReader reader = new BufferedReader(new InputStreamReader(
837
					fin));
838

    
839
			// Read in file
840
			String fileLine;
841
			while ((fileLine = reader.readLine()) != null) {
842
				String endChar = ";";
843
				String trimmedLine = fileLine.trim();
844

    
845
				// get the first word on the line
846
				String firstWord = trimmedLine;
847
				if (trimmedLine.indexOf(' ') > 0) {
848
					firstWord = trimmedLine.substring(0, trimmedLine
849
							.indexOf(' '));
850
				}
851
				if (firstWord.endsWith(endChar)) {
852
					firstWord = firstWord.substring(0, firstWord.indexOf(endChar));
853
				}
854

    
855
				// if the first word is a known sql command, start creating a
856
				// sql statement.
857
				if (sqlCommandSet.contains(firstWord.toUpperCase())) {
858
					String sqlStatement = "";
859

    
860
					// keep reading lines until we find one that is not a
861
					// comment and ends with endChar
862
					do {
863
						String trimmedInnerLine = fileLine.trim();
864
						
865
						// if there is a BEGIN or DECLARE statement, we are now in plsql and we're 
866
						// using the '/' character as our sql end delimiter.
867
						if (trimmedInnerLine.toUpperCase().equals("BEGIN")  ||
868
								trimmedInnerLine.toUpperCase().startsWith("BEGIN ")  ||
869
								trimmedInnerLine.toUpperCase().equals("DECLARE")  ||
870
								trimmedInnerLine.toUpperCase().startsWith("DECLARE ")) {
871
							endChar = "/";
872
						}
873
						
874
						// ignore comments and empty lines
875
						if (trimmedInnerLine.matches("^$")
876
								|| trimmedInnerLine.matches("^\\*.*")
877
								|| trimmedInnerLine.matches("/\\*.*")) {
878
							continue;
879
						}
880

    
881
						// get rid of any "--" comments at the end of the line
882
						if (trimmedInnerLine.indexOf("--") >= 0) {
883
							trimmedInnerLine = trimmedInnerLine.substring(0,
884
									trimmedInnerLine.indexOf("--")).trim();
885
						}
886
						if (sqlStatement.length() > 0) {
887
							sqlStatement += " ";
888
						}
889
						sqlStatement += trimmedInnerLine;
890
						if (trimmedInnerLine.endsWith(endChar)) {
891
							sqlStatement = 
892
								sqlStatement.substring(0, sqlStatement.length() - 1);
893
							sqlCommands.add(sqlStatement);
894
							break;
895
						}
896
					} while ((fileLine = reader.readLine()) != null);
897
				}
898
			}
899
		} finally {
900
			// Close our input stream
901
			fin.close();
902
		}
903

    
904
		return sqlCommands;
905
	}
906

    
907
	/**
908
	 * Validate the most important configuration options submitted by the user.
909
	 * 
910
	 * @return a vector holding error message for any fields that fail
911
	 *         validation.
912
	 */
913
	protected Vector<String> validateOptions(HttpServletRequest request) {
914
		Vector<String> errorVector = new Vector<String>();
915

    
916
		// TODO MCD validate options.
917

    
918
		return errorVector;
919
	}
920
}
(3-3/10)