Last active
June 25, 2018 14:06
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
misc.CustomNameServiceDescriptor |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Test extends App { | |
CustomNameService.overrides.put("whatever", InetAddress.getByAddress("whatever", InetAddress.getLoopbackAddress.getAddress)) | |
println(InetAddress.getByName("whatever")) | |
println(InetAddress.getByName("www.google.com")) | |
} |
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
This is activated with:
The file
sun.net.spi.nameservice.NameServiceDescriptor
must be located in META-INF/services