Skip to content

Instantly share code, notes, and snippets.

@shkhln
Last active February 4, 2021 07:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shkhln/b8ee1f6d2930da11f2d2de262fafa987 to your computer and use it in GitHub Desktop.
Save shkhln/b8ee1f6d2930da11f2d2de262fafa987 to your computer and use it in GitHub Desktop.
import javax.inject.Inject
import scala.concurrent.Future
import play.api.{Configuration, Environment, Mode}
import play.api.inject.{ApplicationLifecycle, Binding, Module}
class DevModeWorkaroundsModule extends Module {
def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
Seq(bind[DevModeWorkarounds].toSelf.eagerly())
}
}
import java.lang.reflect.Field
import java.lang.reflect.Modifier
class DevModeWorkarounds @Inject()(env: Environment, lifecycle: ApplicationLifecycle) {
def newInstance[T](_class: Class[T]): T = {
val ctr = _class.getDeclaredConstructor()
ctr.setAccessible(true)
ctr.newInstance()
}
def getDeclaredField(_class: Class[_], name: String): Field = {
try {
_class.getDeclaredField(name)
} catch {
case ex: NoSuchFieldException =>
if (_class.getSuperclass != null) {
getDeclaredField(_class.getSuperclass, name)
} else {
throw ex
}
}
}
def getStaticFieldValue[R](_class: Class[_], name: String): R = {
val f = getDeclaredField(_class, name)
f.setAccessible(true)
f.get(null).asInstanceOf[R]
}
def getFieldValue[R](instance: AnyRef, name: String): R = {
val f = getDeclaredField(instance.getClass, name)
f.setAccessible(true)
f.get(instance).asInstanceOf[R]
}
val modifiers = classOf[Field].getDeclaredField("modifiers")
modifiers.setAccessible(true)
def setStaticFieldValue(_class: Class[_], name: String, value: Any): Unit = {
val f = getDeclaredField(_class, name)
if (Modifier.isFinal(f.getModifiers)) {
modifiers.setInt(f, f.getModifiers & ~Modifier.FINAL)
}
f.setAccessible(true)
f.set(null, value)
}
def setFieldValue(instance: AnyRef, name: String, value: Any): Unit = {
val f = getDeclaredField(instance.getClass, name)
if (Modifier.isFinal(f.getModifiers)) {
modifiers.setInt(f, f.getModifiers & ~Modifier.FINAL)
}
f.setAccessible(true)
f.set(instance, value)
}
if (env.mode == Mode.Dev) {
// Jackson
{
import com.fasterxml.jackson.databind.`type`.TypeFactory
import com.fasterxml.jackson.databind.util.LRUMap
import com.fasterxml.jackson.module.scala.introspect.ScalaAnnotationIntrospector
lifecycle.addStopHook { () =>
TypeFactory.defaultInstance().clearCache()
getFieldValue[LRUMap[_, _]](ScalaAnnotationIntrospector, "_descriptorCache").clear()
Future.successful(())
}
}
// Logback
{
import scala.jdk.CollectionConverters._
import ch.qos.logback.classic.{AsyncAppender, Logger, LoggerContext}
val ctx = org.slf4j.LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext]
for (logger <- ctx.getLoggerList.asScala) {
val it = logger.asInstanceOf[Logger].iteratorForAppenders
while (it.hasNext) {
val appender = it.next
if (appender.isInstanceOf[AsyncAppender]) {
getFieldValue[Thread](appender, "worker").setContextClassLoader(null)
}
}
}
}
// Netty
{
setStaticFieldValue(classOf[org.jboss.netty.channel.DefaultChannelFuture], "CANCELLED", new Throwable())
}
// Netty again
{
import java.util.concurrent.CancellationException
import play.shaded.ahc.io.netty.util.concurrent.{DefaultPromise, GlobalEventExecutor, ImmediateEventExecutor}
import play.shaded.ahc.io.netty.util.internal.ThrowableUtil
setStaticFieldValue(classOf[GlobalEventExecutor], "INSTANCE", newInstance(classOf[GlobalEventExecutor]))
setStaticFieldValue(classOf[ImmediateEventExecutor], "INSTANCE", newInstance(classOf[ImmediateEventExecutor]))
val causeHolder = getStaticFieldValue[Object](classOf[DefaultPromise[_]], "CANCELLATION_CAUSE_HOLDER")
val throwable = ThrowableUtil.unknownStackTrace(
new CancellationException(), classOf[DefaultPromise[_]], "cancel(...)")
setFieldValue(causeHolder, "cause", throwable)
}
// Ebean
{
import java.util.concurrent.ConcurrentMap
import io.ebeaninternal.server.deploy.parse.AnnotationBase
import io.ebeaninternal.server.lib.ShutdownManager
val shutdownHook = getStaticFieldValue[Thread](classOf[ShutdownManager], "shutdownHook")
shutdownHook.setContextClassLoader(null)
lifecycle.addStopHook { () =>
System.setProperty("ebean.datasource.deregisterAllDrivers", "true")
io.ebean.EbeanServerFactory.shutdown()
System.clearProperty("ebean.datasource.deregisterAllDrivers")
//val valueMethods = getStaticFieldValue[ConcurrentMap[_, _]](classOf[AnnotationBase], "valueMethods")
//valueMethods.clear()
Future.successful(())
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment