Reformatting with new Eclipse formatter settings. Went with a variation of Sun-style, which leads to more compact method bodies, but still white-space to "highlight" class and method declarations.

pull/131/head
Brett Wooldridge 11 years ago
parent 0486c5904e
commit 775cba7db5

@ -82,8 +82,7 @@ public class HikariConfig implements HikariConfigMBean
private IConnectionCustomizer customizer; private IConnectionCustomizer customizer;
private int transactionIsolation; private int transactionIsolation;
static static {
{
JavassistProxyFactory.initialize(); JavassistProxyFactory.initialize();
} }
@ -133,21 +132,18 @@ public class HikariConfig implements HikariConfigMBean
this(); this();
File propFile = new File(propertyFileName); File propFile = new File(propertyFileName);
if (!propFile.isFile()) if (!propFile.isFile()) {
{
throw new IllegalArgumentException("Property file " + propertyFileName + " was not found."); throw new IllegalArgumentException("Property file " + propertyFileName + " was not found.");
} }
try try {
{
FileInputStream fis = new FileInputStream(propFile); FileInputStream fis = new FileInputStream(propFile);
Properties props = new Properties(); Properties props = new Properties();
props.load(fis); props.load(fis);
PropertyBeanSetter.setTargetFromProperties(this, props); PropertyBeanSetter.setTargetFromProperties(this, props);
fis.close(); fis.close();
} }
catch (IOException io) catch (IOException io) {
{
throw new RuntimeException("Error loading properties file", io); throw new RuntimeException("Error loading properties file", io);
} }
} }
@ -271,16 +267,13 @@ public class HikariConfig implements HikariConfigMBean
@Override @Override
public void setConnectionTimeout(long connectionTimeoutMs) public void setConnectionTimeout(long connectionTimeoutMs)
{ {
if (connectionTimeoutMs == 0) if (connectionTimeoutMs == 0) {
{
this.connectionTimeout = Integer.MAX_VALUE; this.connectionTimeout = Integer.MAX_VALUE;
} }
else if (connectionTimeoutMs < 100) else if (connectionTimeoutMs < 100) {
{
throw new IllegalArgumentException("connectionTimeout cannot be less than 100ms"); throw new IllegalArgumentException("connectionTimeout cannot be less than 100ms");
} }
else else {
{
this.connectionTimeout = connectionTimeoutMs; this.connectionTimeout = connectionTimeoutMs;
} }
} }
@ -344,14 +337,12 @@ public class HikariConfig implements HikariConfigMBean
public void setDriverClassName(String driverClassName) public void setDriverClassName(String driverClassName)
{ {
try try {
{
Class<?> driverClass = this.getClass().getClassLoader().loadClass(driverClassName); Class<?> driverClass = this.getClass().getClassLoader().loadClass(driverClassName);
driverClass.newInstance(); driverClass.newInstance();
this.driverClassName = driverClassName; this.driverClassName = driverClassName;
} }
catch (Exception e) catch (Exception e) {
{
throw new RuntimeException("driverClassName specified class '" + driverClassName + "' could not be loaded", e); throw new RuntimeException("driverClassName specified class '" + driverClassName + "' could not be loaded", e);
} }
} }
@ -516,8 +507,7 @@ public class HikariConfig implements HikariConfigMBean
@Override @Override
public void setMaximumPoolSize(int maxPoolSize) public void setMaximumPoolSize(int maxPoolSize)
{ {
if (maxPoolSize < 0) if (maxPoolSize < 0) {
{
throw new IllegalArgumentException("maxPoolSize cannot be negative"); throw new IllegalArgumentException("maxPoolSize cannot be negative");
} }
this.maxPoolSize = maxPoolSize; this.maxPoolSize = maxPoolSize;
@ -556,8 +546,7 @@ public class HikariConfig implements HikariConfigMBean
@Override @Override
public void setMinimumIdle(int minIdle) public void setMinimumIdle(int minIdle)
{ {
if (minIdle < 0 || minIdle > maxPoolSize) if (minIdle < 0 || minIdle > maxPoolSize) {
{
throw new IllegalArgumentException("maxPoolSize cannot be negative or greater than maximumPoolSize"); throw new IllegalArgumentException("maxPoolSize cannot be negative or greater than maximumPoolSize");
} }
this.minIdle = minIdle; this.minIdle = minIdle;
@ -642,63 +631,50 @@ public class HikariConfig implements HikariConfigMBean
validateNumerics(); validateNumerics();
if (connectionCustomizerClassName != null) if (connectionCustomizerClassName != null) {
{ try {
try
{
getClass().getClassLoader().loadClass(connectionCustomizerClassName); getClass().getClassLoader().loadClass(connectionCustomizerClassName);
} }
catch (Exception e) catch (Exception e) {
{
logger.warn("connectionCustomizationClass specified class '" + connectionCustomizerClassName + "' could not be loaded", e); logger.warn("connectionCustomizationClass specified class '" + connectionCustomizerClassName + "' could not be loaded", e);
connectionCustomizerClassName = null; connectionCustomizerClassName = null;
} }
} }
if (driverClassName != null && jdbcUrl == null) if (driverClassName != null && jdbcUrl == null) {
{
logger.error("when specifying driverClassName, jdbcUrl must also be specified"); logger.error("when specifying driverClassName, jdbcUrl must also be specified");
throw new IllegalStateException("when specifying driverClassName, jdbcUrl must also be specified"); throw new IllegalStateException("when specifying driverClassName, jdbcUrl must also be specified");
} }
else if (jdbcUrl != null && driverClassName == null) else if (jdbcUrl != null && driverClassName == null) {
{
logger.error("when specifying jdbcUrl, driverClassName must also be specified"); logger.error("when specifying jdbcUrl, driverClassName must also be specified");
throw new IllegalStateException("when specifying jdbcUrl, driverClassName must also be specified"); throw new IllegalStateException("when specifying jdbcUrl, driverClassName must also be specified");
} }
else if (driverClassName != null && jdbcUrl != null) else if (driverClassName != null && jdbcUrl != null) {
{
// OK // OK
} }
else if (dataSource == null && dataSourceClassName == null) else if (dataSource == null && dataSourceClassName == null) {
{
logger.error("one of either dataSource, dataSourceClassName, or jdbcUrl and driverClassName must be specified"); logger.error("one of either dataSource, dataSourceClassName, or jdbcUrl and driverClassName must be specified");
throw new IllegalArgumentException("one of either dataSource or dataSourceClassName must be specified"); throw new IllegalArgumentException("one of either dataSource or dataSourceClassName must be specified");
} }
else if (dataSource != null && dataSourceClassName != null) else if (dataSource != null && dataSourceClassName != null) {
{
logger.warn("both dataSource and dataSourceClassName are specified, ignoring dataSourceClassName"); logger.warn("both dataSource and dataSourceClassName are specified, ignoring dataSourceClassName");
} }
if (connectionTestQuery != null) if (connectionTestQuery != null) {
{
isJdbc4connectionTest = false; isJdbc4connectionTest = false;
} }
else if (!isJdbc4connectionTest) else if (!isJdbc4connectionTest) {
{
logger.error("Either jdbc4ConnectionTest must be enabled or a connectionTestQuery must be specified"); logger.error("Either jdbc4ConnectionTest must be enabled or a connectionTestQuery must be specified");
throw new IllegalStateException("Either jdbc4ConnectionTest must be enabled or a connectionTestQuery must be specified"); throw new IllegalStateException("Either jdbc4ConnectionTest must be enabled or a connectionTestQuery must be specified");
} }
if (transactionIsolationName != null) if (transactionIsolationName != null) {
{ try {
try
{
Field field = Connection.class.getField(transactionIsolationName); Field field = Connection.class.getField(transactionIsolationName);
int level = field.getInt(null); int level = field.getInt(null);
this.transactionIsolation = level; this.transactionIsolation = level;
} }
catch (Exception e) catch (Exception e) {
{
throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName);
} }
} }
@ -712,45 +688,37 @@ public class HikariConfig implements HikariConfigMBean
{ {
Logger logger = LoggerFactory.getLogger(getClass()); Logger logger = LoggerFactory.getLogger(getClass());
if (connectionTimeout == Integer.MAX_VALUE) if (connectionTimeout == Integer.MAX_VALUE) {
{
logger.warn("No connection wait timeout is set, this might cause an infinite wait"); logger.warn("No connection wait timeout is set, this might cause an infinite wait");
} }
else if (connectionTimeout < TimeUnit.MILLISECONDS.toMillis(250)) else if (connectionTimeout < TimeUnit.MILLISECONDS.toMillis(250)) {
{
logger.warn("connectionTimeout is less than 250ms, did you specify the wrong time unit? Using default instead"); logger.warn("connectionTimeout is less than 250ms, did you specify the wrong time unit? Using default instead");
connectionTimeout = CONNECTION_TIMEOUT; connectionTimeout = CONNECTION_TIMEOUT;
} }
if (minIdle < 0) if (minIdle < 0) {
{
minIdle = maxPoolSize; minIdle = maxPoolSize;
} }
if (idleTimeout < 0) if (idleTimeout < 0) {
{
logger.error("idleTimeout cannot be negative."); logger.error("idleTimeout cannot be negative.");
throw new IllegalArgumentException("idleTimeout cannot be negative"); throw new IllegalArgumentException("idleTimeout cannot be negative");
} }
else if (idleTimeout < TimeUnit.SECONDS.toMillis(30) && idleTimeout != 0) else if (idleTimeout < TimeUnit.SECONDS.toMillis(30) && idleTimeout != 0) {
{
logger.warn("idleTimeout is less than 30000ms, did you specify the wrong time unit? Using default instead"); logger.warn("idleTimeout is less than 30000ms, did you specify the wrong time unit? Using default instead");
idleTimeout = IDLE_TIMEOUT; idleTimeout = IDLE_TIMEOUT;
} }
if (leakDetectionThreshold != 0 && leakDetectionThreshold < TimeUnit.SECONDS.toMillis(10)) if (leakDetectionThreshold != 0 && leakDetectionThreshold < TimeUnit.SECONDS.toMillis(10)) {
{
logger.warn("leakDetectionThreshold is less than 10000ms, did you specify the wrong time unit? Disabling leak detection"); logger.warn("leakDetectionThreshold is less than 10000ms, did you specify the wrong time unit? Disabling leak detection");
leakDetectionThreshold = 0; leakDetectionThreshold = 0;
} }
if (maxLifetime < 0) if (maxLifetime < 0) {
{
logger.error("maxLifetime cannot be negative."); logger.error("maxLifetime cannot be negative.");
throw new IllegalArgumentException("maxLifetime cannot be negative."); throw new IllegalArgumentException("maxLifetime cannot be negative.");
} }
else if (maxLifetime < TimeUnit.SECONDS.toMillis(120) && maxLifetime != 0) else if (maxLifetime < TimeUnit.SECONDS.toMillis(120) && maxLifetime != 0) {
{
logger.warn("maxLifetime is less than 120000ms, did you specify the wrong time unit? Using default instead."); logger.warn("maxLifetime is less than 120000ms, did you specify the wrong time unit? Using default instead.");
maxLifetime = MAX_LIFETIME; maxLifetime = MAX_LIFETIME;
} }
@ -760,16 +728,13 @@ public class HikariConfig implements HikariConfigMBean
{ {
LOGGER.debug("HikariCP pool {} configuration:", poolName); LOGGER.debug("HikariCP pool {} configuration:", poolName);
Set<String> propertyNames = new TreeSet<String>(PropertyBeanSetter.getPropertyNames(HikariConfig.class)); Set<String> propertyNames = new TreeSet<String>(PropertyBeanSetter.getPropertyNames(HikariConfig.class));
for (String prop : propertyNames) for (String prop : propertyNames) {
{ try {
try
{
Object value = PropertyBeanSetter.getProperty(prop, this); Object value = PropertyBeanSetter.getProperty(prop, this);
prop = (prop + "................................................").substring(0, 32); prop = (prop + "................................................").substring(0, 32);
LOGGER.debug(prop + (value != null ? value : "")); LOGGER.debug(prop + (value != null ? value : ""));
} }
catch (Exception e) catch (Exception e) {
{
continue; continue;
} }
} }
@ -777,17 +742,13 @@ public class HikariConfig implements HikariConfigMBean
void copyState(HikariConfig other) void copyState(HikariConfig other)
{ {
for (Field field : HikariConfig.class.getDeclaredFields()) for (Field field : HikariConfig.class.getDeclaredFields()) {
{ if (!Modifier.isFinal(field.getModifiers())) {
if (!Modifier.isFinal(field.getModifiers()))
{
field.setAccessible(true); field.setAccessible(true);
try try {
{
field.set(other, field.get(this)); field.set(other, field.get(this));
} }
catch (Exception e) catch (Exception e) {
{
throw new RuntimeException("Exception copying HikariConfig state: " + e.getMessage(), e); throw new RuntimeException("Exception copying HikariConfig state: " + e.getMessage(), e);
} }
} }

@ -83,25 +83,20 @@ public class HikariDataSource extends HikariConfig implements DataSource
@Override @Override
public Connection getConnection() throws SQLException public Connection getConnection() throws SQLException
{ {
if (isShutdown) if (isShutdown) {
{
throw new SQLException("Pool has been shutdown"); throw new SQLException("Pool has been shutdown");
} }
if (fastPathPool != null) if (fastPathPool != null) {
{
return fastPathPool.getConnection(); return fastPathPool.getConnection();
} }
// See http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java // See http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
HikariPool result = pool; HikariPool result = pool;
if (result == null) if (result == null) {
{ synchronized (this) {
synchronized (this)
{
result = pool; result = pool;
if (result == null) if (result == null) {
{
validate(); validate();
LOGGER.info("HikariCP pool {} is starting.", getPoolName()); LOGGER.info("HikariCP pool {} is starting.", getPoolName());
pool = result = new HikariPool(this); pool = result = new HikariPool(this);
@ -117,19 +112,16 @@ public class HikariDataSource extends HikariConfig implements DataSource
@Override @Override
public Connection getConnection(String username, String password) throws SQLException public Connection getConnection(String username, String password) throws SQLException
{ {
if (isShutdown) if (isShutdown) {
{
throw new SQLException("Pool has been shutdown"); throw new SQLException("Pool has been shutdown");
} }
final MultiPoolKey key = new MultiPoolKey(username, password); final MultiPoolKey key = new MultiPoolKey(username, password);
HikariPool hikariPool; HikariPool hikariPool;
synchronized (multiPool) synchronized (multiPool) {
{
hikariPool = multiPool.get(key); hikariPool = multiPool.get(key);
if (hikariPool == null) if (hikariPool == null) {
{
hikariPool = new HikariPool(this, username, password); hikariPool = new HikariPool(this, username, password);
multiPool.put(key, hikariPool); multiPool.put(key, hikariPool);
} }
@ -149,8 +141,7 @@ public class HikariDataSource extends HikariConfig implements DataSource
@Override @Override
public void setLogWriter(PrintWriter out) throws SQLException public void setLogWriter(PrintWriter out) throws SQLException
{ {
if (pool.getDataSource() != null) if (pool.getDataSource() != null) {
{
pool.getDataSource().setLogWriter(out); pool.getDataSource().setLogWriter(out);
} }
} }
@ -180,8 +171,7 @@ public class HikariDataSource extends HikariConfig implements DataSource
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws SQLException public <T> T unwrap(Class<T> iface) throws SQLException
{ {
if (pool != null && iface.isInstance(pool.getDataSource())) if (pool != null && iface.isInstance(pool.getDataSource())) {
{
return (T) pool.getDataSource(); return (T) pool.getDataSource();
} }
@ -204,8 +194,7 @@ public class HikariDataSource extends HikariConfig implements DataSource
*/ */
public void evictConnection(Connection connection) public void evictConnection(Connection connection)
{ {
if (!isShutdown && pool != null && connection instanceof IHikariConnectionProxy) if (!isShutdown && pool != null && connection instanceof IHikariConnectionProxy) {
{
pool.closeConnection((IHikariConnectionProxy) connection); pool.closeConnection((IHikariConnectionProxy) connection);
} }
} }
@ -223,20 +212,17 @@ public class HikariDataSource extends HikariConfig implements DataSource
*/ */
public void shutdown() public void shutdown()
{ {
if (isShutdown) if (isShutdown) {
{
return; return;
} }
isShutdown = true; isShutdown = true;
if (fastPathPool != null) if (fastPathPool != null) {
{
shutdownHelper(fastPathPool); shutdownHelper(fastPathPool);
} }
for (HikariPool hikariPool : multiPool.values()) for (HikariPool hikariPool : multiPool.values()) {
{
shutdownHelper(hikariPool); shutdownHelper(hikariPool);
} }
} }
@ -250,17 +236,14 @@ public class HikariDataSource extends HikariConfig implements DataSource
private void shutdownHelper(HikariPool hPool) private void shutdownHelper(HikariPool hPool)
{ {
try try {
{
hPool.shutdown(); hPool.shutdown();
} }
catch (InterruptedException e) catch (InterruptedException e) {
{
LoggerFactory.getLogger(getClass()).warn("Interrupted during shutdown", e); LoggerFactory.getLogger(getClass()).warn("Interrupted during shutdown", e);
} }
if (hPool.getDataSource() instanceof DriverDataSource) if (hPool.getDataSource() instanceof DriverDataSource) {
{
((DriverDataSource) hPool.getDataSource()).shutdown(); ((DriverDataSource) hPool.getDataSource()).shutdown();
} }
} }
@ -286,20 +269,16 @@ public class HikariDataSource extends HikariConfig implements DataSource
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
MultiPoolKey otherKey = ((MultiPoolKey) obj); MultiPoolKey otherKey = ((MultiPoolKey) obj);
if (username != null && !username.equals(otherKey.username)) if (username != null && !username.equals(otherKey.username)) {
{
return false; return false;
} }
else if (username != otherKey.username) else if (username != otherKey.username) {
{
return false; return false;
} }
else if (password != null && !password.equals(otherKey.password)) else if (password != null && !password.equals(otherKey.password)) {
{
return false; return false;
} }
else if (password != otherKey.password) else if (password != otherKey.password) {
{
return false; return false;
} }

@ -41,23 +41,19 @@ public class HikariJNDIFactory implements ObjectFactory
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception
{ {
// We only know how to deal with <code>javax.naming.Reference</code> that specify a class name of "javax.sql.DataSource" // We only know how to deal with <code>javax.naming.Reference</code> that specify a class name of "javax.sql.DataSource"
if ((obj == null) || !(obj instanceof Reference)) if ((obj == null) || !(obj instanceof Reference)) {
{
return null; return null;
} }
Reference ref = (Reference) obj; Reference ref = (Reference) obj;
if (!"javax.sql.DataSource".equals(ref.getClassName())) if (!"javax.sql.DataSource".equals(ref.getClassName())) {
{
throw new NamingException(ref.getClassName() + " is not a valid class name/type for this JNDI factory."); throw new NamingException(ref.getClassName() + " is not a valid class name/type for this JNDI factory.");
} }
Properties properties = new Properties(); Properties properties = new Properties();
for (String propertyName : PropertyBeanSetter.getPropertyNames(HikariConfig.class)) for (String propertyName : PropertyBeanSetter.getPropertyNames(HikariConfig.class)) {
{
RefAddr ra = ref.get(propertyName); RefAddr ra = ref.get(propertyName);
if (ra != null) if (ra != null) {
{
String propertyValue = ra.getContent().toString(); String propertyValue = ra.getContent().toString();
properties.setProperty(propertyName, propertyValue); properties.setProperty(propertyName, propertyValue);
} }
@ -68,8 +64,7 @@ public class HikariJNDIFactory implements ObjectFactory
private DataSource createDataSource(Properties properties, Context context) private DataSource createDataSource(Properties properties, Context context)
{ {
if (properties.getProperty("dataSourceJNDI") != null) if (properties.getProperty("dataSourceJNDI") != null) {
{
return lookupJndiDataSource(properties, context); return lookupJndiDataSource(properties, context);
} }
@ -80,37 +75,29 @@ public class HikariJNDIFactory implements ObjectFactory
{ {
DataSource jndiDS = null; DataSource jndiDS = null;
String jndiName = properties.getProperty("dataSourceJNDI"); String jndiName = properties.getProperty("dataSourceJNDI");
try try {
{ if (context != null) {
if (context != null)
{
jndiDS = (DataSource) context.lookup(jndiName); jndiDS = (DataSource) context.lookup(jndiName);
} }
else else {
{
throw new RuntimeException("dataSourceJNDI property is configued, but local JNDI context is null."); throw new RuntimeException("dataSourceJNDI property is configued, but local JNDI context is null.");
} }
} }
catch (NamingException e) catch (NamingException e) {
{
throw new RuntimeException("The name \"" + jndiName + "\" can not be found in the local context."); throw new RuntimeException("The name \"" + jndiName + "\" can not be found in the local context.");
} }
if (jndiDS == null) if (jndiDS == null) {
{ try {
try
{
context = (Context) (new InitialContext()); context = (Context) (new InitialContext());
jndiDS = (DataSource) context.lookup(jndiName); jndiDS = (DataSource) context.lookup(jndiName);
} }
catch (NamingException e) catch (NamingException e) {
{
throw new RuntimeException("The name \"" + jndiName + "\" can not be found in the InitialContext."); throw new RuntimeException("The name \"" + jndiName + "\" can not be found in the InitialContext.");
} }
} }
if (jndiDS != null) if (jndiDS != null) {
{
HikariConfig config = new HikariConfig(properties); HikariConfig config = new HikariConfig(properties);
config.setDataSource(jndiDS); config.setDataSource(jndiDS);
return new HikariDataSource(config); return new HikariDataSource(config);

@ -50,11 +50,9 @@ public class HikariConfigurationUtil
copyProperty(AvailableSettings.USER, props, "username", hikariProps); copyProperty(AvailableSettings.USER, props, "username", hikariProps);
copyProperty(AvailableSettings.PASS, props, "password", hikariProps); copyProperty(AvailableSettings.PASS, props, "password", hikariProps);
for (Object keyo : props.keySet()) for (Object keyo : props.keySet()) {
{
String key = (String) keyo; String key = (String) keyo;
if (key.startsWith(CONFIG_PREFIX)) if (key.startsWith(CONFIG_PREFIX)) {
{
hikariProps.setProperty(key.substring(CONFIG_PREFIX.length()), (String) props.get(key)); hikariProps.setProperty(key.substring(CONFIG_PREFIX.length()), (String) props.get(key));
} }
} }
@ -65,8 +63,7 @@ public class HikariConfigurationUtil
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static void copyProperty(String srcKey, Map src, String dstKey, Properties dst) private static void copyProperty(String srcKey, Map src, String dstKey, Properties dst)
{ {
if (src.containsKey(srcKey)) if (src.containsKey(srcKey)) {
{
dst.setProperty(dstKey, (String) src.get(srcKey)); dst.setProperty(dstKey, (String) src.get(srcKey));
} }
} }

@ -73,16 +73,14 @@ public class HikariConnectionProvider implements ConnectionProvider, Configurabl
@Override @Override
public void configure(Map props) throws HibernateException public void configure(Map props) throws HibernateException
{ {
try try {
{
LOGGER.debug("Configuring HikariCP"); LOGGER.debug("Configuring HikariCP");
this.hcfg = HikariConfigurationUtil.loadConfiguration(props); this.hcfg = HikariConfigurationUtil.loadConfiguration(props);
this.hds = new HikariDataSource(this.hcfg); this.hds = new HikariDataSource(this.hcfg);
} }
catch (Exception e) catch (Exception e) {
{
throw new HibernateException(e); throw new HibernateException(e);
} }
@ -97,8 +95,7 @@ public class HikariConnectionProvider implements ConnectionProvider, Configurabl
public Connection getConnection() throws SQLException public Connection getConnection() throws SQLException
{ {
Connection conn = null; Connection conn = null;
if (this.hds != null) if (this.hds != null) {
{
conn = this.hds.getConnection(); conn = this.hds.getConnection();
} }
@ -128,12 +125,10 @@ public class HikariConnectionProvider implements ConnectionProvider, Configurabl
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> unwrapType) public <T> T unwrap(Class<T> unwrapType)
{ {
if (isUnwrappableAs(unwrapType)) if (isUnwrappableAs(unwrapType)) {
{
return (T) this; return (T) this;
} }
else else {
{
throw new UnknownUnwrapTypeException(unwrapType); throw new UnknownUnwrapTypeException(unwrapType);
} }
} }

@ -57,8 +57,7 @@ public final class CodaHaleMetricsTracker extends MetricsTracker
public void stop() public void stop()
{ {
if (innerContext != null) if (innerContext != null) {
{
innerContext.stop(); innerContext.stop();
} }
} }

@ -16,7 +16,6 @@
package com.zaxxer.hikari.metrics; package com.zaxxer.hikari.metrics;
/** /**
* This class does absolutely nothing. * This class does absolutely nothing.
* *

@ -48,24 +48,20 @@ public final class HikariMBeanElf
*/ */
public static void registerMBeans(HikariConfig configuration, HikariPool pool) public static void registerMBeans(HikariConfig configuration, HikariPool pool)
{ {
try try {
{
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName poolConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + configuration.getPoolName() + ")"); ObjectName poolConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + configuration.getPoolName() + ")");
ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + configuration.getPoolName() + ")"); ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + configuration.getPoolName() + ")");
if (!mBeanServer.isRegistered(poolConfigName)) if (!mBeanServer.isRegistered(poolConfigName)) {
{
mBeanServer.registerMBean(configuration, poolConfigName); mBeanServer.registerMBean(configuration, poolConfigName);
mBeanServer.registerMBean(pool, poolName); mBeanServer.registerMBean(pool, poolName);
} }
else else {
{
LOGGER.error("You cannot use the same HikariConfig for separate pool instances."); LOGGER.error("You cannot use the same HikariConfig for separate pool instances.");
} }
} }
catch (Exception e) catch (Exception e) {
{
LOGGER.warn("Unable to register management beans.", e); LOGGER.warn("Unable to register management beans.", e);
} }
} }
@ -78,24 +74,20 @@ public final class HikariMBeanElf
*/ */
public static void unregisterMBeans(HikariConfig configuration, HikariPool pool) public static void unregisterMBeans(HikariConfig configuration, HikariPool pool)
{ {
try try {
{
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName poolConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + configuration.getPoolName() + ")"); ObjectName poolConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + configuration.getPoolName() + ")");
ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + configuration.getPoolName() + ")"); ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + configuration.getPoolName() + ")");
if (mBeanServer.isRegistered(poolConfigName)) if (mBeanServer.isRegistered(poolConfigName)) {
{
mBeanServer.unregisterMBean(poolConfigName); mBeanServer.unregisterMBean(poolConfigName);
mBeanServer.unregisterMBean(poolName); mBeanServer.unregisterMBean(poolName);
} }
else else {
{
LOGGER.error("No registered MBean for {}.", configuration.getPoolName()); LOGGER.error("No registered MBean for {}.", configuration.getPoolName());
} }
} }
catch (Exception e) catch (Exception e) {
{
LOGGER.warn("Unable to unregister management beans.", e); LOGGER.warn("Unable to unregister management beans.", e);
} }
} }

@ -128,12 +128,12 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
this.leakDetectionThreshold = configuration.getLeakDetectionThreshold(); this.leakDetectionThreshold = configuration.getLeakDetectionThreshold();
this.transactionIsolation = configuration.getTransactionIsolation(); this.transactionIsolation = configuration.getTransactionIsolation();
this.isRecordMetrics = configuration.isRecordMetrics(); this.isRecordMetrics = configuration.isRecordMetrics();
this.metricsTracker = MetricsFactory.createMetricsTracker((isRecordMetrics ? configuration.getMetricsTrackerClassName() : "com.zaxxer.hikari.metrics.MetricsTracker"), configuration.getPoolName()); this.metricsTracker = MetricsFactory.createMetricsTracker((isRecordMetrics ? configuration.getMetricsTrackerClassName()
: "com.zaxxer.hikari.metrics.MetricsTracker"), configuration.getPoolName());
this.dataSource = initializeDataSource(); this.dataSource = initializeDataSource();
if (isRegisteredMbeans) if (isRegisteredMbeans) {
{
HikariMBeanElf.registerMBeans(configuration, this); HikariMBeanElf.registerMBeans(configuration, this);
} }
@ -158,27 +158,22 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
final MetricsContext context = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT); final MetricsContext context = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT);
long timeout = connectionTimeout; long timeout = connectionTimeout;
try try {
{ do {
do
{
IHikariConnectionProxy connection = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS); IHikariConnectionProxy connection = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (connection == null) if (connection == null) {
{
break; // We timed out... break and throw exception break; // We timed out... break and throw exception
} }
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
connection.unclose(now); connection.unclose(now);
if (now > connection.getExpirationTime() || (now - connection.getLastAccess() > 1000L && !isConnectionAlive(connection, timeout))) if (now > connection.getExpirationTime() || (now - connection.getLastAccess() > 1000L && !isConnectionAlive(connection, timeout))) {
{
closeConnection(connection); // Throw away the dead connection and try again closeConnection(connection); // Throw away the dead connection and try again
timeout -= elapsedTimeMs(start); timeout -= elapsedTimeMs(start);
continue; continue;
} }
else if (leakDetectionThreshold != 0) else if (leakDetectionThreshold != 0) {
{
connection.captureStack(leakDetectionThreshold, houseKeepingTimer); connection.captureStack(leakDetectionThreshold, houseKeepingTimer);
} }
@ -186,18 +181,16 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
} }
while (timeout > 0L); while (timeout > 0L);
} }
catch (InterruptedException e) catch (InterruptedException e) {
{
throw new SQLException("Interrupted during connection acquisition", e); throw new SQLException("Interrupted during connection acquisition", e);
} }
finally finally {
{
context.stop(); context.stop();
} }
logPoolState("Timeout failure "); logPoolState("Timeout failure ");
throw new SQLException(String.format("Timeout of %dms encountered waiting for connection.", throw new SQLException(String.format("Timeout of %dms encountered waiting for connection.", configuration.getConnectionTimeout()),
configuration.getConnectionTimeout()), lastConnectionFailure.getAndSet(null)); lastConnectionFailure.getAndSet(null));
} }
/** /**
@ -208,13 +201,11 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/ */
public void releaseConnection(final IHikariConnectionProxy connectionProxy, final boolean isBroken) public void releaseConnection(final IHikariConnectionProxy connectionProxy, final boolean isBroken)
{ {
if (isRecordMetrics) if (isRecordMetrics) {
{
metricsTracker.recordConnectionUsage(elapsedTimeMs(connectionProxy.getLastOpenTime())); metricsTracker.recordConnectionUsage(elapsedTimeMs(connectionProxy.getLastOpenTime()));
} }
if (isBroken || isShutdown) if (isBroken || isShutdown) {
{
LOGGER.debug("Connection returned to pool {} is broken, or the pool is shutting down. Closing connection.", configuration.getPoolName()); LOGGER.debug("Connection returned to pool {} is broken, or the pool is shutting down. Closing connection.", configuration.getPoolName());
closeConnection(connectionProxy); closeConnection(connectionProxy);
return; return;
@ -231,8 +222,7 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/ */
public void shutdown() throws InterruptedException public void shutdown() throws InterruptedException
{ {
if (!isShutdown) if (!isShutdown) {
{
isShutdown = true; isShutdown = true;
LOGGER.info("HikariCP pool {} is shutting down.", configuration.getPoolName()); LOGGER.info("HikariCP pool {} is shutting down.", configuration.getPoolName());
@ -241,17 +231,15 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
addConnectionExecutor.shutdownNow(); addConnectionExecutor.shutdownNow();
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
do do {
{
closeIdleConnections(); closeIdleConnections();
abortActiveConnections(); abortActiveConnections();
} }
while ((getIdleConnections() > 0 || getActiveConnections() > 0 ) && elapsedTimeMs(start) < TimeUnit.SECONDS.toMillis(5)); while ((getIdleConnections() > 0 || getActiveConnections() > 0) && elapsedTimeMs(start) < TimeUnit.SECONDS.toMillis(5));
logPoolState("After shutdown "); logPoolState("After shutdown ");
if (isRegisteredMbeans) if (isRegisteredMbeans) {
{
HikariMBeanElf.unregisterMBeans(configuration, this); HikariMBeanElf.unregisterMBeans(configuration, this);
} }
} }
@ -274,21 +262,17 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/ */
public void closeConnection(final IHikariConnectionProxy connectionProxy) public void closeConnection(final IHikariConnectionProxy connectionProxy)
{ {
try try {
{
int tc = totalConnections.decrementAndGet(); int tc = totalConnections.decrementAndGet();
if (tc < 0) if (tc < 0) {
{
LOGGER.warn("Internal accounting inconsistency, totalConnections={}", tc, new Exception()); LOGGER.warn("Internal accounting inconsistency, totalConnections={}", tc, new Exception());
} }
connectionProxy.realClose(); connectionProxy.realClose();
} }
catch (SQLException e) catch (SQLException e) {
{
return; return;
} }
finally finally {
{
connectionBag.remove(connectionProxy); connectionBag.remove(connectionProxy);
} }
} }
@ -307,23 +291,21 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
@Override @Override
public void addBagItem() public void addBagItem()
{ {
class AddConnection implements Runnable { class AddConnection implements Runnable
{
public void run() public void run()
{ {
long sleepBackoff = 200L; long sleepBackoff = 200L;
final int maxPoolSize = configuration.getMaximumPoolSize(); final int maxPoolSize = configuration.getMaximumPoolSize();
final int minIdle = configuration.getMinimumIdle(); final int minIdle = configuration.getMinimumIdle();
while (!isShutdown && totalConnections.get() < maxPoolSize && (minIdle == 0 || getIdleConnections() < minIdle)) while (!isShutdown && totalConnections.get() < maxPoolSize && (minIdle == 0 || getIdleConnections() < minIdle)) {
{ if (!addConnection()) {
if (!addConnection())
{
quietlySleep(sleepBackoff); quietlySleep(sleepBackoff);
sleepBackoff = Math.min(1000L, (long) ((double) sleepBackoff * 1.5)); sleepBackoff = Math.min(1000L, (long) ((double) sleepBackoff * 1.5));
continue; continue;
} }
if (minIdle == 0) if (minIdle == 0) {
{
break; // This break is here so we only add one connection when there is no min. idle break; // This break is here so we only add one connection when there is no min. idle
} }
} }
@ -369,10 +351,8 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
@Override @Override
public void closeIdleConnections() public void closeIdleConnections()
{ {
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_NOT_IN_USE)) for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_NOT_IN_USE)) {
{ if (connectionBag.reserve(connectionProxy)) {
if (connectionBag.reserve(connectionProxy))
{
closeConnection(connectionProxy); closeConnection(connectionProxy);
} }
} }
@ -388,11 +368,9 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
private boolean addConnection() private boolean addConnection()
{ {
Connection connection = null; Connection connection = null;
try try {
{
// Speculative increment of totalConnections with expectation of success // Speculative increment of totalConnections with expectation of success
if (totalConnections.incrementAndGet() > configuration.getMaximumPoolSize() || isShutdown) if (totalConnections.incrementAndGet() > configuration.getMaximumPoolSize() || isShutdown) {
{
totalConnections.decrementAndGet(); totalConnections.decrementAndGet();
return true; return true;
} }
@ -403,15 +381,14 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
executeSqlAutoCommit(connection, configuration.getConnectionInitSql()); executeSqlAutoCommit(connection, configuration.getConnectionInitSql());
IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, connection, configuration.getMaxLifetime(), IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, connection, configuration.getMaxLifetime(), transactionIsolation,
transactionIsolation, isAutoCommit, isReadOnly, catalog); isAutoCommit, isReadOnly, catalog);
proxyConnection.resetConnectionState(); proxyConnection.resetConnectionState();
connectionBag.add(proxyConnection); connectionBag.add(proxyConnection);
lastConnectionFailure.set(null); lastConnectionFailure.set(null);
return true; return true;
} }
catch (Exception e) catch (Exception e) {
{
// We failed, so undo speculative increment of totalConnections // We failed, so undo speculative increment of totalConnections
totalConnections.decrementAndGet(); totalConnections.decrementAndGet();
@ -431,34 +408,28 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/ */
private boolean isConnectionAlive(final IHikariConnectionProxy connection, long timeoutMs) private boolean isConnectionAlive(final IHikariConnectionProxy connection, long timeoutMs)
{ {
try try {
{
final boolean timeoutEnabled = (configuration.getConnectionTimeout() != Integer.MAX_VALUE); final boolean timeoutEnabled = (configuration.getConnectionTimeout() != Integer.MAX_VALUE);
timeoutMs = timeoutEnabled ? Math.max(1000L, timeoutMs) : 0; timeoutMs = timeoutEnabled ? Math.max(1000L, timeoutMs) : 0;
if (isJdbc4ConnectionTest) if (isJdbc4ConnectionTest) {
{
return connection.isValid((int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs)); return connection.isValid((int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs));
} }
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
try try {
{
statement.setQueryTimeout((int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs)); statement.setQueryTimeout((int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs));
statement.executeQuery(configuration.getConnectionTestQuery()); statement.executeQuery(configuration.getConnectionTestQuery());
return true; return true;
} }
finally finally {
{
statement.close(); statement.close();
if (isIsolateInternalQueries && !isAutoCommit) if (isIsolateInternalQueries && !isAutoCommit) {
{
connection.rollback(); connection.rollback();
} }
} }
} }
catch (SQLException e) catch (SQLException e) {
{
LOGGER.warn("Exception during keep alive check, that means the connection must be dead.", e); LOGGER.warn("Exception during keep alive check, that means the connection must be dead.", e);
return false; return false;
} }
@ -469,18 +440,14 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/ */
private void fillPool() private void fillPool()
{ {
if (configuration.isInitializationFailFast()) if (configuration.isInitializationFailFast()) {
{ for (int maxIters = configuration.getMinimumIdle(); maxIters > 0; maxIters--) {
for (int maxIters = configuration.getMinimumIdle(); maxIters > 0; maxIters--) if (!addConnection()) {
{
if (!addConnection())
{
throw new RuntimeException("Fail-fast during pool initialization", lastConnectionFailure.getAndSet(null)); throw new RuntimeException("Fail-fast during pool initialization", lastConnectionFailure.getAndSet(null));
} }
} }
} }
else if (configuration.getMinimumIdle() > 0) else if (configuration.getMinimumIdle() > 0) {
{
addBagItem(); addBagItem();
} }
} }
@ -493,31 +460,24 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
private void abortActiveConnections() throws InterruptedException private void abortActiveConnections() throws InterruptedException
{ {
ThreadPoolExecutor assassinExecutor = createThreadPoolExecutor(configuration.getMaximumPoolSize(), "HikariCP connection assassin"); ThreadPoolExecutor assassinExecutor = createThreadPoolExecutor(configuration.getMaximumPoolSize(), "HikariCP connection assassin");
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_IN_USE)) for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_IN_USE)) {
{ try {
try if (IS_JAVA7) {
{
if (IS_JAVA7)
{
connectionProxy.abort(assassinExecutor); connectionProxy.abort(assassinExecutor);
continue; continue;
} }
connectionProxy.close(); connectionProxy.close();
} }
catch (SQLException e) catch (SQLException e) {
{
continue; continue;
} }
finally finally {
{
totalConnections.decrementAndGet(); totalConnections.decrementAndGet();
try try {
{
connectionBag.remove(connectionProxy); connectionBag.remove(connectionProxy);
} }
catch (IllegalStateException ise) catch (IllegalStateException ise) {
{
continue; continue;
} }
} }
@ -535,14 +495,12 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
private DataSource initializeDataSource() private DataSource initializeDataSource()
{ {
String dsClassName = configuration.getDataSourceClassName(); String dsClassName = configuration.getDataSourceClassName();
if (configuration.getDataSource() == null && dsClassName != null) if (configuration.getDataSource() == null && dsClassName != null) {
{
DataSource dataSource = createInstance(dsClassName, DataSource.class); DataSource dataSource = createInstance(dsClassName, DataSource.class);
PropertyBeanSetter.setTargetFromProperties(dataSource, configuration.getDataSourceProperties()); PropertyBeanSetter.setTargetFromProperties(dataSource, configuration.getDataSourceProperties());
return dataSource; return dataSource;
} }
else if (configuration.getJdbcUrl() != null) else if (configuration.getJdbcUrl() != null) {
{
return new DriverDataSource(configuration.getJdbcUrl(), configuration.getDataSourceProperties(), username, password); return new DriverDataSource(configuration.getJdbcUrl(), configuration.getDataSourceProperties(), username, password);
} }
@ -551,8 +509,7 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
private IConnectionCustomizer initializeCustomizer() private IConnectionCustomizer initializeCustomizer()
{ {
if (configuration.getConnectionCustomizerClassName() != null) if (configuration.getConnectionCustomizerClassName() != null) {
{
return createInstance(configuration.getConnectionCustomizerClassName(), IConnectionCustomizer.class); return createInstance(configuration.getConnectionCustomizerClassName(), IConnectionCustomizer.class);
} }
@ -563,8 +520,8 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
{ {
int total = totalConnections.get(); int total = totalConnections.get();
int idle = getIdleConnections(); int idle = getIdleConnections();
LOGGER.debug("{}pool stats {} (total={}, inUse={}, avail={}, waiting={})", (prefix.length > 0 ? prefix[0] : ""), LOGGER.debug("{}pool stats {} (total={}, inUse={}, avail={}, waiting={})", (prefix.length > 0 ? prefix[0] : ""), configuration.getPoolName(), total,
configuration.getPoolName(), total, total - idle, idle, getThreadsAwaitingConnection()); total - idle, idle, getThreadsAwaitingConnection());
} }
/** /**
@ -583,14 +540,9 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
final long idleTimeout = configuration.getIdleTimeout(); final long idleTimeout = configuration.getIdleTimeout();
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_NOT_IN_USE)) for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_NOT_IN_USE)) {
{ if (connectionBag.reserve(connectionProxy)) {
if (connectionBag.reserve(connectionProxy)) if ((idleTimeout > 0L && now > connectionProxy.getLastAccess() + idleTimeout) || (now > connectionProxy.getExpirationTime())) {
{
if ((idleTimeout > 0L && now > connectionProxy.getLastAccess() + idleTimeout)
||
(now > connectionProxy.getExpirationTime()))
{
closeConnection(connectionProxy); closeConnection(connectionProxy);
continue; continue;
} }

@ -69,8 +69,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
private final int hashCode; private final int hashCode;
// static initializer // static initializer
static static {
{
SQL_ERRORS = new HashSet<String>(); SQL_ERRORS = new HashSet<String>();
SQL_ERRORS.add("57P01"); // ADMIN SHUTDOWN SQL_ERRORS.add("57P01"); // ADMIN SHUTDOWN
SQL_ERRORS.add("57P02"); // CRASH SHUTDOWN SQL_ERRORS.add("57P02"); // CRASH SHUTDOWN
@ -80,7 +79,8 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
SQL_ERRORS.add("JZ0C1"); // Sybase disconnect error SQL_ERRORS.add("JZ0C1"); // Sybase disconnect error
} }
protected ConnectionProxy(HikariPool pool, Connection connection, long maxLifetime, int defaultIsolationLevel, boolean defaultAutoCommit, boolean defaultReadOnly, String defaultCatalog) protected ConnectionProxy(HikariPool pool, Connection connection, long maxLifetime, int defaultIsolationLevel, boolean defaultAutoCommit,
boolean defaultReadOnly, String defaultCatalog)
{ {
this.parentPool = pool; this.parentPool = pool;
this.delegate = connection; this.delegate = connection;
@ -137,15 +137,13 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void checkException(SQLException sqle) public final void checkException(SQLException sqle)
{ {
String sqlState = sqle.getSQLState(); String sqlState = sqle.getSQLState();
if (sqlState != null) if (sqlState != null) {
{
forceClose |= sqlState.startsWith("08") | SQL_ERRORS.contains(sqlState); forceClose |= sqlState.startsWith("08") | SQL_ERRORS.contains(sqlState);
if (forceClose) if (forceClose) {
{ LOGGER.warn(String.format("Connection %s (%s) marked as broken because of SQLSTATE(%s), ErrorCode(%d).", delegate.toString(),
LOGGER.warn(String.format("Connection %s (%s) marked as broken because of SQLSTATE(%s), ErrorCode(%d).", delegate.toString(), parentPool.toString(), sqlState, sqle.getErrorCode()), sqle); parentPool.toString(), sqlState, sqle.getErrorCode()), sqle);
} }
else if (sqle.getNextException() instanceof SQLException) else if (sqle.getNextException() instanceof SQLException) {
{
checkException(sqle.getNextException()); checkException(sqle.getNextException());
} }
} }
@ -190,31 +188,26 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
@Override @Override
public final void resetConnectionState() throws SQLException public final void resetConnectionState() throws SQLException
{ {
if (!delegate.getAutoCommit()) if (!delegate.getAutoCommit()) {
{
delegate.rollback(); delegate.rollback();
} }
if (isReadOnlyDirty) if (isReadOnlyDirty) {
{
delegate.setReadOnly(defaultReadOnly); delegate.setReadOnly(defaultReadOnly);
isReadOnlyDirty = false; isReadOnlyDirty = false;
} }
if (isAutoCommitDirty) if (isAutoCommitDirty) {
{
delegate.setAutoCommit(defaultAutoCommit); delegate.setAutoCommit(defaultAutoCommit);
isAutoCommitDirty = false; isAutoCommitDirty = false;
} }
if (isTransactionIsolationDirty) if (isTransactionIsolationDirty) {
{
delegate.setTransactionIsolation(defaultIsolationLevel); delegate.setTransactionIsolation(defaultIsolationLevel);
isTransactionIsolationDirty = false; isTransactionIsolationDirty = false;
} }
if (isCatalogDirty && defaultCatalog != null) if (isCatalogDirty && defaultCatalog != null) {
{
delegate.setCatalog(defaultCatalog); delegate.setCatalog(defaultCatalog);
isCatalogDirty = false; isCatalogDirty = false;
} }
@ -237,8 +230,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
// If the connection is not closed. If it is closed, it means this is being // If the connection is not closed. If it is closed, it means this is being
// called back as a result of the close() method below in which case we // called back as a result of the close() method below in which case we
// will clear the openStatements collection en mass. // will clear the openStatements collection en mass.
if (!isClosed) if (!isClosed) {
{
openStatements.remove(statement); openStatements.remove(statement);
} }
} }
@ -249,8 +241,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
protected final void checkClosed() throws SQLException protected final void checkClosed() throws SQLException
{ {
if (isClosed) if (isClosed) {
{
throw new SQLException("Connection is closed"); throw new SQLException("Connection is closed");
} }
} }
@ -288,29 +279,22 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
@Override @Override
public final void close() throws SQLException public final void close() throws SQLException
{ {
if (!isClosed) if (!isClosed) {
{
isClosed = true; isClosed = true;
if (leakTask != null) if (leakTask != null) {
{
leakTask.cancel(); leakTask.cancel();
leakTask = null; leakTask = null;
} }
try try {
{
final int size = openStatements.size(); final int size = openStatements.size();
if (size > 0) if (size > 0) {
{ for (int i = 0; i < size; i++) {
for (int i = 0; i < size; i++) try {
{
try
{
openStatements.get(i).close(); openStatements.get(i).close();
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
} }
} }
@ -320,13 +304,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
resetConnectionState(); resetConnectionState();
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
finally finally {
{
lastAccess = System.currentTimeMillis(); lastAccess = System.currentTimeMillis();
parentPool.releaseConnection(this, forceClose); parentPool.releaseConnection(this, forceClose);
} }
@ -345,13 +327,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final Statement createStatement() throws SQLException public final Statement createStatement() throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement()); Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement());
return trackStatement(proxyStatement); return trackStatement(proxyStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -362,13 +342,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException public final Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement(resultSetType, resultSetConcurrency)); Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement(resultSetType, resultSetConcurrency));
return trackStatement(proxyStatement); return trackStatement(proxyStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -379,13 +357,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException public final Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability)); Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability));
return trackStatement(proxyStatement); return trackStatement(proxyStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -396,13 +372,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final CallableStatement prepareCall(String sql) throws SQLException public final CallableStatement prepareCall(String sql) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql)); CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql));
return trackStatement(proxyCallableStatement); return trackStatement(proxyCallableStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -413,13 +387,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException public final CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency)); CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency));
return trackStatement(proxyCallableStatement); return trackStatement(proxyCallableStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -430,13 +402,12 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException public final CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{ CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency,
CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability)); resultSetHoldability));
return trackStatement(proxyCallableStatement); return trackStatement(proxyCallableStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -447,13 +418,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql) throws SQLException public final PreparedStatement prepareStatement(String sql) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql)); PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql));
return trackStatement(proxyPreparedStatement); return trackStatement(proxyPreparedStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -464,13 +433,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException public final PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, autoGeneratedKeys)); PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, autoGeneratedKeys));
return trackStatement(proxyPreparedStatement); return trackStatement(proxyPreparedStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -481,13 +448,12 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException public final PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{ PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this,
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, resultSetType, resultSetConcurrency)); delegate.prepareStatement(sql, resultSetType, resultSetConcurrency));
return trackStatement(proxyPreparedStatement); return trackStatement(proxyPreparedStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -498,13 +464,13 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException public final PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{ PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, resultSetType,
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability)); resultSetConcurrency,
resultSetHoldability));
return trackStatement(proxyPreparedStatement); return trackStatement(proxyPreparedStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -515,13 +481,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException public final PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, columnIndexes)); PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, columnIndexes));
return trackStatement(proxyPreparedStatement); return trackStatement(proxyPreparedStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -532,13 +496,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException public final PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, columnNames)); PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, columnNames));
return trackStatement(proxyPreparedStatement); return trackStatement(proxyPreparedStatement);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -548,17 +510,14 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
@Override @Override
public final boolean isValid(int timeout) throws SQLException public final boolean isValid(int timeout) throws SQLException
{ {
if (isClosed) if (isClosed) {
{
return false; return false;
} }
try try {
{
return delegate.isValid(timeout); return delegate.isValid(timeout);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -569,13 +528,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void setAutoCommit(boolean autoCommit) throws SQLException public final void setAutoCommit(boolean autoCommit) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
delegate.setAutoCommit(autoCommit); delegate.setAutoCommit(autoCommit);
isAutoCommitDirty = (autoCommit != defaultAutoCommit); isAutoCommitDirty = (autoCommit != defaultAutoCommit);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -586,13 +543,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void setReadOnly(boolean readOnly) throws SQLException public final void setReadOnly(boolean readOnly) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
delegate.setReadOnly(readOnly); delegate.setReadOnly(readOnly);
isReadOnlyDirty = (readOnly != defaultReadOnly); isReadOnlyDirty = (readOnly != defaultReadOnly);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -603,13 +558,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void setTransactionIsolation(int level) throws SQLException public final void setTransactionIsolation(int level) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
delegate.setTransactionIsolation(level); delegate.setTransactionIsolation(level);
isTransactionIsolationDirty = (level != defaultIsolationLevel); isTransactionIsolationDirty = (level != defaultIsolationLevel);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -619,13 +572,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void setCatalog(String catalog) throws SQLException public final void setCatalog(String catalog) throws SQLException
{ {
checkClosed(); checkClosed();
try try {
{
delegate.setCatalog(catalog); delegate.setCatalog(catalog);
isCatalogDirty = !catalog.equals(defaultCatalog); isCatalogDirty = !catalog.equals(defaultCatalog);
} }
catch (SQLException e) catch (SQLException e) {
{
checkException(e); checkException(e);
throw e; throw e;
} }
@ -643,8 +594,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public final <T> T unwrap(Class<T> iface) throws SQLException public final <T> T unwrap(Class<T> iface) throws SQLException
{ {
if (iface.isInstance(delegate)) if (iface.isInstance(delegate)) {
{
return (T) delegate; return (T) delegate;
} }

@ -47,23 +47,19 @@ public final class JavassistProxyFactory
{ {
private ClassPool classPool; private ClassPool classPool;
static static {
{
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try try {
{
Thread.currentThread().setContextClassLoader(JavassistProxyFactory.class.getClassLoader()); Thread.currentThread().setContextClassLoader(JavassistProxyFactory.class.getClassLoader());
JavassistProxyFactory proxyFactoryFactory = new JavassistProxyFactory(); JavassistProxyFactory proxyFactoryFactory = new JavassistProxyFactory();
proxyFactoryFactory.modifyProxyFactory(); proxyFactoryFactory.modifyProxyFactory();
} }
catch (Exception e) catch (Exception e) {
{
LoggerFactory.getLogger(JavassistProxyFactory.class).error("Fatal exception during proxy generation", e); LoggerFactory.getLogger(JavassistProxyFactory.class).error("Fatal exception during proxy generation", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
finally finally {
{
Thread.currentThread().setContextClassLoader(contextClassLoader); Thread.currentThread().setContextClassLoader(contextClassLoader);
} }
} }
@ -83,8 +79,7 @@ public final class JavassistProxyFactory
classPool.importPackage("java.sql"); classPool.importPackage("java.sql");
classPool.appendClassPath(new LoaderClassPath(this.getClass().getClassLoader())); classPool.appendClassPath(new LoaderClassPath(this.getClass().getClassLoader()));
try try {
{
// Connection is special, it has a checkClosed() call at the beginning // Connection is special, it has a checkClosed() call at the beginning
String methodBody = "{ checkClosed(); try { return delegate.method($$); } catch (SQLException e) { checkException(e); throw e;} }"; String methodBody = "{ checkClosed(); try { return delegate.method($$); } catch (SQLException e) { checkException(e); throw e;} }";
generateProxyClass(Connection.class, ConnectionProxy.class, methodBody); generateProxyClass(Connection.class, ConnectionProxy.class, methodBody);
@ -98,8 +93,7 @@ public final class JavassistProxyFactory
generateProxyClass(PreparedStatement.class, PreparedStatementProxy.class, methodBody); generateProxyClass(PreparedStatement.class, PreparedStatementProxy.class, methodBody);
generateProxyClass(CallableStatement.class, CallableStatementProxy.class, methodBody); generateProxyClass(CallableStatement.class, CallableStatementProxy.class, methodBody);
} }
catch (Exception e) catch (Exception e) {
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -108,23 +102,18 @@ public final class JavassistProxyFactory
{ {
String packageName = JavassistProxyFactory.class.getPackage().getName(); String packageName = JavassistProxyFactory.class.getPackage().getName();
CtClass proxyCt = classPool.getCtClass("com.zaxxer.hikari.proxy.ProxyFactory"); CtClass proxyCt = classPool.getCtClass("com.zaxxer.hikari.proxy.ProxyFactory");
for (CtMethod method : proxyCt.getMethods()) for (CtMethod method : proxyCt.getMethods()) {
{
String methodName = method.getName(); String methodName = method.getName();
if ("getProxyConnection".equals(methodName)) if ("getProxyConnection".equals(methodName)) {
{
method.setBody("{return new " + packageName + ".ConnectionJavassistProxy($$);}"); method.setBody("{return new " + packageName + ".ConnectionJavassistProxy($$);}");
} }
else if ("getProxyStatement".equals(methodName)) else if ("getProxyStatement".equals(methodName)) {
{
method.setBody("{return new " + packageName + ".StatementJavassistProxy($$);}"); method.setBody("{return new " + packageName + ".StatementJavassistProxy($$);}");
} }
else if ("getProxyPreparedStatement".equals(methodName)) else if ("getProxyPreparedStatement".equals(methodName)) {
{
method.setBody("{return new " + packageName + ".PreparedStatementJavassistProxy($$);}"); method.setBody("{return new " + packageName + ".PreparedStatementJavassistProxy($$);}");
} }
else if ("getProxyCallableStatement".equals(methodName)) else if ("getProxyCallableStatement".equals(methodName)) {
{
method.setBody("{return new " + packageName + ".CallableStatementJavassistProxy($$);}"); method.setBody("{return new " + packageName + ".CallableStatementJavassistProxy($$);}");
} }
} }
@ -146,10 +135,8 @@ public final class JavassistProxyFactory
// Make a set of method signatures we inherit implementation for, so we don't generate delegates for these // Make a set of method signatures we inherit implementation for, so we don't generate delegates for these
Set<String> superSigs = new HashSet<String>(); Set<String> superSigs = new HashSet<String>();
for (CtMethod method : superClassCt.getMethods()) for (CtMethod method : superClassCt.getMethods()) {
{ if ((method.getModifiers() & Modifier.ABSTRACT) != Modifier.ABSTRACT) {
if ((method.getModifiers() & Modifier.ABSTRACT) != Modifier.ABSTRACT)
{
superSigs.add(method.getName() + method.getSignature()); superSigs.add(method.getName() + method.getSignature());
} }
} }
@ -158,23 +145,19 @@ public final class JavassistProxyFactory
Set<String> methods = new HashSet<String>(); Set<String> methods = new HashSet<String>();
Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(primaryInterface); Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(primaryInterface);
for (Class<?> intf : interfaces) for (Class<?> intf : interfaces) {
{
CtClass intfCt = classPool.getCtClass(intf.getName()); CtClass intfCt = classPool.getCtClass(intf.getName());
targetCt.addInterface(intfCt); targetCt.addInterface(intfCt);
for (CtMethod intfMethod : intfCt.getDeclaredMethods()) for (CtMethod intfMethod : intfCt.getDeclaredMethods()) {
{
final String signature = intfMethod.getName() + intfMethod.getSignature(); final String signature = intfMethod.getName() + intfMethod.getSignature();
// don't generate delegates for methods we override // don't generate delegates for methods we override
if (superSigs.contains(signature)) if (superSigs.contains(signature)) {
{
continue; continue;
} }
// Ignore already added methods that come from other interfaces // Ignore already added methods that come from other interfaces
if (methods.contains(signature)) if (methods.contains(signature)) {
{
continue; continue;
} }
@ -186,17 +169,14 @@ public final class JavassistProxyFactory
// Generate a method that simply invokes the same method on the delegate // Generate a method that simply invokes the same method on the delegate
String modifiedBody; String modifiedBody;
if (isThrowsSqlException(intfMethod)) if (isThrowsSqlException(intfMethod)) {
{
modifiedBody = methodBody.replace("method", method.getName()); modifiedBody = methodBody.replace("method", method.getName());
} }
else else {
{
modifiedBody = "{ return ((cast) delegate).method($$); }".replace("method", method.getName()).replace("cast", primaryInterface.getName()); modifiedBody = "{ return ((cast) delegate).method($$); }".replace("method", method.getName()).replace("cast", primaryInterface.getName());
} }
if (method.getReturnType() == CtClass.voidType) if (method.getReturnType() == CtClass.voidType) {
{
modifiedBody = modifiedBody.replace("return", ""); modifiedBody = modifiedBody.replace("return", "");
} }
@ -205,8 +185,7 @@ public final class JavassistProxyFactory
} }
} }
if (LoggerFactory.getLogger(getClass()).isDebugEnabled()) if (LoggerFactory.getLogger(getClass()).isDebugEnabled()) {
{
targetCt.debugWriteFile(System.getProperty("java.io.tmpdir")); targetCt.debugWriteFile(System.getProperty("java.io.tmpdir"));
} }
@ -215,18 +194,14 @@ public final class JavassistProxyFactory
private boolean isThrowsSqlException(CtMethod method) private boolean isThrowsSqlException(CtMethod method)
{ {
try try {
{ for (CtClass clazz : method.getExceptionTypes()) {
for (CtClass clazz : method.getExceptionTypes()) if (clazz.getSimpleName().equals("SQLException")) {
{
if (clazz.getSimpleName().equals("SQLException"))
{
return true; return true;
} }
} }
} }
catch (NotFoundException e) catch (NotFoundException e) {
{
// fall thru // fall thru
} }

@ -38,8 +38,7 @@ class LeakTask extends TimerTask
@Override @Override
public void run() public void run()
{ {
if (System.currentTimeMillis() > leakTime) if (System.currentTimeMillis() > leakTime) {
{
Exception e = new Exception(); Exception e = new Exception();
e.setStackTrace(stackTrace); e.setStackTrace(stackTrace);
LoggerFactory.getLogger(LeakTask.class).warn("Connection leak detection triggered, stack trace follows", e); LoggerFactory.getLogger(LeakTask.class).warn("Connection leak detection triggered, stack trace follows", e);
@ -51,8 +50,7 @@ class LeakTask extends TimerTask
public boolean cancel() public boolean cancel()
{ {
boolean cancelled = super.cancel(); boolean cancelled = super.cancel();
if (cancelled) if (cancelled) {
{
stackTrace = null; stackTrace = null;
} }
return cancelled; return cancelled;

@ -40,12 +40,10 @@ public abstract class PreparedStatementProxy extends StatementProxy implements P
@Override @Override
public final ResultSet executeQuery() throws SQLException public final ResultSet executeQuery() throws SQLException
{ {
try try {
{
return ((PreparedStatement) delegate).executeQuery(); return ((PreparedStatement) delegate).executeQuery();
} }
catch (SQLException e) catch (SQLException e) {
{
connection.checkException(e); connection.checkException(e);
throw e; throw e;
} }

@ -48,7 +48,8 @@ public final class ProxyFactory
* @param defaultCatalog the default catalog of the underlying {@link Connection} * @param defaultCatalog the default catalog of the underlying {@link Connection}
* @return a proxy that wraps the specified {@link Connection} * @return a proxy that wraps the specified {@link Connection}
*/ */
public static IHikariConnectionProxy getProxyConnection(HikariPool pool, Connection connection, long maxLifeTime, int defaultIsolationLevel, boolean defaultAutoCommit, boolean defaultIReadOnly, String defaultCatalog) public static IHikariConnectionProxy getProxyConnection(HikariPool pool, Connection connection, long maxLifeTime, int defaultIsolationLevel,
boolean defaultAutoCommit, boolean defaultIReadOnly, String defaultCatalog)
{ {
// Body is injected by JavassistProxyFactory // Body is injected by JavassistProxyFactory
return null; return null;

@ -52,20 +52,17 @@ public abstract class StatementProxy implements Statement
@Override @Override
public final void close() throws SQLException public final void close() throws SQLException
{ {
if (isClosed) if (isClosed) {
{
return; return;
} }
isClosed = true; isClosed = true;
connection.untrackStatement(this); connection.untrackStatement(this);
try try {
{
delegate.close(); delegate.close();
} }
catch (SQLException e) catch (SQLException e) {
{
connection.checkException(e); connection.checkException(e);
throw e; throw e;
} }
@ -75,12 +72,10 @@ public abstract class StatementProxy implements Statement
@Override @Override
public final ResultSet executeQuery(String sql) throws SQLException public final ResultSet executeQuery(String sql) throws SQLException
{ {
try try {
{
return delegate.executeQuery(sql); return delegate.executeQuery(sql);
} }
catch (SQLException e) catch (SQLException e) {
{
connection.checkException(e); connection.checkException(e);
throw e; throw e;
} }
@ -90,12 +85,10 @@ public abstract class StatementProxy implements Statement
@Override @Override
public final ResultSet getResultSet() throws SQLException public final ResultSet getResultSet() throws SQLException
{ {
try try {
{
return delegate.getResultSet(); return delegate.getResultSet();
} }
catch (SQLException e) catch (SQLException e) {
{
connection.checkException(e); connection.checkException(e);
throw e; throw e;
} }
@ -105,12 +98,10 @@ public abstract class StatementProxy implements Statement
@Override @Override
public final ResultSet getGeneratedKeys() throws SQLException public final ResultSet getGeneratedKeys() throws SQLException
{ {
try try {
{
return delegate.getGeneratedKeys(); return delegate.getGeneratedKeys();
} }
catch (SQLException e) catch (SQLException e) {
{
connection.checkException(e); connection.checkException(e);
throw e; throw e;
} }
@ -127,8 +118,7 @@ public abstract class StatementProxy implements Statement
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public final <T> T unwrap(Class<T> iface) throws SQLException public final <T> T unwrap(Class<T> iface) throws SQLException
{ {
if (iface.isInstance(delegate)) if (iface.isInstance(delegate)) {
{
return (T) delegate; return (T) delegate;
} }

@ -33,8 +33,7 @@ public final class ClassLoaderUtils
public static ClassLoader getClassLoader() public static ClassLoader getClassLoader()
{ {
ClassLoader cl = Thread.currentThread().getContextClassLoader(); ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) if (cl != null) {
{
return new CascadingClassLoader(cl); return new CascadingClassLoader(cl);
} }
return ClassLoaderUtils.class.getClassLoader(); return ClassLoaderUtils.class.getClassLoader();
@ -43,8 +42,7 @@ public final class ClassLoaderUtils
public static Class<?> loadClass(String className) throws ClassNotFoundException public static Class<?> loadClass(String className) throws ClassNotFoundException
{ {
ClassLoader cl = Thread.currentThread().getContextClassLoader(); ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) if (cl != null) {
{
return new CascadingClassLoader(cl).loadClass(className); return new CascadingClassLoader(cl).loadClass(className);
} }
@ -54,21 +52,17 @@ public final class ClassLoaderUtils
public static Set<Class<?>> getAllInterfaces(Class<?> clazz) public static Set<Class<?>> getAllInterfaces(Class<?> clazz)
{ {
Set<Class<?>> interfaces = new HashSet<Class<?>>(); Set<Class<?>> interfaces = new HashSet<Class<?>>();
for (Class<?> intf : Arrays.asList(clazz.getInterfaces())) for (Class<?> intf : Arrays.asList(clazz.getInterfaces())) {
{ if (intf.getInterfaces().length > 0) {
if (intf.getInterfaces().length > 0)
{
interfaces.addAll(getAllInterfaces(intf)); interfaces.addAll(getAllInterfaces(intf));
} }
interfaces.add(intf); interfaces.add(intf);
} }
if (clazz.getSuperclass() != null) if (clazz.getSuperclass() != null) {
{
interfaces.addAll(getAllInterfaces(clazz.getSuperclass())); interfaces.addAll(getAllInterfaces(clazz.getSuperclass()));
} }
if (clazz.isInterface()) if (clazz.isInterface()) {
{
interfaces.add(clazz); interfaces.add(clazz);
} }
@ -87,12 +81,10 @@ public final class ClassLoaderUtils
@Override @Override
protected Class<?> findClass(String name) throws ClassNotFoundException protected Class<?> findClass(String name) throws ClassNotFoundException
{ {
try try {
{
return contextLoader.loadClass(name); return contextLoader.loadClass(name);
} }
catch (ClassNotFoundException cnfe) catch (ClassNotFoundException cnfe) {
{
return CascadingClassLoader.class.getClassLoader().loadClass(name); return CascadingClassLoader.class.getClassLoader().loadClass(name);
} }
} }

@ -101,19 +101,15 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
{ {
// Try the thread-local list first // Try the thread-local list first
FastList<WeakReference<T>> list = threadList.get(); FastList<WeakReference<T>> list = threadList.get();
if (list == null) if (list == null) {
{
list = new FastList<WeakReference<T>>(WeakReference.class); list = new FastList<WeakReference<T>>(WeakReference.class);
threadList.set(list); threadList.set(list);
} }
else else {
{ for (int i = list.size() - 1; i >= 0; i--) {
for (int i = list.size() - 1; i >= 0; i--)
{
final WeakReference<T> reference = list.removeLast(); final WeakReference<T> reference = list.removeLast();
final T element = reference.get(); final T element = reference.get();
if (element != null && element.compareAndSetState(STATE_NOT_IN_USE, STATE_IN_USE)) if (element != null && element.compareAndSetState(STATE_NOT_IN_USE, STATE_IN_USE)) {
{
return element; return element;
} }
} }
@ -123,23 +119,21 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
timeout = timeUnit.toNanos(timeout); timeout = timeUnit.toNanos(timeout);
do { do {
final long startScan = System.nanoTime(); final long startScan = System.nanoTime();
for (T reference : sharedList) for (T reference : sharedList) {
{ if (reference.compareAndSetState(STATE_NOT_IN_USE, STATE_IN_USE)) {
if (reference.compareAndSetState(STATE_NOT_IN_USE, STATE_IN_USE))
{
return reference; return reference;
} }
} }
if (listener != null) if (listener != null) {
{
listener.addBagItem(); listener.addBagItem();
} }
synchronizer.tryAcquireSharedNanos(startScan, timeout); synchronizer.tryAcquireSharedNanos(startScan, timeout);
timeout -= (System.nanoTime() - startScan); timeout -= (System.nanoTime() - startScan);
} while (timeout > 0); }
while (timeout > 0);
return null; return null;
} }
@ -155,16 +149,13 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
*/ */
public void requite(final T value) public void requite(final T value)
{ {
if (value == null) if (value == null) {
{
throw new NullPointerException("Cannot return a null value to the bag"); throw new NullPointerException("Cannot return a null value to the bag");
} }
if (value.compareAndSetState(STATE_IN_USE, STATE_NOT_IN_USE)) if (value.compareAndSetState(STATE_IN_USE, STATE_NOT_IN_USE)) {
{
FastList<WeakReference<T>> list = threadList.get(); FastList<WeakReference<T>> list = threadList.get();
if (list == null) if (list == null) {
{
list = new FastList<WeakReference<T>>(WeakReference.class); list = new FastList<WeakReference<T>>(WeakReference.class);
threadList.set(list); threadList.set(list);
} }
@ -172,8 +163,7 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
list.add(new WeakReference<T>(value)); list.add(new WeakReference<T>(value));
synchronizer.releaseShared(System.nanoTime()); synchronizer.releaseShared(System.nanoTime());
} }
else else {
{
throw new IllegalStateException("Value was returned to the bag that was not borrowed: "); throw new IllegalStateException("Value was returned to the bag that was not borrowed: ");
} }
} }
@ -199,15 +189,12 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
*/ */
public void remove(T value) public void remove(T value)
{ {
if (value.compareAndSetState(STATE_IN_USE, STATE_REMOVED) || value.compareAndSetState(STATE_RESERVED, STATE_REMOVED)) if (value.compareAndSetState(STATE_IN_USE, STATE_REMOVED) || value.compareAndSetState(STATE_RESERVED, STATE_REMOVED)) {
{ if (!sharedList.remove(value)) {
if (!sharedList.remove(value))
{
throw new IllegalStateException("Attempt to remove an object from the bag that does not exist"); throw new IllegalStateException("Attempt to remove an object from the bag that does not exist");
} }
} }
else else {
{
throw new IllegalStateException("Attempt to remove an object from the bag that was not borrowed or reserved"); throw new IllegalStateException("Attempt to remove an object from the bag that was not borrowed or reserved");
} }
} }
@ -224,12 +211,9 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
public List<T> values(int state) public List<T> values(int state)
{ {
ArrayList<T> list = new ArrayList<T>(sharedList.size()); ArrayList<T> list = new ArrayList<T>(sharedList.size());
if (state == STATE_IN_USE || state == STATE_NOT_IN_USE) if (state == STATE_IN_USE || state == STATE_NOT_IN_USE) {
{ for (T reference : sharedList) {
for (T reference : sharedList) if (reference.getState() == state) {
{
if (reference.getState() == state)
{
list.add(reference); list.add(reference);
} }
} }
@ -263,8 +247,7 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
public void unreserve(T value) public void unreserve(T value)
{ {
final long checkInTime = System.nanoTime(); final long checkInTime = System.nanoTime();
if (!value.compareAndSetState(STATE_RESERVED, STATE_NOT_IN_USE)) if (!value.compareAndSetState(STATE_RESERVED, STATE_NOT_IN_USE)) {
{
throw new IllegalStateException("Attempt to relinquish an object to the bag that was not reserved"); throw new IllegalStateException("Attempt to relinquish an object to the bag that was not reserved");
} }
@ -296,10 +279,8 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
public int getCount(int state) public int getCount(int state)
{ {
int count = 0; int count = 0;
for (T reference : sharedList) for (T reference : sharedList) {
{ if (reference.getState() == state) {
if (reference.getState() == state)
{
count++; count++;
} }
} }
@ -324,15 +305,12 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
private static final long serialVersionUID = 104753538004341218L; private static final long serialVersionUID = 104753538004341218L;
private static final boolean JAVA7; private static final boolean JAVA7;
static static {
{
boolean b = false; boolean b = false;
try try {
{
b = AbstractQueuedLongSynchronizer.class.getMethod("hasQueuedPredecessors", new Class<?>[0]) != null; b = AbstractQueuedLongSynchronizer.class.getMethod("hasQueuedPredecessors", new Class<?>[0]) != null;
} }
catch (Exception e) catch (Exception e) {
{
} }
JAVA7 = b; JAVA7 = b;
@ -355,8 +333,7 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
private boolean java67hasQueuedPredecessors() private boolean java67hasQueuedPredecessors()
{ {
if (JAVA7) if (JAVA7) {
{
return hasQueuedPredecessors(); return hasQueuedPredecessors();
} }

@ -33,27 +33,22 @@ public final class DriverDataSource implements DataSource
public DriverDataSource(String jdbcUrl, Properties properties, String username, String password) public DriverDataSource(String jdbcUrl, Properties properties, String username, String password)
{ {
try try {
{
this.jdbcUrl = jdbcUrl; this.jdbcUrl = jdbcUrl;
this.driverProperties = new Properties(properties); this.driverProperties = new Properties(properties);
if (username != null) if (username != null) {
{
driverProperties.put("user", driverProperties.getProperty("user", username)); driverProperties.put("user", driverProperties.getProperty("user", username));
} }
if (password != null) if (password != null) {
{
driverProperties.put("password", driverProperties.getProperty("password", password)); driverProperties.put("password", driverProperties.getProperty("password", password));
} }
if (DriverManager.getDriver(jdbcUrl) == null) if (DriverManager.getDriver(jdbcUrl) == null) {
{
throw new IllegalArgumentException("DriverManager was unable to load driver for URL " + jdbcUrl); throw new IllegalArgumentException("DriverManager was unable to load driver for URL " + jdbcUrl);
} }
} }
catch (SQLException e) catch (SQLException e) {
{ throw new RuntimeException("Unable to get driver for JDBC URL " + jdbcUrl);
throw new RuntimeException("Unable to get driver for JDBC URL "+ jdbcUrl);
} }
} }

@ -18,7 +18,6 @@ package com.zaxxer.hikari.util;
import java.lang.reflect.Array; import java.lang.reflect.Array;
/** /**
* Fast list without range checking. * Fast list without range checking.
* *
@ -57,12 +56,10 @@ public final class FastList<T>
*/ */
public void add(T element) public void add(T element)
{ {
try try {
{
elementData[size++] = element; elementData[size++] = element;
} }
catch (ArrayIndexOutOfBoundsException e) catch (ArrayIndexOutOfBoundsException e) {
{
// overflow-conscious code // overflow-conscious code
final int oldCapacity = elementData.length; final int oldCapacity = elementData.length;
final int newCapacity = oldCapacity << 1; final int newCapacity = oldCapacity << 1;
@ -108,13 +105,10 @@ public final class FastList<T>
*/ */
public void remove(T element) public void remove(T element)
{ {
for (int index = size - 1; index >= 0; index--) for (int index = size - 1; index >= 0; index--) {
{ if (element == elementData[index]) {
if (element == elementData[index])
{
final int numMoved = size - index - 1; final int numMoved = size - index - 1;
if (numMoved > 0) if (numMoved > 0) {
{
System.arraycopy(elementData, index + 1, elementData, index, numMoved); System.arraycopy(elementData, index + 1, elementData, index, numMoved);
} }
elementData[--size] = null; elementData[--size] = null;
@ -128,15 +122,13 @@ public final class FastList<T>
*/ */
public void clear() public void clear()
{ {
for (int i = 0; i < size; i++) for (int i = 0; i < size; i++) {
{
elementData[i] = null; elementData[i] = null;
} }
size = 0; size = 0;
} }
/** /**
* Get the current number of elements in the FastList. * Get the current number of elements in the FastList.
* *

@ -14,15 +14,12 @@ public final class PoolUtilities
{ {
public static final boolean IS_JAVA7; public static final boolean IS_JAVA7;
static static {
{
boolean b = false; boolean b = false;
try try {
{
b = AbstractQueuedLongSynchronizer.class.getMethod("hasQueuedPredecessors", new Class<?>[0]) != null; b = AbstractQueuedLongSynchronizer.class.getMethod("hasQueuedPredecessors", new Class<?>[0]) != null;
} }
catch (Exception e) catch (Exception e) {
{
} }
IS_JAVA7 = b; IS_JAVA7 = b;
@ -30,14 +27,11 @@ public final class PoolUtilities
public static void quietlyCloseConnection(Connection connection) public static void quietlyCloseConnection(Connection connection)
{ {
if (connection != null) if (connection != null) {
{ try {
try
{
connection.close(); connection.close();
} }
catch (SQLException e) catch (SQLException e) {
{
return; return;
} }
} }
@ -63,16 +57,13 @@ public final class PoolUtilities
*/ */
public static void executeSqlAutoCommit(Connection connection, String sql) throws SQLException public static void executeSqlAutoCommit(Connection connection, String sql) throws SQLException
{ {
if (sql != null) if (sql != null) {
{
connection.setAutoCommit(true); connection.setAutoCommit(true);
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
try try {
{
statement.execute(sql); statement.execute(sql);
} }
finally finally {
{
statement.close(); statement.close();
} }
} }
@ -80,44 +71,37 @@ public final class PoolUtilities
public static void quietlySleep(long millis) public static void quietlySleep(long millis)
{ {
try try {
{
Thread.sleep(millis); Thread.sleep(millis);
} }
catch (InterruptedException e) catch (InterruptedException e) {
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T createInstance(String className, Class<T> clazz, Object...args) public static <T> T createInstance(String className, Class<T> clazz, Object... args)
{
if (className == null)
{ {
if (className == null) {
return null; return null;
} }
try try {
{
Class<?> loaded = PoolUtilities.class.getClassLoader().loadClass(className); Class<?> loaded = PoolUtilities.class.getClassLoader().loadClass(className);
Class<?>[] argClasses = new Class<?>[args.length]; Class<?>[] argClasses = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) for (int i = 0; i < args.length; i++) {
{
argClasses[i] = args[i].getClass(); argClasses[i] = args[i].getClass();
} }
if (args.length > 0) if (args.length > 0) {
{
Constructor<?> constructor = loaded.getConstructor(argClasses); Constructor<?> constructor = loaded.getConstructor(argClasses);
return (T) constructor.newInstance(args); return (T) constructor.newInstance(args);
} }
return (T) loaded.newInstance(); return (T) loaded.newInstance();
} }
catch (Exception e) catch (Exception e) {
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -135,7 +119,8 @@ public final class PoolUtilities
int processors = Math.max(1, Runtime.getRuntime().availableProcessors() / 2); int processors = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(queueSize); LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(queueSize);
ThreadPoolExecutor executor = new ThreadPoolExecutor(processors, processors, 2, TimeUnit.SECONDS, queue, threadFactory, new ThreadPoolExecutor.DiscardPolicy()); ThreadPoolExecutor executor = new ThreadPoolExecutor(processors, processors, 2, TimeUnit.SECONDS, queue, threadFactory,
new ThreadPoolExecutor.DiscardPolicy());
executor.allowCoreThreadTimeOut(true); executor.allowCoreThreadTimeOut(true);
return executor; return executor;
} }

@ -42,23 +42,19 @@ public final class PropertyBeanSetter
public static void setTargetFromProperties(Object target, Properties properties) public static void setTargetFromProperties(Object target, Properties properties)
{ {
if (target == null || properties == null) if (target == null || properties == null) {
{
return; return;
} }
for (Entry<Object, Object> propEntry : properties.entrySet()) for (Entry<Object, Object> propEntry : properties.entrySet()) {
{
String propName = propEntry.getKey().toString(); String propName = propEntry.getKey().toString();
Object propValue = propEntry.getValue(); Object propValue = propEntry.getValue();
if (target instanceof HikariConfig && propName.startsWith("dataSource.")) if (target instanceof HikariConfig && propName.startsWith("dataSource.")) {
{
HikariConfig config = (HikariConfig) target; HikariConfig config = (HikariConfig) target;
config.addDataSourceProperty(propName.substring("dataSource.".length()), propValue); config.addDataSourceProperty(propName.substring("dataSource.".length()), propValue);
} }
else else {
{
setProperty(target, propName, propValue); setProperty(target, propName, propValue);
} }
} }
@ -73,43 +69,35 @@ public final class PropertyBeanSetter
public static Set<String> getPropertyNames(Class<?> targetClass) public static Set<String> getPropertyNames(Class<?> targetClass)
{ {
HashSet<String> set = new HashSet<String>(); HashSet<String> set = new HashSet<String>();
try try {
{
BeanInfo info = Introspector.getBeanInfo(targetClass); BeanInfo info = Introspector.getBeanInfo(targetClass);
for (PropertyDescriptor descr : info.getPropertyDescriptors()) for (PropertyDescriptor descr : info.getPropertyDescriptors()) {
{ if (!"class".equals(descr.getName())) {
if (!"class".equals(descr.getName()))
{
set.add(descr.getName()); set.add(descr.getName());
} }
} }
return set; return set;
} }
catch (IntrospectionException e) catch (IntrospectionException e) {
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static Object getProperty(String propName, Object target) public static Object getProperty(String propName, Object target)
{ {
try try {
{
String capitalized = "get" + propName.substring(0, 1).toUpperCase() + propName.substring(1); String capitalized = "get" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
Method method = target.getClass().getMethod(capitalized); Method method = target.getClass().getMethod(capitalized);
return method.invoke(target); return method.invoke(target);
} }
catch (Exception e) catch (Exception e) {
{ try {
try
{
String capitalized = "is" + propName.substring(0, 1).toUpperCase() + propName.substring(1); String capitalized = "is" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
Method method = target.getClass().getMethod(capitalized); Method method = target.getClass().getMethod(capitalized);
return method.invoke(target); return method.invoke(target);
} }
catch (Exception e2) catch (Exception e2) {
{
return null; return null;
} }
} }
@ -119,51 +107,40 @@ public final class PropertyBeanSetter
{ {
String capitalized = "set" + propName.substring(0, 1).toUpperCase() + propName.substring(1); String capitalized = "set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
PropertyDescriptor propertyDescriptor; PropertyDescriptor propertyDescriptor;
try try {
{
propertyDescriptor = new PropertyDescriptor(propName, target.getClass(), null, capitalized); propertyDescriptor = new PropertyDescriptor(propName, target.getClass(), null, capitalized);
} }
catch (IntrospectionException e) catch (IntrospectionException e) {
{
capitalized = "set" + propName.toUpperCase(); capitalized = "set" + propName.toUpperCase();
try try {
{
propertyDescriptor = new PropertyDescriptor(propName, target.getClass(), null, capitalized); propertyDescriptor = new PropertyDescriptor(propName, target.getClass(), null, capitalized);
} }
catch (IntrospectionException e1) catch (IntrospectionException e1) {
{
LOGGER.error("Property {} is does not exist on target class {}", propName, target.getClass()); LOGGER.error("Property {} is does not exist on target class {}", propName, target.getClass());
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
try try {
{
Method writeMethod = propertyDescriptor.getWriteMethod(); Method writeMethod = propertyDescriptor.getWriteMethod();
Class<?> paramClass = writeMethod.getParameterTypes()[0]; Class<?> paramClass = writeMethod.getParameterTypes()[0];
if (paramClass == int.class) if (paramClass == int.class) {
{
writeMethod.invoke(target, Integer.parseInt(propValue.toString())); writeMethod.invoke(target, Integer.parseInt(propValue.toString()));
} }
else if (paramClass == long.class) else if (paramClass == long.class) {
{
writeMethod.invoke(target, Long.parseLong(propValue.toString())); writeMethod.invoke(target, Long.parseLong(propValue.toString()));
} }
else if (paramClass == boolean.class) else if (paramClass == boolean.class) {
{
writeMethod.invoke(target, Boolean.parseBoolean(propValue.toString())); writeMethod.invoke(target, Boolean.parseBoolean(propValue.toString()));
} }
else if (paramClass == String.class) else if (paramClass == String.class) {
{
writeMethod.invoke(target, propValue.toString()); writeMethod.invoke(target, propValue.toString());
} }
else else {
{
writeMethod.invoke(target, propValue); writeMethod.invoke(target, propValue);
} }
} }
catch (Exception e) catch (Exception e) {
{
LOGGER.error("Exception setting property {} on target class {}", propName, target.getClass(), e); LOGGER.error("Exception setting property {} on target class {}", propName, target.getClass(), e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }

Loading…
Cancel
Save