ClasspathHandler.kt

  1. package com.hexagontk.core

  2. import java.net.URL
  3. import java.net.URLConnection
  4. import java.net.URLStreamHandler

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

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

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

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