Skip to content

Instantly share code, notes, and snippets.

@crypticmind
Last active June 25, 2018 14:06
Show Gist options
  • Save crypticmind/720992c0ae121ed82879 to your computer and use it in GitHub Desktop.
Save crypticmind/720992c0ae121ed82879 to your computer and use it in GitHub Desktop.
This is a custom name service for the JVM so you can add your own entries during testing of a web service/app.
package misc
import java.net.{InetAddress, UnknownHostException}
import java.util.concurrent.ConcurrentHashMap
import sun.net.spi.nameservice.{NameService, NameServiceDescriptor}
class CustomNameService extends NameService {
override def lookupAllHostAddr(s: String): Array[InetAddress] =
Option(CustomNameService.overrides.get(s))
.map(a => Array(a))
.getOrElse(throw new UnknownHostException)
def getHostByAddr(bytes: Array[Byte]) = throw new UnknownHostException
}
object CustomNameService {
val overrides = new ConcurrentHashMap[String, InetAddress]()
}
class CustomNameServiceDescriptor extends NameServiceDescriptor {
val getType = "dns"
val getProviderName = "custom"
def createNameService(): NameService = {
println("Creating new CustomNameService")
new CustomNameService
}
}
object Test extends App {
CustomNameService.overrides.put("whatever", InetAddress.getByAddress("whatever", InetAddress.getLoopbackAddress.getAddress))
println(InetAddress.getByName("whatever"))
println(InetAddress.getByName("www.google.com"))
}
@crypticmind
Copy link
Author

This is activated with:

-Dsun.net.spi.nameservice.provider.1=dns,custom
-Dsun.net.spi.nameservice.provider.2=default

The file sun.net.spi.nameservice.NameServiceDescriptor must be located in META-INF/services

@stokito
Copy link

stokito commented Jun 25, 2018

FYI: it will stop to work in JDK9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment