SNRK-83: changed decomposition and moved main to test/

This commit is contained in:
Anton Belyi 2023-05-05 15:24:01 +03:00
parent b4423e8bba
commit ff7b02d98a
2 changed files with 67 additions and 48 deletions

View File

@ -11,6 +11,7 @@ import io.ktor.server.response.*
import io.ktor.server.http.content.*
import kotlinx.html.*
import io.ktor.server.routing.*
import kotlinx.css.html
import java.nio.file.Path
import space.kscience.snark.storage.Directory
import space.kscience.snark.storage.local.localStorage
@ -24,11 +25,13 @@ public interface DataHolder {
fun init() : Directory
fun represent(): String
//will be HTML later
}
class LocalDataHolder: DataHolder {
private var source: Path? = null
private var response: String = ""
override fun init(): Directory {
source?.toFile()?.deleteRecursively()
source = createTempDirectory()
return localStorage(source!!)
}
@ -50,11 +53,29 @@ class LocalDataHolder: DataHolder {
response
}
}
fun main() {
val dataHolder: DataHolder = LocalDataHolder()
embeddedServer(Netty, 9090) {
routing {
get("/") {
public class SNARKServer(val dataHolder: DataHolder, val port: Int): Runnable {
private suspend fun renderGet(call: ApplicationCall) {
call.respondText(dataHolder.represent())
}
private suspend fun renderUpload(call: ApplicationCall) {
val multipartData = call.receiveMultipart()
val tmp = createTempFile(suffix=".zip")
multipartData.forEachPart { part ->
when (part) {
is PartData.FileItem -> {
val fileBytes = part.streamProvider().readBytes()
tmp.writeBytes(fileBytes)
}
else -> {
}
}
part.dispose()
}
unzip(tmp.toPath().toString(), dataHolder.init())
call.respondText("File is successfully uploaded")
}
private suspend fun renderMainPage(call: ApplicationCall) {
call.respondHtml(HttpStatusCode.OK) {
head {
title {
@ -82,26 +103,19 @@ fun main() {
}
}
}
override fun run() {
embeddedServer(Netty, port) {
routing {
get("/") {
renderMainPage(call)
}
post("/upload") {
val multipartData = call.receiveMultipart()
val tmp = createTempFile(suffix=".zip")
multipartData.forEachPart { part ->
when (part) {
is PartData.FileItem -> {
val fileBytes = part.streamProvider().readBytes()
tmp.writeBytes(fileBytes)
}
else -> {
}
}
part.dispose()
}
unzip(tmp.toPath().toString(), dataHolder.init())
call.respondText("File is successfully uploaded")
renderUpload(call)
}
get("/data") {
call.respondText(dataHolder.represent())
renderGet(call)
}
}
}.start(wait = true)
}
}

View File

@ -0,0 +1,5 @@
package space.kscience.snark.ktor
fun main() {
SNARKServer(LocalDataHolder(), 9090).run()
}