Skip to content

Commit

Permalink
fix: removed reset() call on HttpBotRequest's input stream
Browse files Browse the repository at this point in the history
  • Loading branch information
i.ilyin authored and CptBronzebeard committed Mar 6, 2024
1 parent 3114023 commit 7ed4972
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import java.nio.charset.Charset
/**
* Contains details of the HTTP request to the corresponding [HttpBotChannel]
*
* @property stream input stream containing a request data
* @param stream input stream containing a request data
* @property headers request HTTP headers
* @property parameters HTTP query parameters
* @property requestMetadata optional metadata for request processing
Expand All @@ -18,21 +18,20 @@ class HttpBotRequest(
val parameters: Map<String, List<String>> = mapOf(),
val requestMetadata: String? = null
) {
val stream = stream.buffered()
private val streamBody: ByteArray

fun receiveText(charset: Charset = Charset.forName("UTF-8")) = stream.runAndReset { bufferedReader(charset).readText() }
init {
streamBody = stream.readBytes()
}

fun receiveText(charset: Charset = Charset.forName("UTF-8")) = streamBody.toString(charset)

fun firstHeader(name: String) = headers[name]?.first()

fun firstParameter(name: String) = parameters[name]?.first()

override fun toString() =
"HttpBotRequest(stream=$stream, headers=$headers, parameters=$parameters, requestMetadata=$requestMetadata"
}

fun <R> InputStream.runAndReset(action: InputStream.() -> R): R {
mark(0)
return action().also { reset() }
"HttpBotRequest(streamBody=$streamBody, headers=$headers, parameters=$parameters, requestMetadata=$requestMetadata"
}

fun String.asHttpBotRequest(requestMetadata: String? = null) = HttpBotRequest(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.justai.jaicf.core.test.channel

import com.justai.jaicf.channel.http.HttpBotRequest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import kotlin.random.Random
import kotlin.test.assertEquals

class HttpBotRequestTest {
@Test
fun `should not throw exception on long request body`() {
val randomBytes = Random.Default.nextBytes(65536)
val request = HttpBotRequest(randomBytes.inputStream())
val resultString = assertDoesNotThrow {
request.receiveText(charset = Charsets.UTF_8)
}
assertEquals(
randomBytes.decodeToString(),
resultString
)
}
}

0 comments on commit 7ed4972

Please sign in to comment.