Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
monosoul committed Jul 14, 2022
1 parent e6aacd7 commit 7b75494
Showing 1 changed file with 12 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,9 @@ import org.testcontainers.containers.JdbcDatabaseContainer
import org.testcontainers.containers.output.Slf4jLogConsumer
import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy
import org.testcontainers.utility.DockerImageName
import java.lang.reflect.Field
import java.sql.Driver
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class GenericDatabaseContainer(
private val image: Image,
Expand All @@ -21,11 +18,7 @@ class GenericDatabaseContainer(
) : JdbcDatabaseContainer<GenericDatabaseContainer>(DockerImageName.parse(image.name)) {

private val driverLoadLock = ReentrantLock()
private var driver: Driver? by ReflectionDelegate(
JdbcDatabaseContainer::class.java.getDeclaredField("driver").also {
it.isAccessible = true
}
)
private var driver: Driver? = null

init {
withLogConsumer(
Expand Down Expand Up @@ -55,29 +48,23 @@ class GenericDatabaseContainer(
if (driver == null) {
driverLoadLock.withLock {
if (driver == null) {
return try {
@Suppress("DEPRECATION")
jdbcAwareClassLoader.loadClass(driverClassName).newInstance() as Driver
} catch (e: Exception) {
when (e) {
is InstantiationException, is IllegalAccessException, is ClassNotFoundException -> {
throw NoDriverFoundException("Could not get Driver", e)
}
else -> throw e
}
}.also {
driver = it
}
driver = getNewJdbcDriverInstance()
}
}
}

return driver!!
}

private class ReflectionDelegate<T>(private val field: Field) : ReadWriteProperty<Any, T> {
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: Any, property: KProperty<*>): T = field.get(thisRef) as T
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = field.set(thisRef, value)
private fun getNewJdbcDriverInstance() = try {
@Suppress("DEPRECATION")
jdbcAwareClassLoader.loadClass(driverClassName).newInstance() as Driver
} catch (e: Exception) {
when (e) {
is InstantiationException, is IllegalAccessException, is ClassNotFoundException -> {
throw NoDriverFoundException("Could not get Driver", e)
}
else -> throw e
}
}
}

0 comments on commit 7b75494

Please sign in to comment.