aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/iciql/util/JdbcUtils.java
blob: edf21e84031912f73821d2c600e67299d0d15431 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
 * Copyright 2004-2011 H2 Group.
 * Copyright 2011 James Moger.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iciql.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.naming.Context;
import javax.sql.DataSource;
import javax.sql.XAConnection;

/**
 * This is a utility class with JDBC helper functions.
 */
public class JdbcUtils {

	private static final String[] DRIVERS = { "h2:", "org.h2.Driver", "Cache:",
			"com.intersys.jdbc.CacheDriver", "daffodilDB://", "in.co.daffodil.db.rmi.RmiDaffodilDBDriver",
			"daffodil", "in.co.daffodil.db.jdbc.DaffodilDBDriver", "db2:", "COM.ibm.db2.jdbc.net.DB2Driver",
			"derby:net:", "org.apache.derby.jdbc.ClientDriver", "derby://",
			"org.apache.derby.jdbc.ClientDriver", "derby:", "org.apache.derby.jdbc.EmbeddedDriver",
			"FrontBase:", "com.frontbase.jdbc.FBJDriver", "firebirdsql:", "org.firebirdsql.jdbc.FBDriver",
			"hsqldb:", "org.hsqldb.jdbcDriver", "informix-sqli:", "com.informix.jdbc.IfxDriver", "jtds:",
			"net.sourceforge.jtds.jdbc.Driver", "microsoft:", "com.microsoft.jdbc.sqlserver.SQLServerDriver",
			"mimer:", "com.mimer.jdbc.Driver", "mysql:", "com.mysql.jdbc.Driver", "odbc:",
			"sun.jdbc.odbc.JdbcOdbcDriver", "oracle:", "oracle.jdbc.driver.OracleDriver", "pervasive:",
			"com.pervasive.jdbc.v2.Driver", "pointbase:micro:", "com.pointbase.me.jdbc.jdbcDriver",
			"pointbase:", "com.pointbase.jdbc.jdbcUniversalDriver", "postgresql:", "org.postgresql.Driver",
			"sybase:", "com.sybase.jdbc3.jdbc.SybDriver", "sqlserver:",
			"com.microsoft.sqlserver.jdbc.SQLServerDriver", "teradata:", "com.ncr.teradata.TeraDriver", };

	private JdbcUtils() {
		// utility class
	}

	/**
	 * Close a statement without throwing an exception.
	 * 
	 * @param stat
	 *            the statement or null
	 */
	public static void closeSilently(Statement stat) {
		if (stat != null) {
			try {
				stat.close();
			} catch (SQLException e) {
				// ignore
			}
		}
	}

	/**
	 * Close a connection without throwing an exception.
	 * 
	 * @param conn
	 *            the connection or null
	 */
	public static void closeSilently(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// ignore
			}
		}
	}

	/**
	 * Close a result set without throwing an exception.
	 * 
	 * @param rs
	 *            the result set or null
	 */
	public static void closeSilently(ResultSet rs) {
		closeSilently(rs, false);
	}

	/**
	 * Close a result set, and optionally its statement without throwing an
	 * exception.
	 * 
	 * @param rs
	 *            the result set or null
	 */
	public static void closeSilently(ResultSet rs, boolean closeStatement) {
		if (rs != null) {
			Statement stat = null;
			if (closeStatement) {
				try {
					stat = rs.getStatement();
				} catch (SQLException e) {
					// ignore
				}
			}
			try {
				rs.close();
			} catch (SQLException e) {
				// ignore
			}
			closeSilently(stat);
		}
	}

	/**
	 * Close an XA connection set without throwing an exception.
	 * 
	 * @param conn
	 *            the XA connection or null
	 */
	public static void closeSilently(XAConnection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// ignore
			}
		}
	}

	/**
	 * Open a new database connection with the given settings.
	 * 
	 * @param driver
	 *            the driver class name
	 * @param url
	 *            the database URL
	 * @param user
	 *            the user name
	 * @param password
	 *            the password
	 * @return the database connection
	 */
	public static Connection getConnection(String driver, String url, String user, String password)
			throws SQLException {
		Properties prop = new Properties();
		if (user != null) {
			prop.setProperty("user", user);
		}
		if (password != null) {
			prop.setProperty("password", password);
		}
		return getConnection(driver, url, prop);
	}

	/**
	 * Escape table or schema patterns used for DatabaseMetaData functions.
	 * 
	 * @param pattern
	 *            the pattern
	 * @return the escaped pattern
	 */
	public static String escapeMetaDataPattern(String pattern) {
		if (pattern == null || pattern.length() == 0) {
			return pattern;
		}
		return StringUtils.replaceAll(pattern, "\\", "\\\\");
	}

	/**
	 * Open a new database connection with the given settings.
	 * 
	 * @param driver
	 *            the driver class name
	 * @param url
	 *            the database URL
	 * @param prop
	 *            the properties containing at least the user name and password
	 * @return the database connection
	 */
	public static Connection getConnection(String driver, String url, Properties prop) throws SQLException {
		if (StringUtils.isNullOrEmpty(driver)) {
			JdbcUtils.load(url);
		} else {
			Class<?> d = Utils.loadClass(driver);
			if (java.sql.Driver.class.isAssignableFrom(d)) {
				return DriverManager.getConnection(url, prop);
			} else if (javax.naming.Context.class.isAssignableFrom(d)) {
				// JNDI context
				try {
					Context context = (Context) d.newInstance();
					DataSource ds = (DataSource) context.lookup(url);
					String user = prop.getProperty("user");
					String password = prop.getProperty("password");
					if (StringUtils.isNullOrEmpty(user) && StringUtils.isNullOrEmpty(password)) {
						return ds.getConnection();
					}
					return ds.getConnection(user, password);
				} catch (SQLException e) {
					throw e;
				} catch (Exception e) {					
					throw new SQLException("Failed to get connection for " + url, e);
				}
			} else {
				// Don't know, but maybe it loaded a JDBC Driver
				return DriverManager.getConnection(url, prop);
			}
		}
		return DriverManager.getConnection(url, prop);
	}

	/**
	 * Get the driver class name for the given URL, or null if the URL is
	 * unknown.
	 * 
	 * @param url
	 *            the database URL
	 * @return the driver class name
	 */
	public static String getDriver(String url) {
		if (url.startsWith("jdbc:")) {
			url = url.substring("jdbc:".length());
			for (int i = 0; i < DRIVERS.length; i += 2) {
				String prefix = DRIVERS[i];
				if (url.startsWith(prefix)) {
					return DRIVERS[i + 1];
				}
			}
		}
		return null;
	}

	/**
	 * Load the driver class for the given URL, if the database URL is known.
	 * 
	 * @param url
	 *            the database URL
	 */
	public static void load(String url) {
		String driver = getDriver(url);
		if (driver != null) {
			Utils.loadClass(driver);
		}
	}

}