ClasspathHandler.kt

  1. package com.hexagonkt.core

  2. import com.hexagonkt.core.logging.logger
  3. import java.net.URL
  4. import java.net.URLConnection
  5. import java.net.URLStreamHandler

  6. object ClasspathHandler : URLStreamHandler() {
  7.     private val classLoader: ClassLoader by lazy { Thread.currentThread().contextClassLoader }
  8.     private val protocolHandlers: Map<String, URLStreamHandler> by lazy {
  9.         mapOf("classpath" to this)
  10.     }

  11.     override fun openConnection(url: URL): URLConnection =
  12.         classLoader.getResource(url.path)?.openConnection()
  13.             ?: throw ResourceNotFoundException("$url cannot be open")

  14.     fun registerHandler() {
  15.         try {
  16.             URL.setURLStreamHandlerFactory {
  17.                 createURLStreamHandler(it)
  18.             }
  19.         }
  20.         catch (e: Error) {
  21.             logger.error(e)
  22.         }
  23.     }

  24.     fun createURLStreamHandler(protocol: String): URLStreamHandler? {
  25.         return protocolHandlers[protocol]
  26.     }
  27. }