1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.migration;
17
18 import java.sql.Connection;
19 import java.sql.Driver;
20 import java.sql.DriverManager;
21 import java.sql.SQLException;
22 import java.util.Enumeration;
23 import java.util.HashMap;
24 import java.util.Map;
25
26 import org.apache.ibatis.migration.driver.DriverShim;
27
28 public class JdbcConnectionProvider implements ConnectionProvider {
29 private static final Map<String, Driver> registeredDrivers = registeredDrivers();
30
31 private final String url;
32 private final String username;
33 private final String password;
34
35 public JdbcConnectionProvider(String driver, String url, String username, String password) {
36 this(null, driver, url, username, password);
37 }
38
39 public JdbcConnectionProvider(ClassLoader classLoader, String driver, String url, String username, String password) {
40 this.url = url;
41 this.username = username;
42 this.password = password;
43 registerDriver(classLoader, driver);
44 }
45
46 @Override
47 public Connection getConnection() throws SQLException {
48 return DriverManager.getConnection(url, username, password);
49 }
50
51 private void registerDriver(ClassLoader classLoader, String driver) {
52 registeredDrivers.computeIfAbsent(driver, d -> createDriverClass(classLoader, d));
53 }
54
55 private Driver createDriverClass(ClassLoader classLoader, String driver) {
56 try {
57 final Class<?> driverClass = classLoader == null ? Class.forName(driver)
58 : Class.forName(driver, true, classLoader);
59 final Driver driverInstance = (Driver) driverClass.getDeclaredConstructor().newInstance();
60 final DriverShim driverShim = new DriverShim(driverInstance);
61 DriverManager.registerDriver(driverShim);
62 return driverShim;
63 } catch (final Exception e) {
64 throw new IllegalStateException("Failed to register driver " + driver, e);
65 }
66 }
67
68 private static Map<String, Driver> registeredDrivers() {
69 final Map<String, Driver> registeredDrivers = new HashMap<>();
70 final Enumeration<Driver> drivers = DriverManager.getDrivers();
71 while (drivers.hasMoreElements()) {
72 final Driver driver = drivers.nextElement();
73 registeredDrivers.put(driver.getClass().getName(), driver);
74 }
75 return registeredDrivers;
76 }
77 }