Subversion Repositories XServices

Rev

Rev 198 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 198 Rev 199
1
/*
1
/*
2
 *   Copyright 2011 Brian Rosenberger (Brutex Network)
2
 *   Copyright 2011 Brian Rosenberger (Brutex Network)
3
 *
3
 *
4
 *   Licensed under the Apache License, Version 2.0 (the "License");
4
 *   Licensed under the Apache License, Version 2.0 (the "License");
5
 *   you may not use this file except in compliance with the License.
5
 *   you may not use this file except in compliance with the License.
6
 *   You may obtain a copy of the License at
6
 *   You may obtain a copy of the License at
7
 *
7
 *
8
 *       http://www.apache.org/licenses/LICENSE-2.0
8
 *       http://www.apache.org/licenses/LICENSE-2.0
9
 *
9
 *
10
 *   Unless required by applicable law or agreed to in writing, software
10
 *   Unless required by applicable law or agreed to in writing, software
11
 *   distributed under the License is distributed on an "AS IS" BASIS,
11
 *   distributed under the License is distributed on an "AS IS" BASIS,
12
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *   See the License for the specific language governing permissions and
13
 *   See the License for the specific language governing permissions and
14
 *   limitations under the License.
14
 *   limitations under the License.
15
 */
15
 */
16
 
16
 
17
package net.brutex.xservices.util;
17
package net.brutex.xservices.util;
18
 
18
 
19
import java.io.BufferedReader;
19
import java.io.BufferedReader;
20
import java.io.File;
20
import java.io.File;
21
import java.io.FileNotFoundException;
21
import java.io.FileNotFoundException;
22
import java.io.FileReader;
22
import java.io.FileReader;
23
import java.io.IOException;
23
import java.io.IOException;
24
import java.sql.Connection;
24
import java.sql.Connection;
25
import java.sql.DatabaseMetaData;
25
import java.sql.DatabaseMetaData;
26
import java.sql.DriverManager;
26
import java.sql.DriverManager;
27
import java.sql.ResultSet;
27
import java.sql.ResultSet;
28
import java.sql.SQLException;
28
import java.sql.SQLException;
29
import java.sql.Statement;
29
import java.sql.Statement;
30
import java.util.ArrayList;
30
import java.util.ArrayList;
31
import java.util.List;
31
import java.util.List;
-
 
32
 
32
 
33
 
33
import org.apache.logging.log4j.Level;
-
 
34
import org.apache.logging.log4j.LogManager;
-
 
35
import org.apache.logging.log4j.Logger;
34
import lombok.extern.slf4j.Slf4j;
36
import org.quartz.utils.ConnectionProvider;
35
import org.quartz.utils.ConnectionProvider;
37
 
36
 
38
/**
37
/**
39
 * @author Brian Rosenberger
38
 * @author Brian Rosenberger
40
 * 
39
 * 
41
 */
40
 */
-
 
41
@Slf4j
42
public class BrutexQuartzConnectionProvider implements ConnectionProvider {
42
public class BrutexQuartzConnectionProvider implements ConnectionProvider {
43
	
43
	
44
	private Connection conn = null;
44
	private Connection conn = null;
45
	private final Logger logger = LogManager.getLogger();
-
 
46
	
45
 
47
 
46
 
48
	public Connection getConnection() throws SQLException {
47
	public Connection getConnection() throws SQLException {
49
		if( conn!= null) { // Todo: && conn.conn.isValid(5)) {) {
48
		if( conn!= null) { // Todo: && conn.conn.isValid(5)) {) {
50
			logger.debug("Checking tables on pre-exisiting database connection.");
49
			log.debug("Checking tables on pre-exisiting database connection.");
51
			checkTables();
50
			checkTables();
52
			return conn;
51
			return conn;
53
		}
52
		}
54
		try {
53
		try {
55
			// Class.forName("org.hsqldb.jdbc.JDBCDriver" );
54
			// Class.forName("org.hsqldb.jdbc.JDBCDriver" );
56
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
55
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
57
		} catch (Exception e) {
56
		} catch (Exception e) {
58
			logger.fatal("Failed to load Derby JDBC driver.");
57
			log.error("Failed to load Derby JDBC driver.");
59
			e.printStackTrace();
58
			e.printStackTrace();
60
			return null;
59
			return null;
61
		}
60
		}
62
 
61
 
63
		if(isConnected(false)) {
62
		if(isConnected(false)) {
64
			checkTables();
63
			checkTables();
65
		} else {
64
		} else {
66
			return null;
65
			return null;
67
		}
66
		}
68
		
67
		
69
		return conn;
68
		return conn;
70
	}
69
	}
71
 
70
 
72
	public void shutdown() throws SQLException {
71
	public void shutdown() throws SQLException {
73
		try {
72
		try {
74
			// Class.forName("org.hsqldb.jdbc.JDBCDriver" );
73
			// Class.forName("org.hsqldb.jdbc.JDBCDriver" );
75
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
74
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
76
		} catch (Exception e) {
75
		} catch (Exception e) {
77
			System.err.println("ERROR: failed to load Derby JDBC driver.");
76
			System.err.println("ERROR: failed to load Derby JDBC driver.");
78
			e.printStackTrace();
77
			e.printStackTrace();
79
			return;
78
			return;
80
		}
79
		}
81
		String t = this.getClass().getClassLoader().getResource("/").toString()
80
		String t = this.getClass().getClassLoader().getResource("/").toString()
82
				.substring(6);
81
				.substring(6);
83
		t += "../data/db";
82
		t += "../data/db";
84
		System.out.println("Shut down embedded database now.");
83
		System.out.println("Shut down embedded database now.");
85
		Connection c = DriverManager.getConnection("jdbc:derby:" + t
84
		Connection c = DriverManager.getConnection("jdbc:derby:" + t
86
				+ ";shutdown=true;");
85
				+ ";shutdown=true;");
87
 
86
 
88
	}
87
	}
89
 
88
 
90
	@Override
89
	@Override
91
	public void initialize() throws SQLException {
90
	public void initialize() throws SQLException {
92
 
91
 
93
	}
92
	}
94
 
93
 
95
	private synchronized void recursiveDelete(File dbDir) {
94
	private synchronized void recursiveDelete(File dbDir) {
96
		File[] files = dbDir.listFiles();
95
		File[] files = dbDir.listFiles();
97
		for (int i = 0; i < files.length; i++) {
96
		for (int i = 0; i < files.length; i++) {
98
			if (files[i].isFile()) {
97
			if (files[i].isFile()) {
99
				files[i].delete();
98
				files[i].delete();
100
			} else {
99
			} else {
101
				recursiveDelete(files[i]);
100
				recursiveDelete(files[i]);
102
				files[i].delete();
101
				files[i].delete();
103
			}
102
			}
104
		}
103
		}
105
		dbDir.delete();
104
		dbDir.delete();
106
	}
105
	}
107
	
106
	
108
	private synchronized void checkTables() throws SQLException {
107
	private synchronized void checkTables() throws SQLException {
109
		logger.debug("Checking QUARTZ database schema.");
108
		log.debug("Checking QUARTZ database schema.");
110
		if(!isConnected(false)) {
109
		if(!isConnected(false)) {
111
			logger.error("Failed to validate QUARTZ database schema.");
110
			log.error("Failed to validate QUARTZ database schema.");
112
			return;
111
			return;
113
		}
112
		}
114
		List<String> ddl_list = new ArrayList<String>(11);
113
		List<String> ddl_list = new ArrayList<String>(11);
115
		ddl_list.add("QRTZ_JOB_DETAILS");
114
		ddl_list.add("QRTZ_JOB_DETAILS");
116
		ddl_list.add("QRTZ_TRIGGERS");
115
		ddl_list.add("QRTZ_TRIGGERS");
117
		ddl_list.add("QRTZ_SIMPLE_TRIGGERS");
116
		ddl_list.add("QRTZ_SIMPLE_TRIGGERS");
118
		ddl_list.add("QRTZ_CRON_TRIGGERS");
117
		ddl_list.add("QRTZ_CRON_TRIGGERS");
119
		ddl_list.add("QRTZ_SIMPROP_TRIGGERS");
118
		ddl_list.add("QRTZ_SIMPROP_TRIGGERS");
120
		ddl_list.add("QRTZ_BLOB_TRIGGERS");
119
		ddl_list.add("QRTZ_BLOB_TRIGGERS");
121
		ddl_list.add("QRTZ_CALENDARS");
120
		ddl_list.add("QRTZ_CALENDARS");
122
		ddl_list.add("QRTZ_PAUSED_TRIGGER_GRPS");
121
		ddl_list.add("QRTZ_PAUSED_TRIGGER_GRPS");
123
		ddl_list.add("QRTZ_FIRED_TRIGGERS");
122
		ddl_list.add("QRTZ_FIRED_TRIGGERS");
124
		ddl_list.add("QRTZ_SCHEDULER_STATE");
123
		ddl_list.add("QRTZ_SCHEDULER_STATE");
125
		ddl_list.add("QRTZ_LOCKS");
124
		ddl_list.add("QRTZ_LOCKS");
126
		
125
		
127
		String ddl = this.getClass().getClassLoader().getResource("/").toString()
126
		String ddl = this.getClass().getClassLoader().getResource("/").toString()
128
		.substring(6)+ "../data/";
127
		.substring(6)+ "../data/";
129
 
128
 
130
		DatabaseMetaData dmd = conn.getMetaData();
129
		DatabaseMetaData dmd = conn.getMetaData();
131
		for (String tbl : ddl_list) {
130
		for (String tbl : ddl_list) {
132
			ResultSet rs = dmd.getTables(null, "APP", tbl, null);
131
			ResultSet rs = dmd.getTables(null, "APP", tbl, null);
133
			if (!rs.next()) {
132
			if (!rs.next()) {
134
				logger.log(Level.INFO, "Adding DDL for table "+ tbl);
133
				log.debug("Adding DDL for table {}.", tbl);
135
				Statement st = conn.createStatement();
134
				Statement st = conn.createStatement();
136
				File ddlFile = new File(ddl + tbl + ".ddl");
135
				File ddlFile = new File(ddl + tbl + ".ddl");
137
				String create = "";
136
				String create = "";
138
				try {
137
				try {
139
						BufferedReader r = new BufferedReader(new FileReader(ddlFile));
138
						BufferedReader r = new BufferedReader(new FileReader(ddlFile));
140
						while (r.ready()) {
139
						while (r.ready()) {
141
							create += r.readLine() + "\n";
140
							create += r.readLine() + "\n";
142
						}
141
						}
143
						create.trim();
142
						create.trim();
144
						if( st.execute(create)) {
143
						if( st.execute(create)) {
145
							logger.log(Level.INFO, "Table " + tbl + " created.");
144
							log.debug("Table {} created.", tbl);
146
						} 
145
						} 
147
					} catch (FileNotFoundException ex) {
-
 
148
						ex.printStackTrace();
-
 
149
					} catch (IOException ex) {
146
					} catch (IOException ex) {
150
						ex.printStackTrace();
147
						ex.printStackTrace();
151
					} catch (SQLException ex) {
148
					} catch (SQLException ex) {
152
						logger.log(Level.ERROR, "Error executing statement "+ create );
149
						log.error("Error executing statement {}", create, ex );
153
						System.out.println(ex.getMessage());
150
						System.out.println(ex.getMessage());
154
					}
151
					}
155
				} else {
152
				} else {
156
					logger.trace("Table "+tbl+" exists.");
153
					log.trace("Table {} exists.", tbl);
157
				}
154
				}
158
			}
155
			}
159
		}
156
		}
160
	
157
	
161
	private synchronized boolean isConnected(boolean fail) throws SQLException {
158
	private synchronized boolean isConnected(boolean fail) throws SQLException {
162
		if(conn!=null ) { // Todo: && conn.conn.isValid(5)) {) {
159
		if(conn!=null ) { // Todo: && conn.conn.isValid(5)) {) {
163
			return true;
160
			return true;
164
		} else {
161
		} else {
165
			String t = this.getClass().getClassLoader().getResource("/").toString().substring(6); // WEB-INF/classes
162
			String t = this.getClass().getClassLoader().getResource("/").toString().substring(6); // WEB-INF/classes
166
			t += "../data/db";
163
			t += "../data/db";
167
			logger.debug("Database directory is set to '" + t + "'");
164
			log.debug("Database directory is set to '{}'", t);
168
			try {
165
			try {
169
				this.conn = DriverManager.getConnection("jdbc:derby:" + t + ";create=true;");
166
				this.conn = DriverManager.getConnection("jdbc:derby:" + t + ";create=true;");
170
			} catch (SQLException ex) {
167
			} catch (SQLException ex) {
171
				logger.error(ex.getMessage(), ex);
168
				log.error(ex.getMessage(), ex);
172
				if(!fail) {
169
				if(!fail) {
173
					logger.warn("Deleting database directory.");
170
					log.warn("Deleting database directory.");
174
					recursiveDelete(new File(t));
171
					recursiveDelete(new File(t));
175
					logger.warn("Retrying to connect to database.");
172
					log.warn("Retrying to connect to database.");
176
					return isConnected(true);
173
					return isConnected(true);
177
				} else {
174
				} else {
178
					return false;
175
					return false;
179
				}
176
				}
180
			}
177
			}
181
		}
178
		}
182
		return false;
179
		return false;
183
	}
180
	}
184
 
-
 
185
}
181
}