'How to conditionally load specific libraries depending on OS?

I am loading a netty library depending if I am in development or production server (OSX versus linux)

val nettyEpoll        = "io.netty"                   % "netty-transport-native-epoll"  % nettyVersion classifier "linux-x86_64"
  val nettyKqueue       = "io.netty"                   % "netty-transport-native-kqueue" % nettyVersion classifier "osx-x86_64"

Now in my code how would I load the correct class depending on the OS that is currently running?

In my code I have:

  val workerGroup =
      new KQueueEventLoopGroup

If this is linux I need to load NioEventLoopGroup.

Is there a way to load the correct one when I create a production build?

If I build on my OSX laptop, is there a way to tell the compiler to build for linux?



Solution 1:[1]

For checking OS version in your code, you can use java function System.getProperty("os.name"), somthing like

def getWorkerGroup(): EventLoopGroup = {
    System.getProperty("os.name").toLowerCase match {
        case mac if mac.contains("mac")  => new KQueueEventLoopGroup()
        case linux if linux.contains("linux") => new NioEventLoopGroup()
  }
}

In sbt build, you can use same function to select library to use:

val configureDependencyByPlatform = settingKey[ModuleID]("Dynamically change reference to the jars dependency depending on the platform")
configureDependencyByPlatform := {
  System.getProperty("os.name").toLowerCase match {
    case mac if mac.contains("mac")  => "org.example" %% "somelib-mac" % "1.0.0"
    case linux if linux.contains("linux") => "org.example" %% "somelib-linux" % "1.0.0"
    case osName => throw new RuntimeException(s"Unknown operating system $osName")
  }
}

If you want to manually select, which build you need, you can add some kind of optional parameter, and check it before getting os.name.

Solution 2:[2]

we can use Apache lang dependency to decide which OS you're running programmatically through Java by importing org.apache.commons.lang3.SystemUtils; and we can put condition as per our need for example: SystemUtils.IS_OS_WINDOWS .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sanjay Gupta