All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.javalin.json.PipedStreamUtil.kt Maven / Gradle / Ivy

There is a newer version: 6.3.0
Show newest version
package io.javalin.json

import io.javalin.util.ConcurrencyUtil
import io.javalin.util.javalinLazy
import java.io.InputStream
import java.io.PipedInputStream
import java.io.PipedOutputStream

object PipedStreamUtil {

    private val executorService by javalinLazy { ConcurrencyUtil.executorService("JavalinPipedStreamingThreadPool") }

    fun getInputStream(userCallback: (PipedOutputStream) -> Unit): InputStream {
        val pipedOutputStream = PipedOutputStream()
        val pipedInputStream = object : PipedInputStream(pipedOutputStream) {
            var exception: Exception? = null // possible exception from child thread
            override fun close() = exception?.let { throw it } ?: super.close()
        }
        executorService.execute { // start child thread, necessary to prevent deadlock
            try {
                userCallback(pipedOutputStream)
            } catch (userException: Exception) {
                pipedInputStream.exception = userException // pass exception to parent thead
            } finally {
                pipedOutputStream.close()
            }
        }
        return pipedInputStream
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy