Skip to content

Instantly share code, notes, and snippets.

@andaag
Last active December 14, 2017 12:06
Show Gist options
  • Save andaag/ee02753549c910ba6ea5ad4b27262682 to your computer and use it in GitHub Desktop.
Save andaag/ee02753549c910ba6ea5ad4b27262682 to your computer and use it in GitHub Desktop.
package com.schibsted.mp.ads.sales
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded
import org.jetbrains.spek.api.dsl.Spec
import org.jetbrains.spek.api.lifecycle.CachingMode
import org.jetbrains.spek.api.lifecycle.LifecycleAware
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.Locale
fun Spec.embeddedDynamodb(): LifecycleAware<AmazonDynamoDB> {
return memoized(CachingMode.GROUP) {
copyNativeLibraries()
addLibraryPath("build/nativelibs")
val amazonDynamoDb = DynamoDBEmbedded.create().amazonDynamoDB()
afterGroup {
amazonDynamoDb.shutdown()
}
amazonDynamoDb
}
}
fun addLibraryPath(pathToAdd: String) {
val usrPathsField = ClassLoader::class.java.getDeclaredField("usr_paths")
usrPathsField.isAccessible = true
//get array of paths
@Suppress("UNCHECKED_CAST")
val paths = usrPathsField.get(null) as Array<String>
//check if the path to add is already present
paths.filter { it == pathToAdd }.forEach { return }
//add the new path
val newPaths = Arrays.copyOf(paths, paths.size + 1)
newPaths[newPaths.size - 1] = pathToAdd
usrPathsField.set(null, newPaths)
}
private fun copyNativeLibraries() {
val classPath = System.getProperty("java.class.path", ".")
val classPathElements = classPath
.split(System.getProperty("path.separator")
.toRegex())
.dropLastWhile { it.isEmpty() }.toTypedArray()
File("build/nativelibs").mkdirs()
for (element in classPathElements) {
val filename = element.toLowerCase(Locale.UK)
if (filename.contains("sqlite4java") && (filename.endsWith("dll") || filename.endsWith("so") || filename.endsWith("dylib"))) {
val input = Paths.get(File(element).toURI())
val output = Paths.get(File("build/nativelibs", File(element).name).toURI())
Files.copy(input, output)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment