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-26 17:27:47 -0700 (Fri, 26 Sep 2008) $'
10
 * '$Revision: 4400 $'
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

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

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

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

    
209
				upgradeDatabase();
210

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

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

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

    
241

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

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

    
260
		return TABLES_DO_NOT_EXIST;
261
	}
262

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

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

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

    
288
		return databaseVersion;
289
	}
290

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

    
313
			databaseVersion = getRegisteredDBVersion();
314
			if (databaseVersion != null) {
315
				return databaseVersion;
316
			}
317

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

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

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

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

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

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

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

    
413
			String dbVersionString = null;
414

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

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

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

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

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

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

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

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

    
521
		return null;
522
	}
523

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
830
		FileInputStream fin = null;
831
		try {
832
			fin = new FileInputStream(sqlFileName);
833

    
834
			BufferedReader reader = new BufferedReader(new InputStreamReader(
835
					fin));
836

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

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

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

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

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

    
902
		return sqlCommands;
903
	}
904

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

    
914
		// TODO MCD validate options.
915

    
916
		return errorVector;
917
	}
918
}
(3-3/10)