diff --git a/lithic-java-core/src/main/kotlin/com/lithic/api/core/http/BinaryResponseContent.kt b/lithic-java-core/src/main/kotlin/com/lithic/api/core/http/BinaryResponseContent.kt new file mode 100644 index 00000000..5af28e8c --- /dev/null +++ b/lithic-java-core/src/main/kotlin/com/lithic/api/core/http/BinaryResponseContent.kt @@ -0,0 +1,15 @@ +package com.lithic.api.core.http + +import java.io.Closeable +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream + +interface BinaryResponseContent : Closeable { + + fun contentType(): String? + + fun body(): InputStream + + @Throws(IOException::class) fun writeTo(outputStream: OutputStream) +} diff --git a/lithic-java-core/src/main/kotlin/com/lithic/api/services/Handlers.kt b/lithic-java-core/src/main/kotlin/com/lithic/api/services/Handlers.kt index 5ddd30ce..0dcd0bef 100644 --- a/lithic-java-core/src/main/kotlin/com/lithic/api/services/Handlers.kt +++ b/lithic-java-core/src/main/kotlin/com/lithic/api/services/Handlers.kt @@ -4,6 +4,7 @@ package com.lithic.api.services import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.lithic.api.core.http.BinaryResponseContent import com.lithic.api.core.http.HttpResponse import com.lithic.api.core.http.HttpResponse.Handler import com.lithic.api.errors.BadRequestException @@ -16,6 +17,8 @@ import com.lithic.api.errors.RateLimitException import com.lithic.api.errors.UnauthorizedException import com.lithic.api.errors.UnexpectedStatusCodeException import com.lithic.api.errors.UnprocessableEntityException +import java.io.InputStream +import java.io.OutputStream @JvmSynthetic internal fun emptyHandler(): Handler = EmptyHandler @@ -25,12 +28,20 @@ private object EmptyHandler : Handler { @JvmSynthetic internal fun stringHandler(): Handler = StringHandler +@JvmSynthetic internal fun binaryHandler(): Handler = BinaryHandler + private object StringHandler : Handler { override fun handle(response: HttpResponse): String { return response.body().readBytes().toString(Charsets.UTF_8) } } +private object BinaryHandler : Handler { + override fun handle(response: HttpResponse): BinaryResponseContent { + return BinaryResponseContentImpl(response) + } +} + @JvmSynthetic internal inline fun jsonHandler(jsonMapper: JsonMapper): Handler { return object : Handler { @@ -96,3 +107,24 @@ internal fun Handler.withErrorHandler(errorHandler: Handler) } } } + +class BinaryResponseContentImpl +constructor( + private val response: HttpResponse, +) : BinaryResponseContent { + override fun contentType(): String? { + return response.headers().get("Content-Type").firstOrNull() + } + + override fun body(): InputStream { + return response.body() + } + + override fun writeTo(outputStream: OutputStream) { + response.body().copyTo(outputStream) + } + + override fun close() { + response.body().close() + } +}