Subversion Repositories XServices

Rev

Rev 198 | Details | Compare with Previous | Last modification | View Log | RSS feed

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