aboutsummaryrefslogtreecommitdiff
path: root/flow/src/main/scala/com/github/jodersky/flow/internal/NativeLoader.scala
blob: 034be966b36c6637dae16e911aeed2855485f5ed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.github.jodersky.flow.internal

import java.io.File
import java.io.FileOutputStream
import scalax.file.Path
import scalax.io.Resource
import scala.util.Try

/** Handles loading of the current platform's native library for flow. */
object NativeLoader {

  def extract(): Option[File] = {
    val os = System.getProperty("os.name").toLowerCase.filter(_ != ' ')
    val arch = System.getProperty("os.arch").toLowerCase
    val fqlib = System.mapLibraryName("flow") //fully qualified library name

    val in = NativeLoader.getClass().getResourceAsStream(s"/native/${arch}-${os}/${fqlib}")
    if (in == null) return None

    val temp = Path.createTempFile()
    Resource.fromInputStream(in).copyDataTo(temp)
    temp.fileOption
  }

  def loadFromJar() = extract() match {
    case Some(file) => System.load(file.getAbsolutePath)
    case None => throw new UnsatisfiedLinkError("cannot extract native library, the native library may not exist for your specific os/architecture combination")
  }

  def load = {
    try {
      System.loadLibrary("flow")
    } catch {
      case ex: UnsatisfiedLinkError => loadFromJar()
    }
  }

}