Коммит 5bb86c52 создал по автору Aleksei Tirman's avatar Aleksei Tirman
Просмотр файлов

KTOR-2001 Fix code style errors in ktor-client module

владелец 4a50c76c
......@@ -106,7 +106,8 @@ public class AndroidClientEngine(override val config: AndroidEngineConfig) : Htt
}
internal suspend fun OutgoingContent.writeTo(
stream: OutputStream, callContext: CoroutineContext
stream: OutputStream,
callContext: CoroutineContext
): Unit = stream.use { blockingOutput ->
when (this) {
is OutgoingContent.ByteArrayContent -> blockingOutput.write(bytes())
......
......@@ -8,7 +8,6 @@ import io.ktor.client.engine.*
import java.net.*
import javax.net.ssl.*
/**
* Configuration for [Android] client engine.
*/
......@@ -25,7 +24,6 @@ public class AndroidEngineConfig : HttpClientEngineConfig() {
*/
public var socketTimeout: Int = 100_000
/**
* Https connection manipulator. inherited methods are not permitted.
*/
......
......@@ -27,20 +27,23 @@ import kotlin.test.*
import kotlin.test.Test
class AndroidHttpsTest : TestWithKtor() {
override val server: ApplicationEngine = embeddedServer(Netty, applicationEngineEnvironment {
sslConnector(keyStore, "sha256ecdsa", { "changeit".toCharArray() }, { "changeit".toCharArray() }) {
port = serverPort
keyStorePath = keyStoreFile.absoluteFile
override val server: ApplicationEngine = embeddedServer(
Netty,
applicationEngineEnvironment {
sslConnector(keyStore, "sha256ecdsa", { "changeit".toCharArray() }, { "changeit".toCharArray() }) {
port = serverPort
keyStorePath = keyStoreFile.absoluteFile
module {
routing {
get("/") {
call.respondText("Hello, world")
module {
routing {
get("/") {
call.respondText("Hello, world")
}
}
}
}
}
})
)
companion object {
val keyStoreFile = File("build/temp.jks")
......@@ -89,11 +92,13 @@ class AndroidHttpsTest : TestWithKtor() {
@Test
fun hello(): Unit = runBlocking {
HttpClient(Android.config {
sslManager = { conn ->
conn.sslSocketFactory = sslContext.socketFactory
HttpClient(
Android.config {
sslManager = { conn ->
conn.sslSocketFactory = sslContext.socketFactory
}
}
}).use { client ->
).use { client ->
val actual = client.get<String>("https://127.0.0.1:$serverPort/")
assertEquals("Hello, world", actual)
}
......
......@@ -53,16 +53,17 @@ internal class ApacheEngine(override val config: ApacheEngineConfig) : HttpClien
isDaemon = true
setUncaughtExceptionHandler { _, _ -> }
}
}
disableAuthCaching()
disableConnectionState()
disableCookieManagement()
setMaxConnPerRoute(MAX_CONNECTIONS_COUNT)
setMaxConnTotal(MAX_CONNECTIONS_COUNT)
setDefaultIOReactorConfig(IOReactorConfig.custom()
.setIoThreadCount(IO_THREAD_COUNT_DEFAULT)
.build())
setDefaultIOReactorConfig(
IOReactorConfig.custom()
.setIoThreadCount(IO_THREAD_COUNT_DEFAULT)
.build()
)
setupProxy()
}
......
......@@ -25,7 +25,14 @@ class ResponseConsumerTest {
}
}
val requestData = HttpRequestData(URLBuilder().build(), HttpMethod.Get, Headers.Empty, body, Job(), Attributes())
val requestData = HttpRequestData(
URLBuilder().build(),
HttpMethod.Get,
Headers.Empty,
body,
Job(),
Attributes()
)
val consumer = ApacheResponseConsumer(parentContext, requestData)
val decoder = object : ContentDecoder {
......
......@@ -25,8 +25,7 @@ private val testData = mutableMapOf(
internal class ClientBenchmark {
lateinit var client: HttpClient
@Param("Apache", "OkHttp", "Android", "CIO")// "Jetty")
@Param("Apache", "OkHttp", "Android", "CIO") // "Jetty")
var zengineName: String = ""
@Param("0", "1", "16", "32", "64", "256", "1024")
......
// ktlint-disable filename
/*
* Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
......
......@@ -121,9 +121,13 @@ internal class CIOEngine(
return endpoints.computeIfAbsent(endpointId) {
val secure = (protocol.isSecure())
Endpoint(
host, port, proxy, secure,
host,
port,
proxy,
secure,
config,
connectionFactory, coroutineContext,
connectionFactory,
coroutineContext,
onDone = { endpoints.remove(endpointId) }
)
}
......
......@@ -77,7 +77,10 @@ public class EndpointConfig {
/**
* Maximum number of connection attempts.
*/
@Deprecated("This is deprecated due to the misleading name. Use connectAttempts instead.", replaceWith = ReplaceWith("connectAttempts"))
@Deprecated(
"This is deprecated due to the misleading name. Use connectAttempts instead.",
replaceWith = ReplaceWith("connectAttempts")
)
public var connectRetryAttempts: Int
get() = connectAttempts
set(value) {
......
// ktlint-disable filename
/*
* Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
......
......@@ -108,7 +108,8 @@ internal class Endpoint(
val originOutput = this@Endpoint.mapEngineExceptions(connection.output, request)
val output = originOutput.handleHalfClosed(
callContext, config.endpoint.allowHalfClose
callContext,
config.endpoint.allowHalfClose
)
callContext[Job]!!.invokeOnCompletion { cause ->
......@@ -134,8 +135,11 @@ internal class Endpoint(
}
private suspend fun writeRequestAndReadResponse(
request: HttpRequestData, output: ByteWriteChannel, callContext: CoroutineContext,
input: ByteReadChannel, originOutput: ByteWriteChannel
request: HttpRequestData,
output: ByteWriteChannel,
callContext: CoroutineContext,
input: ByteReadChannel,
originOutput: ByteWriteChannel
): HttpResponseData {
val requestTime = GMTDate()
request.write(output, callContext, proxy != null)
......@@ -147,7 +151,8 @@ internal class Endpoint(
val connection = connect(request)
val pipeline = ConnectionPipeline(
config.endpoint.keepAliveTime, config.endpoint.pipelineMaxSize,
config.endpoint.keepAliveTime,
config.endpoint.pipelineMaxSize,
connection,
proxy != null,
deliveryPoint,
......@@ -252,18 +257,19 @@ internal class Endpoint(
}
private suspend fun <T> CoroutineScope.handleTimeout(
timeout: Long, block: suspend CoroutineScope.() -> T
timeout: Long,
block: suspend CoroutineScope.() -> T
): T = if (timeout == HttpTimeout.INFINITE_TIMEOUT_MS) {
block()
} else {
withTimeout(timeout, block)
}
@Suppress("KDocMissingDocumentation")
@Deprecated(
"Binary compatibility.",
level = DeprecationLevel.HIDDEN, replaceWith = ReplaceWith("FailToConnectException")
level = DeprecationLevel.HIDDEN,
replaceWith = ReplaceWith("FailToConnectException")
)
public open class ConnectException : Exception("Connect timed out or retry attempts exceeded")
......
......@@ -20,7 +20,8 @@ import kotlinx.coroutines.*
import kotlin.coroutines.*
internal suspend fun HttpRequestData.write(
output: ByteWriteChannel, callContext: CoroutineContext,
output: ByteWriteChannel,
callContext: CoroutineContext,
overProxy: Boolean,
closeChannel: Boolean = true
) {
......@@ -66,8 +67,9 @@ internal suspend fun HttpRequestData.write(
}
val content = body
if (content is OutgoingContent.NoContent)
if (content is OutgoingContent.NoContent) {
return
}
val chunkedJob: EncoderJob? = if (chunked) encodeChunked(output, callContext) else null
val channel = chunkedJob?.channel ?: output
......
......@@ -11,13 +11,13 @@ import io.ktor.http.cio.*
import io.ktor.network.sockets.*
import io.ktor.util.cio.*
import io.ktor.util.date.*
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.pool.*
import kotlinx.coroutines.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.channels.Channel
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.pool.*
import kotlinx.coroutines.sync.*
import java.nio.channels.*
import kotlin.coroutines.*
......
......@@ -13,7 +13,10 @@ import io.ktor.http.cio.websocket.*
* Create raw [ClientWebSocketSession]: no ping-pong and other service messages are used.
*/
public suspend fun HttpClient.webSocketRawSession(
method: HttpMethod = HttpMethod.Get, host: String = "localhost", port: Int = DEFAULT_PORT, path: String = "/",
method: HttpMethod = HttpMethod.Get,
host: String = "localhost",
port: Int = DEFAULT_PORT,
path: String = "/",
block: HttpRequestBuilder.() -> Unit = {}
): ClientWebSocketSession = request {
this.method = method
......@@ -25,9 +28,13 @@ public suspend fun HttpClient.webSocketRawSession(
* Create raw [ClientWebSocketSession]: no ping-pong and other service messages are used.
*/
public suspend fun HttpClient.webSocketRaw(
method: HttpMethod = HttpMethod.Get, host: String = "localhost", port: Int = DEFAULT_PORT, path: String = "/",
request: HttpRequestBuilder.() -> Unit = {}, block: suspend ClientWebSocketSession.() -> Unit
): Unit {
method: HttpMethod = HttpMethod.Get,
host: String = "localhost",
port: Int = DEFAULT_PORT,
path: String = "/",
request: HttpRequestBuilder.() -> Unit = {},
block: suspend ClientWebSocketSession.() -> Unit
): Unit { // ktlint-disable filename no-unit-return
val session = webSocketRawSession(method, host, port, path) {
url.protocol = URLProtocol.WS
url.port = port
......@@ -48,20 +55,26 @@ public suspend fun HttpClient.webSocketRaw(
* Create raw [ClientWebSocketSession]: no ping-pong and other service messages are used.
*/
public suspend fun HttpClient.wsRaw(
method: HttpMethod = HttpMethod.Get, host: String = "localhost", port: Int = DEFAULT_PORT, path: String = "/",
request: HttpRequestBuilder.() -> Unit = {}, block: suspend ClientWebSocketSession.() -> Unit
method: HttpMethod = HttpMethod.Get,
host: String = "localhost",
port: Int = DEFAULT_PORT,
path: String = "/",
request: HttpRequestBuilder.() -> Unit = {},
block: suspend ClientWebSocketSession.() -> Unit
): Unit = webSocketRaw(method, host, port, path, request, block)
/**
* Open [DefaultClientWebSocketSession].
*/
@Deprecated(message = "This method is deprecated. Use one from :ktor-client:ktor-client-core", level = DeprecationLevel.HIDDEN)
@Deprecated(
message = "This method is deprecated. Use one from :ktor-client:ktor-client-core",
level = DeprecationLevel.HIDDEN
)
public suspend fun HttpClient.ws(
urlString: String,
request: HttpRequestBuilder.() -> Unit = {},
block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit {
): Unit { // ktlint-disable filename no-unit-return
val url = Url(urlString)
webSocket(HttpMethod.Get, url.host, url.port, url.encodedPath, request, block)
}
......@@ -70,11 +83,22 @@ public suspend fun HttpClient.ws(
* Create secure raw [ClientWebSocketSession]: no ping-pong and other service messages are used.
*/
public suspend fun HttpClient.wssRaw(
method: HttpMethod = HttpMethod.Get, host: String = "localhost", port: Int = DEFAULT_PORT, path: String = "/",
request: HttpRequestBuilder.() -> Unit = {}, block: suspend ClientWebSocketSession.() -> Unit
): Unit = webSocketRaw(method, host, port, path, request = {
url.protocol = URLProtocol.WSS
url.port = port
method: HttpMethod = HttpMethod.Get,
host: String = "localhost",
port: Int = DEFAULT_PORT,
path: String = "/",
request: HttpRequestBuilder.() -> Unit = {},
block: suspend ClientWebSocketSession.() -> Unit
): Unit = webSocketRaw(
method,
host,
port,
path,
request = {
url.protocol = URLProtocol.WSS
url.port = port
request()
}, block = block)
request()
},
block = block
)
......@@ -28,20 +28,28 @@ import kotlin.test.Test
class CIOHttpsTest : TestWithKtor() {
override val server: ApplicationEngine = embeddedServer(Jetty, applicationEngineEnvironment {
sslConnector(keyStore, "sha384ecdsa", { "changeit".toCharArray() }, { "changeit".toCharArray() }) {
port = serverPort
keyStorePath = keyStoreFile.absoluteFile
module {
routing {
get("/") {
call.respondText("Hello, world")
override val server: ApplicationEngine = embeddedServer(
Jetty,
applicationEngineEnvironment {
sslConnector(
keyStore,
"sha384ecdsa",
{ "changeit".toCharArray() },
{ "changeit".toCharArray() }
) {
port = serverPort
keyStorePath = keyStoreFile.absoluteFile
module {
routing {
get("/") {
call.respondText("Hello, world")
}
}
}
}
}
})
)
companion object {
val keyStoreFile = File("build/temp.jks")
......@@ -86,11 +94,10 @@ class CIOHttpsTest : TestWithKtor() {
sslContext.init(null, tmf.trustManagers, null)
x509TrustManager = tmf.trustManagers.first { it is X509TrustManager } as X509TrustManager
}
}
@Test
fun hello(): Unit {
fun hello() {
CIOCipherSuites.SupportedSuites.forEach { suite ->
/**
* Outdated by jetty.
......
......@@ -31,9 +31,11 @@ class CIORequestTest : TestWithKtor() {
routing {
get("/") {
val longHeader = call.request.headers["LongHeader"]!!
call.respond(object : OutgoingContent.NoContent() {
override val headers: Headers = headersOf("LongHeader", longHeader)
})
call.respond(
object : OutgoingContent.NoContent() {
override val headers: Headers = headersOf("LongHeader", longHeader)
}
)
}
get("/echo") {
call.respond("OK")
......
......@@ -63,7 +63,9 @@ class ConnectErrorsTest {
try {
newServer.accept().use { client ->
client.getOutputStream().let { out ->
out.write("HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 2\r\n\r\nOK".toByteArray())
out.write(
"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 2\r\n\r\nOK".toByteArray()
)
out.flush()
}
client.getInputStream().readBytes()
......@@ -88,33 +90,39 @@ class ConnectErrorsTest {
init(keyStore)
}
HttpClient(CIO.config {
maxConnectionsCount = 3
HttpClient(
CIO.config {
maxConnectionsCount = 3
endpoint {
connectTimeout = SOCKET_CONNECT_TIMEOUT
connectRetryAttempts = 1
}
endpoint {
connectTimeout = SOCKET_CONNECT_TIMEOUT
connectRetryAttempts = 1
}
https {
trustManager = trustManagerFactory.trustManagers.first { it is X509TrustManager } as X509TrustManager
https {
trustManager = trustManagerFactory.trustManagers
.first { it is X509TrustManager } as X509TrustManager
}
}
}).use { client ->
).use { client ->
val serverPort = ServerSocket(0).use { it.localPort }
val server = embeddedServer(Netty, environment = applicationEngineEnvironment {
sslConnector(keyStore, "mykey", { "changeit".toCharArray() }, { "changeit".toCharArray() }) {
port = serverPort
keyStorePath = keyStoreFile.absoluteFile
}
module {
routing {
get {
call.respondText("OK")
val server = embeddedServer(
Netty,
environment = applicationEngineEnvironment {
sslConnector(keyStore, "mykey", { "changeit".toCharArray() }, { "changeit".toCharArray() }) {
port = serverPort
keyStorePath = keyStoreFile.absoluteFile
}
module {
routing {
get {
call.respondText("OK")
}
}
}
}
})
)
try {
client.get<String>(scheme = "https", path = "/", port = serverPort)
......
// ktlint-disable filename
/*
* Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
......
......@@ -234,4 +234,3 @@ public class HttpClient(
override fun toString(): String = "HttpClient[$engine]"
}
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать