From cf1937be1fa51557259d7d386d0f914fd67b27cf Mon Sep 17 00:00:00 2001 From: Leonid Stashevsky Date: Tue, 20 Jun 2023 09:06:45 +0200 Subject: [PATCH] Update ktlint version (#3657) * KTOR-5957 Update kotlinter version to 3.15.0 --- .editorconfig | 23 ++++-- buildSrc/src/main/kotlin/Codestyle.kt | 12 ++-- gradle/libs.versions.toml | 2 +- .../engine/apache5/ApacheRequestProducer.kt | 7 +- .../plugins/websocket/cio/buildersCio.kt | 5 +- .../ktor/client/plugins/HttpRequestRetry.kt | 5 +- .../client/plugins/api/KtorCallContexts.kt | 24 ++++--- .../client/plugins/cookies/CookiesStorage.kt | 4 +- .../client/plugins/websocket/WebSockets.kt | 4 +- .../ktor/client/plugins/websocket/builders.kt | 5 +- .../src/io/ktor/client/request/HttpRequest.kt | 1 + .../common/test/CacheExpiresTest.kt | 1 + .../common/test/ClientPluginsTest.kt | 16 ++--- .../curl/internal/CurlMultiApiHandler.kt | 11 +-- .../darwin/internal/DarwinWebsocketSession.kt | 10 +-- .../ktor/client/engine/okhttp/OkHttpEngine.kt | 4 +- .../io/ktor/client/plugins/auth/AuthTest.kt | 8 ++- .../plugins/auth/AuthTokenHolderTest.kt | 1 - .../jvm/test/KotlinxSerializerTest.kt | 4 +- .../test/io/ktor/client/tests/ContentTest.kt | 2 +- .../test/io/ktor/client/tests/MockedTests.kt | 8 ++- .../winhttp/internal/WinHttpChunkedMode.kt | 2 + .../winhttp/internal/WinHttpCoroutine.kt | 7 +- .../winhttp/internal/WinHttpExceptions.kt | 4 +- .../engine/winhttp/internal/WinHttpRequest.kt | 4 +- .../src/io/ktor/http/ContentDisposition.kt | 4 +- .../src/io/ktor/http/HttpHeaderValueParser.kt | 1 - .../src/io/ktor/http/HttpProtocolVersion.kt | 2 +- ktor-http/common/src/io/ktor/http/Ranges.kt | 2 +- .../src/io/ktor/http/auth/HttpAuthHeader.kt | 8 ++- .../test/io/ktor/tests/http/CodecTest.kt | 2 +- .../src/io/ktor/http/cio/ConnectionOptions.kt | 17 +++-- .../ktor/tests/http/cio/RequestParserTest.kt | 8 +-- .../io/ktor/http/cio/CIOMultipartDataBase.kt | 4 +- .../io/ktor/utils/io/ByteChannelSequential.kt | 29 +++++--- .../common/src/io/ktor/utils/io/Coroutines.kt | 10 +-- .../common/src/io/ktor/utils/io/core/Input.kt | 10 +-- .../src/io/ktor/utils/io/core/Output.kt | 8 ++- .../io/ktor/utils/io/core/internal/Unsafe.kt | 1 - .../io/ktor/utils/io/PrimitiveArraysTest.kt | 7 +- .../io/ktor/utils/io/PrimitiveCodecTest.kt | 7 +- ktor-io/jvm/src/io/ktor/utils/io/Delimited.kt | 18 +++-- .../io/ktor/utils/io/charsets/CharsetJVM.kt | 14 ++-- .../src/io/ktor/utils/io/charsets/Strings.kt | 8 ++- .../src/io/ktor/utils/io/core/ScannerJVM.kt | 42 +++++++---- .../src/io/ktor/utils/io/internal/Strings.kt | 4 +- .../io/ktor/utils/io/jvm/javaio/Reading.kt | 5 +- .../src/io/ktor/utils/io/jvm/nio/Reading.kt | 10 +-- .../jvm/test/io/ktor/utils/io/StreamTest.kt | 4 +- .../utils/io/bits/MemoryPrimitivesNative.kt | 70 +++++++++++++------ .../network/selector/ActorSelectorManager.kt | 7 +- .../io/ktor/network/sockets/SocketAddress.kt | 1 + .../io/ktor/network/tls/TLSClientHandshake.kt | 2 +- .../network/tls/extensions/PointFormat.kt | 2 +- .../src/io/ktor/network/sockets/CIOWriter.kt | 4 +- .../cio/internal/WeakTimeoutQueueJvm.kt | 4 +- .../ktor/tests/server/cio/IntegrationTest.kt | 5 +- .../ktor/server/cio/CIOApplicationEngine.kt | 1 + .../src/io/ktor/server/cio/Pipeline.kt | 3 - .../io/ktor/server/config/yaml/YamlConfig.kt | 15 ++-- .../ktor/server/http/content/StaticContent.kt | 7 +- .../server/application/ApplicationPlugin.kt | 6 +- .../server/plugins/OriginConnectionPoint.kt | 1 - .../io/ktor/server/response/ResponseType.kt | 1 + .../io/ktor/server/routing/RouteSelector.kt | 7 +- .../io/ktor/tests/hosts/CommandLineTest.kt | 7 +- .../hosts/ReceiveBlockingPrimitiveTest.kt | 2 + .../io/ktor/server/engine/EmbeddedServer.kt | 40 ++++++----- .../ktor-server-netty/build.gradle.kts | 4 +- .../jvm/src/io/ktor/server/netty/CIO.kt | 5 +- .../ktor/server/netty/NettyDirectEncoder.kt | 8 ++- .../src/io/ktor/server/auth/Principal.kt | 5 +- .../src/io/ktor/server/auth/SessionAuth.kt | 5 +- .../tests/auth/AuthorizeHeaderParserTest.kt | 7 +- .../plugins/callloging/CallLoggingConfig.kt | 5 +- .../plugins/callloging/CallLoggingTest.kt | 2 +- .../contentnegotiation/ResponseConverter.kt | 2 +- .../plugins/defaultheaders/DefaultHeaders.kt | 4 +- .../server/plugins/forwardedheaders/Utils.kt | 4 +- .../io/ktor/tests/html/HtmlTemplateTest.kt | 6 +- .../locations/BackwardCompatibleImpl.kt | 4 +- .../io/ktor/tests/locations/LocationsTest.kt | 5 ++ .../plugins/ratelimit/RateLimitConfig.kt | 3 +- .../RequestValidationTest.kt | 15 ++-- .../sessions/SessionSerializerReflection.kt | 61 ++++++++-------- .../server/plugins/statuspages/StatusPages.kt | 6 +- .../jakarta/ServletApplicationEngine.kt | 4 +- .../server/servlet/jakarta/ServletWriter.kt | 4 +- .../servlet/ServletApplicationEngine.kt | 4 +- .../io/ktor/server/servlet/ServletWriter.kt | 4 +- .../ktor/server/testing/EngineTestBaseJvm.kt | 3 +- .../server/testing/HighLoadHttpGenerator.kt | 2 +- .../client/TestEngineWebsocketSession.kt | 5 +- .../tomcat/jakarta/TomcatApplicationEngine.kt | 44 ++++++------ .../jvm/src/JacksonConverter.kt | 2 +- .../KotlinxSerializationJsonExtensions.kt | 4 +- ktor-utils/jvm/src/io/ktor/util/Nonce.kt | 7 +- .../tests/utils/DeflaterReadChannelTest.kt | 8 +-- 98 files changed, 526 insertions(+), 300 deletions(-) diff --git a/.editorconfig b/.editorconfig index 321005ae1e0..7438c161dd2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,10 +1,19 @@ [*] -charset=utf-8 -end_of_line=lf -insert_final_newline=true -indent_style=space -indent_size=4 -max_line_length=120 +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +max_line_length = 120 [*.json] -indent_size=2 +indent_size = 2 + +[*.{kt,kts}] +ktlint_standard_no-wildcard-imports = disabled +ktlint_standard_trailing-comma-on-call-site = disabled +ktlint_standard_trailing-comma-on-declaration-site = disabled +ktlint_standard_filename = disabled +ktlint_standard_class-naming = disabled +ktlint_standard_annotation = disabled +ktlint_standard_comment-wrapping = disabled \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/Codestyle.kt b/buildSrc/src/main/kotlin/Codestyle.kt index b8f04435794..ce67734790f 100644 --- a/buildSrc/src/main/kotlin/Codestyle.kt +++ b/buildSrc/src/main/kotlin/Codestyle.kt @@ -2,7 +2,9 @@ * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ import org.gradle.api.* +import org.gradle.api.tasks.* import org.gradle.kotlin.dsl.* +import org.jmailen.gradle.kotlinter.tasks.* fun Project.configureCodestyle() { apply(plugin = "org.jmailen.kotlinter") @@ -10,10 +12,10 @@ fun Project.configureCodestyle() { kotlinter.apply { ignoreFailures = true reporters = arrayOf("checkstyle", "plain") - experimentalRules = false - disabledRules = arrayOf( - "no-wildcard-imports", - "indent" - ) + } + + val editorconfigFile = rootProject.file(".editorconfig") + tasks.withType { + inputs.file(editorconfigFile).withPathSensitivity(PathSensitivity.RELATIVE) } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index fa4987b2704..af5d04470b0 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,7 +5,7 @@ coroutines-version = "1.7.1" atomicfu-version = "0.18.5" serialization-version = "1.5.1" validator-version = "0.8.0" -ktlint-version = "3.10.0" +ktlint-version = "3.15.0" netty-version = "4.1.92.Final" netty-tcnative-version = "2.0.61.Final" diff --git a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheRequestProducer.kt b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheRequestProducer.kt index dae6da048ea..f389db3bfe0 100644 --- a/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheRequestProducer.kt +++ b/ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheRequestProducer.kt @@ -55,8 +55,11 @@ internal fun ApacheRequestProducer( return BasicRequestProducer( setupRequest(requestData, config), - if (!hasContent && isGetOrHead) null - else ApacheRequestEntityProducer(requestData, callContext, contentLength, type, isChunked) + if (!hasContent && isGetOrHead) { + null + } else { + ApacheRequestEntityProducer(requestData, callContext, contentLength, type, isChunked) + } ) } diff --git a/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/plugins/websocket/cio/buildersCio.kt b/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/plugins/websocket/cio/buildersCio.kt index 5bcac925b6e..76aec2967b2 100644 --- a/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/plugins/websocket/cio/buildersCio.kt +++ b/ktor-client/ktor-client-cio/jvm/src/io/ktor/client/plugins/websocket/cio/buildersCio.kt @@ -35,8 +35,9 @@ public suspend fun HttpClient.webSocketRawSession( val sessionCompleted = CompletableDeferred() result.complete(session) session.outgoing.invokeOnClose { - if (it != null) sessionCompleted.completeExceptionally(it) - else sessionCompleted.complete(Unit) + if (it != null) { + sessionCompleted.completeExceptionally(it) + } else sessionCompleted.complete(Unit) } sessionCompleted.await() } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt index 7a36e5b6f49..a0a60bdc81f 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpRequestRetry.kt @@ -337,8 +337,9 @@ public class HttpRequestRetry internal constructor(configuration: Configuration) val subRequest = HttpRequestBuilder().takeFrom(request) request.executionContext.invokeOnCompletion { cause -> val subRequestJob = subRequest.executionContext as CompletableJob - if (cause == null) subRequestJob.complete() - else subRequestJob.completeExceptionally(cause) + if (cause == null) { + subRequestJob.complete() + } else subRequestJob.completeExceptionally(cause) } return subRequest } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/api/KtorCallContexts.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/api/KtorCallContexts.kt index 91220b30e96..d2dfed3a016 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/api/KtorCallContexts.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/api/KtorCallContexts.kt @@ -62,11 +62,13 @@ internal object ResponseHook : } internal object TransformRequestBodyHook : - ClientHook OutgoingContent?> { + ClientHook< + suspend TransformRequestBodyContext.( + request: HttpRequestBuilder, + content: Any, + bodyType: TypeInfo? + ) -> OutgoingContent? + > { override fun install( client: HttpClient, @@ -84,11 +86,13 @@ internal object TransformRequestBodyHook : } internal object TransformResponseBodyHook : - ClientHook Any?> { + ClientHook< + suspend TransformResponseBodyContext.( + response: HttpResponse, + content: ByteReadChannel, + requestedType: TypeInfo + ) -> Any? + > { override fun install( client: HttpClient, diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cookies/CookiesStorage.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cookies/CookiesStorage.kt index 0dfd2f91e3b..1b15e8cd8b3 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cookies/CookiesStorage.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/cookies/CookiesStorage.kt @@ -52,7 +52,9 @@ internal fun Cookie.matches(requestUrl: Url): Boolean { if (path != "/" && requestPath != path && !requestPath.startsWith(path) - ) return false + ) { + return false + } return !(secure && !requestUrl.protocol.isSecure()) } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt index 0efc6dc5a31..df72a3a0f21 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt @@ -183,7 +183,9 @@ public class WebSockets internal constructor( val negotiated = if (extensionsSupported) { plugin.completeNegotiation(context) - } else emptyList() + } else { + emptyList() + } clientSession.apply { start(negotiated) diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt index 2f3f8520ff6..fe27fc6ccce 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/builders.kt @@ -42,8 +42,9 @@ public suspend fun HttpClient.webSocketSession( val sessionCompleted = CompletableDeferred() sessionDeferred.complete(session) session.outgoing.invokeOnClose { - if (it != null) sessionCompleted.completeExceptionally(it) - else sessionCompleted.complete(Unit) + if (it != null) { + sessionCompleted.completeExceptionally(it) + } else sessionCompleted.complete(Unit) } sessionCompleted.await() } diff --git a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt index 89703483a1e..37dff138aaf 100644 --- a/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt +++ b/ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequest.kt @@ -85,6 +85,7 @@ public class HttpRequestBuilder : HttpMessageBuilder { */ public var bodyType: TypeInfo? get() = attributes.getOrNull(BodyTypeAttributeKey) + @InternalAPI set(value) { if (value != null) { attributes.put(BodyTypeAttributeKey, value) diff --git a/ktor-client/ktor-client-core/common/test/CacheExpiresTest.kt b/ktor-client/ktor-client-core/common/test/CacheExpiresTest.kt index 06803baa9e6..93b843f8d17 100644 --- a/ktor-client/ktor-client-core/common/test/CacheExpiresTest.kt +++ b/ktor-client/ktor-client-core/common/test/CacheExpiresTest.kt @@ -128,6 +128,7 @@ class CacheExpiresTest { get() = error("Shouldn't be used") override val responseTime: GMTDate get() = error("Shouldn't be used") + @OptIn(InternalAPI::class) override val content: ByteReadChannel get() = error("Shouldn't be used") diff --git a/ktor-client/ktor-client-core/common/test/ClientPluginsTest.kt b/ktor-client/ktor-client-core/common/test/ClientPluginsTest.kt index 8534319d9c7..8b1f26d8321 100644 --- a/ktor-client/ktor-client-core/common/test/ClientPluginsTest.kt +++ b/ktor-client/ktor-client-core/common/test/ClientPluginsTest.kt @@ -144,9 +144,9 @@ class ClientPluginsTest { fun testCustomHook() = testSuspend { var hookCalled = false val plugin = createClientPlugin("F") { - on(CustomHook) { - hookCalled = true - } + on(CustomHook) { + hookCalled = true + } } val client = HttpClient(MockEngine) { @@ -166,11 +166,11 @@ class ClientPluginsTest { @Test fun testSendHook() = testSuspend { val plugin = createClientPlugin("F") { - on(Send) { - val call = proceed(it) - assertEquals("temp response", call.response.bodyAsText()) - proceed(it) - } + on(Send) { + val call = proceed(it) + assertEquals("temp response", call.response.bodyAsText()) + proceed(it) + } } val client = HttpClient(MockEngine) { diff --git a/ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlMultiApiHandler.kt b/ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlMultiApiHandler.kt index 461987ddf1d..7172fbdcaeb 100644 --- a/ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlMultiApiHandler.kt +++ b/ktor-client/ktor-client-curl/desktop/src/io/ktor/client/engine/curl/internal/CurlMultiApiHandler.kt @@ -28,8 +28,9 @@ internal class CurlMultiApiHandler : Closeable { private val cancelledHandles = mutableSetOf>() + @Suppress("DEPRECATION") private val multiHandle: MultiHandle = curl_multi_init() - ?: @Suppress("DEPRECATION") throw CurlRuntimeException("Could not initialize curl multi handle") + ?: throw CurlRuntimeException("Could not initialize curl multi handle") private val easyHandlesToUnpauseLock = SynchronizedObject() private val easyHandlesToUnpause = mutableListOf() @@ -47,7 +48,9 @@ internal class CurlMultiApiHandler : Closeable { fun scheduleRequest(request: CurlRequestData, deferred: CompletableDeferred): EasyHandle { val easyHandle = curl_easy_init() - ?: throw @Suppress("DEPRECATION") CurlIllegalStateException("Could not initialize an easy handle") + ?: throw + @Suppress("DEPRECATION") + CurlIllegalStateException("Could not initialize an easy handle") val bodyStartedReceiving = CompletableDeferred() val responseData = CurlResponseBuilder(request) @@ -207,9 +210,9 @@ internal class CurlMultiApiHandler : Closeable { val messagePtr = curl_multi_info_read(multiHandle, messagesLeft.ptr) val message = messagePtr?.pointed ?: continue + @Suppress("DEPRECATION") val easyHandle = message.easy_handle - ?: @Suppress("DEPRECATION") - throw CurlIllegalStateException("Got a null easy handle from the message") + ?: throw CurlIllegalStateException("Got a null easy handle from the message") try { val result = processCompletedEasyHandle(message.msg, easyHandle, message.data.result) diff --git a/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt b/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt index f75e4f28edc..85b3ead4a80 100644 --- a/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt +++ b/ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/internal/DarwinWebsocketSession.kt @@ -89,8 +89,9 @@ internal class DarwinWebsocketSession( FrameType.TEXT -> { suspendCancellableCoroutine { continuation -> task.sendMessage(NSURLSessionWebSocketMessage(String(frame.data))) { error -> - if (error == null) continuation.resume(Unit) - else continuation.resumeWithException(DarwinHttpRequestException(error)) + if (error == null) { + continuation.resume(Unit) + } else continuation.resumeWithException(DarwinHttpRequestException(error)) } } } @@ -98,8 +99,9 @@ internal class DarwinWebsocketSession( FrameType.BINARY -> { suspendCancellableCoroutine { continuation -> task.sendMessage(NSURLSessionWebSocketMessage(frame.data.toNSData())) { error -> - if (error == null) continuation.resume(Unit) - else continuation.resumeWithException(DarwinHttpRequestException(error)) + if (error == null) { + continuation.resume(Unit) + } else continuation.resumeWithException(DarwinHttpRequestException(error)) } } } diff --git a/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpEngine.kt b/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpEngine.kt index 27dc58bf610..694a75a4508 100644 --- a/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpEngine.kt +++ b/ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkHttpEngine.kt @@ -194,7 +194,9 @@ private fun HttpRequestData.convertToOkHttpRequest(callContext: CoroutineContext val bodyBytes = if (HttpMethod.permitsRequestBody(method.value)) { body.convertToOkHttpBody(callContext) - } else null + } else { + null + } method(method.value, bodyBytes) } diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTest.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTest.kt index 1814f72949f..2b4f4f44614 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTest.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTest.kt @@ -329,8 +329,11 @@ class AuthTest : ClientLoader() { engine { addHandler { request -> fun respond(): HttpResponseData { - return if (request.headers[HttpHeaders.Authorization] != "Bearer initial") respond("OK") - else respond("Error", HttpStatusCode.Unauthorized, headersOf("WWW-Authenticate", "Bearer")) + return if (request.headers[HttpHeaders.Authorization] != "Bearer initial") { + respond("OK") + } else { + respond("Error", HttpStatusCode.Unauthorized, headersOf("WWW-Authenticate", "Bearer")) + } } when (request.url.encodedPath) { @@ -483,7 +486,6 @@ class AuthTest : ClientLoader() { } } - @Suppress("JoinDeclarationAndAssignment") @Test fun testRefreshWithSameClient() = clientTests { diff --git a/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTokenHolderTest.kt b/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTokenHolderTest.kt index bd0d9e4d698..aec5041ad0a 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTokenHolderTest.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-auth/common/test/io/ktor/client/plugins/auth/AuthTokenHolderTest.kt @@ -71,7 +71,6 @@ class AuthTokenHolderTest { var clearTokenCalled = false val holder = AuthTokenHolder { - // suspend until clearToken is called while (!clearTokenCalled) { delay(10) diff --git a/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/jvm/test/KotlinxSerializerTest.kt b/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/jvm/test/KotlinxSerializerTest.kt index 2240b5243b6..206a268b60f 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/jvm/test/KotlinxSerializerTest.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/jvm/test/KotlinxSerializerTest.kt @@ -50,7 +50,9 @@ data class TestEntry(val a: String, val b: Int) inline fun indexListUnwrapper() = object : JsonTransformingSerializer>(ListSerializer(serializer())) { override fun transformDeserialize(element: JsonElement): JsonElement { - return if (element is JsonArray) element else element.jsonObject.values.firstOrNull { it is JsonArray } + return if (element is JsonArray) { + element + } else element.jsonObject.values.firstOrNull { it is JsonArray } ?: error("Collection not found in json") } } diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt index 64d0115eef1..c864352aea4 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt @@ -333,8 +333,8 @@ class ContentTest : ClientLoader(5 * 60) { } } - @Test // NSUrlSession buffers first 512 bytes + @Test fun testDownloadStream() = clientTests(listOf("Darwin", "DarwinLegacy")) { test { client -> client.prepareGet("$TEST_SERVER/content/stream?delay=100").execute { diff --git a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MockedTests.kt b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MockedTests.kt index fae81654672..fff905203c5 100644 --- a/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MockedTests.kt +++ b/ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/MockedTests.kt @@ -57,9 +57,11 @@ class MockedTests { val responseHeaders = headersOf("Content-Type" to listOf(ContentType.Application.Json.toString())) addHandler { request -> - if (request.url.host == "localhost") when (request.url.encodedPath) { - "/long.json" -> return@addHandler respond(longJSONString, headers = responseHeaders) - "/longer.json" -> return@addHandler respond(longerJSONString, headers = responseHeaders) + if (request.url.host == "localhost") { + when (request.url.encodedPath) { + "/long.json" -> return@addHandler respond(longJSONString, headers = responseHeaders) + "/longer.json" -> return@addHandler respond(longerJSONString, headers = responseHeaders) + } } error("${request.url} should not be requested") } diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpChunkedMode.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpChunkedMode.kt index 7a6ac570f28..1296109f073 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpChunkedMode.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpChunkedMode.kt @@ -10,8 +10,10 @@ package io.ktor.client.engine.winhttp.internal internal enum class WinHttpChunkedMode { // Do not encode body Disabled, + // Encode body Enabled, + // Use native encoder Automatic } diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpCoroutine.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpCoroutine.kt index a39944c2039..5f7e328e8e3 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpCoroutine.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpCoroutine.kt @@ -45,7 +45,10 @@ internal suspend inline fun Closeable.closeableCoroutine( try { block(continuation) } catch (cause: Throwable) { - if (continuation.isActive) continuation.resumeWithException(cause) - else close() + if (continuation.isActive) { + continuation.resumeWithException(cause) + } else { + close() + } } } diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpExceptions.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpExceptions.kt index 6e08285d7cb..1720d74ba16 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpExceptions.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpExceptions.kt @@ -103,7 +103,9 @@ private fun formatMessage(errorCode: UInt, moduleHandle: HMODULE? = null): Strin return try { if (readChars > 0u) { bufferPtr.value?.toKStringFromUtf16(readChars.convert()) - } else null + } else { + null + } } finally { @Suppress("INFERRED_TYPE_VARIABLE_INTO_EMPTY_INTERSECTION_ERROR") LocalFree(bufferPtr.reinterpret()) diff --git a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequest.kt b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequest.kt index 65c8c96777b..7bd714282c7 100644 --- a/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequest.kt +++ b/ktor-client/ktor-client-winhttp/windows/src/io/ktor/client/engine/winhttp/internal/WinHttpRequest.kt @@ -237,7 +237,9 @@ internal class WinHttpRequest( val notifications = WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS.convert() val callback = if (enable) { staticCFunction(::winHttpCallback) - } else null + } else { + null + } val oldStatusCallback = WinHttpSetStatusCallback(hRequest, callback, notifications, 0) if (oldStatusCallback?.rawValue?.toLong() == WINHTTP_INVALID_STATUS_CALLBACK) { diff --git a/ktor-http/common/src/io/ktor/http/ContentDisposition.kt b/ktor-http/common/src/io/ktor/http/ContentDisposition.kt index d97c2ea3cad..e523faa9ef1 100644 --- a/ktor-http/common/src/io/ktor/http/ContentDisposition.kt +++ b/ktor-http/common/src/io/ktor/http/ContentDisposition.kt @@ -28,7 +28,9 @@ public class ContentDisposition( public fun withParameter(key: String, value: String, encodeValue: Boolean = true): ContentDisposition { val encodedValue = if (encodeValue) { encodeContentDispositionAttribute(key, value) - } else value + } else { + value + } return ContentDisposition(disposition, parameters + HeaderValueParam(key, encodedValue)) } diff --git a/ktor-http/common/src/io/ktor/http/HttpHeaderValueParser.kt b/ktor-http/common/src/io/ktor/http/HttpHeaderValueParser.kt index 2fa091e260e..6fc3c210ee1 100644 --- a/ktor-http/common/src/io/ktor/http/HttpHeaderValueParser.kt +++ b/ktor-http/common/src/io/ktor/http/HttpHeaderValueParser.kt @@ -20,7 +20,6 @@ public data class HeaderValueParam(val name: String, val value: String, val esca other.value.equals(value, ignoreCase = true) } override fun hashCode(): Int { - var result = name.lowercase().hashCode() result += 31 * result + value.lowercase().hashCode() return result diff --git a/ktor-http/common/src/io/ktor/http/HttpProtocolVersion.kt b/ktor-http/common/src/io/ktor/http/HttpProtocolVersion.kt index 0439816e923..97e5050e29d 100644 --- a/ktor-http/common/src/io/ktor/http/HttpProtocolVersion.kt +++ b/ktor-http/common/src/io/ktor/http/HttpProtocolVersion.kt @@ -55,7 +55,7 @@ public data class HttpProtocolVersion(val name: String, val major: Int, val mino /** * Format: protocol/major.minor */ - val (protocol, major, minor) = value.split("/", ".").also { + val (protocol, major, minor) = value.split("/", ".").also { check(it.size == 3) { "Failed to parse HttpProtocolVersion. Expected format: protocol/major.minor, but actual: $value" } diff --git a/ktor-http/common/src/io/ktor/http/Ranges.kt b/ktor-http/common/src/io/ktor/http/Ranges.kt index cc2d0ab245e..960f88df44c 100644 --- a/ktor-http/common/src/io/ktor/http/Ranges.kt +++ b/ktor-http/common/src/io/ktor/http/Ranges.kt @@ -20,7 +20,7 @@ public enum class RangeUnits(public val unitToken: String) { /** * Range unit `none` */ - None("none"); + None("none") } /** diff --git a/ktor-http/common/src/io/ktor/http/auth/HttpAuthHeader.kt b/ktor-http/common/src/io/ktor/http/auth/HttpAuthHeader.kt index b63ee53bdab..8c542bd5145 100644 --- a/ktor-http/common/src/io/ktor/http/auth/HttpAuthHeader.kt +++ b/ktor-http/common/src/io/ktor/http/auth/HttpAuthHeader.kt @@ -52,8 +52,11 @@ public fun parseAuthorizationHeader(headerValue: String): HttpAuthHeader? { val parameters = mutableMapOf() val endIndex = matchParameters(headerValue, index, parameters) - return if (endIndex == -1) HttpAuthHeader.Parameterized(authScheme, parameters) else + return if (endIndex == -1) { + HttpAuthHeader.Parameterized(authScheme, parameters) + } else { throw ParseException("Function parseAuthorizationHeader can parse only one header") + } } /** @@ -437,8 +440,9 @@ private fun String.skipDelimiter(startIndex: Int, delimiter: Char): Int { var index = skipSpaces(startIndex) if (index == length) return -1 - if (this[index] != delimiter) + if (this[index] != delimiter) { throw ParseException("Expected delimiter $delimiter at position $index") + } index++ return skipSpaces(index) diff --git a/ktor-http/common/test/io/ktor/tests/http/CodecTest.kt b/ktor-http/common/test/io/ktor/tests/http/CodecTest.kt index 7534f1fb07d..6584ad32d1e 100644 --- a/ktor-http/common/test/io/ktor/tests/http/CodecTest.kt +++ b/ktor-http/common/test/io/ktor/tests/http/CodecTest.kt @@ -14,7 +14,7 @@ class CodecTest { private val urlPath = "/wikipedia/commons/9/9c/University_of_Illinois_at_Urbana\u2013Champaign_logo.svg" private val surrogateSymbolUrlPath = "/path/🐕" - @Test/*(timeout = 1000L)*/ + @Test /*(timeout = 1000L)*/ @Ignore fun testDecodeRandom() { val chars = "+%0123abc" diff --git a/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/ConnectionOptions.kt b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/ConnectionOptions.kt index fc14f8f2c7b..472750f117c 100644 --- a/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/ConnectionOptions.kt +++ b/ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/ConnectionOptions.kt @@ -99,13 +99,16 @@ public class ConnectionOptions( if (connectionOptions == null) connectionOptions = KeepAlive - return if (hopHeadersList == null) connectionOptions - else ConnectionOptions( - connectionOptions.close, - connectionOptions.keepAlive, - connectionOptions.upgrade, - hopHeadersList - ) + return if (hopHeadersList == null) { + connectionOptions + } else { + ConnectionOptions( + connectionOptions.close, + connectionOptions.keepAlive, + connectionOptions.upgrade, + hopHeadersList + ) + } } } diff --git a/ktor-http/ktor-http-cio/common/test/io/ktor/tests/http/cio/RequestParserTest.kt b/ktor-http/ktor-http-cio/common/test/io/ktor/tests/http/cio/RequestParserTest.kt index ac0717c749c..00b2e25dd07 100644 --- a/ktor-http/ktor-http-cio/common/test/io/ktor/tests/http/cio/RequestParserTest.kt +++ b/ktor-http/ktor-http-cio/common/test/io/ktor/tests/http/cio/RequestParserTest.kt @@ -20,25 +20,25 @@ class RequestParserTest { Host: www.example.com - """.trimIndent(), + """.trimIndent(), """ GET / HTPT/1.1 Host: www.example.com - """.trimIndent(), + """.trimIndent(), """ GET / _ Host: www.example.com - """.trimIndent(), + """.trimIndent(), """ GET / HTTP/1.01 Host: www.example.com - """.trimIndent() + """.trimIndent() ) for (case in cases) { diff --git a/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/CIOMultipartDataBase.kt b/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/CIOMultipartDataBase.kt index 55b647b0097..9db5ffa8eb4 100644 --- a/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/CIOMultipartDataBase.kt +++ b/ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/CIOMultipartDataBase.kt @@ -90,7 +90,9 @@ public class CIOMultipartDataBase( val completeRead = if (buffer.remaining() > 0) { part.body.readAvailable(buffer) == -1 - } else false + } else { + false + } buffer.flip() diff --git a/ktor-io/common/src/io/ktor/utils/io/ByteChannelSequential.kt b/ktor-io/common/src/io/ktor/utils/io/ByteChannelSequential.kt index 91bca0cec0f..7f50f068287 100644 --- a/ktor-io/common/src/io/ktor/utils/io/ByteChannelSequential.kt +++ b/ktor-io/common/src/io/ktor/utils/io/ByteChannelSequential.kt @@ -230,8 +230,9 @@ public abstract class ByteChannelSequentialBase( if (srcRemaining == 0) return 0 val size = minOf(srcRemaining, availableForWrite) - return if (size == 0) writeAvailableSuspend(src) - else { + return if (size == 0) { + writeAvailableSuspend(src) + } else { writable.writeFully(src, size) afterWrite(size) size @@ -242,8 +243,9 @@ public abstract class ByteChannelSequentialBase( if (length == 0) return 0 val size = minOf(length, availableForWrite) - return if (size == 0) writeAvailableSuspend(src, offset, length) - else { + return if (size == 0) { + writeAvailableSuspend(src, offset, length) + } else { writable.writeFully(src, offset, size) afterWrite(size) size @@ -439,8 +441,9 @@ public abstract class ByteChannelSequentialBase( afterRead(partSize) checkClosed(remaining, builder) - return if (remaining > 0) readPacketSuspend(builder, remaining) - else builder.build() + return if (remaining > 0) { + readPacketSuspend(builder, remaining) + } else builder.build() } private suspend fun readPacketSuspend(builder: BytePacketBuilder, size: Int): ByteReadPacket { @@ -556,8 +559,11 @@ public abstract class ByteChannelSequentialBase( } override suspend fun readBoolean(): Boolean { - return if (readable.canRead()) (readable.readByte() == 1.toByte()).also { afterRead(1) } - else readBooleanSlow() + return if (readable.canRead()) { + (readable.readByte() == 1.toByte()).also { afterRead(1) } + } else { + readBooleanSlow() + } } private suspend fun readBooleanSlow(): Boolean { @@ -712,8 +718,11 @@ public abstract class ByteChannelSequentialBase( } return decodeUTF8LineLoopSuspend(out, limit, { size -> - if (await(size)) readable - else null + if (await(size)) { + readable + } else { + null + } }) { afterRead(it) } } diff --git a/ktor-io/common/src/io/ktor/utils/io/Coroutines.kt b/ktor-io/common/src/io/ktor/utils/io/Coroutines.kt index b51bd471168..fc3eb3aea66 100644 --- a/ktor-io/common/src/io/ktor/utils/io/Coroutines.kt +++ b/ktor-io/common/src/io/ktor/utils/io/Coroutines.kt @@ -51,8 +51,9 @@ public fun reader( parent: Job? = null, block: suspend ReaderScope.() -> Unit ): ReaderJob { - val newContext = if (parent != null) GlobalScope.newCoroutineContext(coroutineContext + parent) - else GlobalScope.newCoroutineContext(coroutineContext) + val newContext = if (parent != null) { + GlobalScope.newCoroutineContext(coroutineContext + parent) + } else GlobalScope.newCoroutineContext(coroutineContext) return CoroutineScope(newContext).reader(EmptyCoroutineContext, channel, block) } @@ -91,8 +92,9 @@ public fun writer( parent: Job? = null, block: suspend WriterScope.() -> Unit ): WriterJob { - val newContext = if (parent != null) GlobalScope.newCoroutineContext(coroutineContext + parent) - else GlobalScope.newCoroutineContext(coroutineContext) + val newContext = if (parent != null) { + GlobalScope.newCoroutineContext(coroutineContext + parent) + } else GlobalScope.newCoroutineContext(coroutineContext) return CoroutineScope(newContext).writer(EmptyCoroutineContext, channel, block) } diff --git a/ktor-io/common/src/io/ktor/utils/io/core/Input.kt b/ktor-io/common/src/io/ktor/utils/io/core/Input.kt index 282ac09b351..801d77c320a 100644 --- a/ktor-io/common/src/io/ktor/utils/io/core/Input.kt +++ b/ktor-io/common/src/io/ktor/utils/io/core/Input.kt @@ -434,8 +434,9 @@ public abstract class Input( takeWhile { buffer -> val rc = buffer.decodeASCII { - if (copied == max) false - else { + if (copied == max) { + false + } else { out.append(it) copied++ true @@ -474,8 +475,9 @@ public abstract class Input( takeWhileSize { buffer -> val size = buffer.decodeUTF8 { - if (copied == max) false - else { + if (copied == max) { + false + } else { out.append(it) copied++ true diff --git a/ktor-io/common/src/io/ktor/utils/io/core/Output.kt b/ktor-io/common/src/io/ktor/utils/io/core/Output.kt index e57be328e46..7f79e5a4f2f 100644 --- a/ktor-io/common/src/io/ktor/utils/io/core/Output.kt +++ b/ktor-io/common/src/io/ktor/utils/io/core/Output.kt @@ -238,12 +238,16 @@ public abstract class Output public constructor( val maxCopySize = PACKET_MAX_COPY_SIZE val appendSize = if (nextSize < maxCopySize && nextSize <= (tail.endGap + tail.writeRemaining)) { nextSize - } else -1 + } else { + -1 + } val prependSize = if (lastSize < maxCopySize && lastSize <= foreignStolen.startGap && foreignStolen.isExclusivelyOwned()) { lastSize - } else -1 + } else { + -1 + } if (appendSize == -1 && prependSize == -1) { // simply enqueue if there is no reason to merge diff --git a/ktor-io/common/src/io/ktor/utils/io/core/internal/Unsafe.kt b/ktor-io/common/src/io/ktor/utils/io/core/internal/Unsafe.kt index c064808f48a..61658c09ecd 100644 --- a/ktor-io/common/src/io/ktor/utils/io/core/internal/Unsafe.kt +++ b/ktor-io/common/src/io/ktor/utils/io/core/internal/Unsafe.kt @@ -58,5 +58,4 @@ internal fun Output.prepareWriteHead(capacity: Int, current: ChunkBuffer?): Chun } @JvmField - internal val EmptyByteArray = ByteArray(0) diff --git a/ktor-io/common/test/io/ktor/utils/io/PrimitiveArraysTest.kt b/ktor-io/common/test/io/ktor/utils/io/PrimitiveArraysTest.kt index c353e263793..6eed66dee05 100644 --- a/ktor-io/common/test/io/ktor/utils/io/PrimitiveArraysTest.kt +++ b/ktor-io/common/test/io/ktor/utils/io/PrimitiveArraysTest.kt @@ -945,8 +945,11 @@ class PrimitiveArraysTest { require(d < 16) { "digit $d should be in [0..15]" } require(d >= 0) { "digit $d should be in [0..15]" } - if (d < 10) append('0' + d) - else append('a' + (d - 10)) + if (d < 10) { + append('0' + d) + } else { + append('a' + (d - 10)) + } } private fun Buffer.writeHex(hex: CharSequence) { diff --git a/ktor-io/common/test/io/ktor/utils/io/PrimitiveCodecTest.kt b/ktor-io/common/test/io/ktor/utils/io/PrimitiveCodecTest.kt index 585dbfd4420..605f9c8cac7 100644 --- a/ktor-io/common/test/io/ktor/utils/io/PrimitiveCodecTest.kt +++ b/ktor-io/common/test/io/ktor/utils/io/PrimitiveCodecTest.kt @@ -768,7 +768,10 @@ class PrimitiveCodecTest { require(d < 16) { "digit $d should be in [0..15]" } require(d >= 0) { "digit $d should be in [0..15]" } - if (d < 10) append('0' + d) - else append('a' + (d - 10)) + if (d < 10) { + append('0' + d) + } else { + append('a' + (d - 10)) + } } } diff --git a/ktor-io/jvm/src/io/ktor/utils/io/Delimited.kt b/ktor-io/jvm/src/io/ktor/utils/io/Delimited.kt index 7f93e345d84..45347f4be57 100644 --- a/ktor-io/jvm/src/io/ktor/utils/io/Delimited.kt +++ b/ktor-io/jvm/src/io/ktor/utils/io/Delimited.kt @@ -29,14 +29,20 @@ public suspend fun ByteReadChannel.readUntilDelimiter(delimiter: ByteBuffer, dst val size = if (rc < 0) { endFound = true -rc - } else rc + } else { + rc + } copied += size } while (dst.hasRemaining() && !endFound) } - return if (copied == 0 && isClosedForRead) -1 - else if (!dst.hasRemaining() || endFound) copied - else readUntilDelimiterSuspend(delimiter, dst, copied) + return if (copied == 0 && isClosedForRead) { + -1 + } else if (!dst.hasRemaining() || endFound) { + copied + } else { + readUntilDelimiterSuspend(delimiter, dst, copied) + } } @Suppress("DEPRECATION") @@ -94,7 +100,9 @@ private suspend fun ByteReadChannel.readUntilDelimiterSuspend( val size = if (rc <= 0) { endFound = true -rc - } else rc + } else { + rc + } copied += size } while (dst.hasRemaining() && !endFound) diff --git a/ktor-io/jvm/src/io/ktor/utils/io/charsets/CharsetJVM.kt b/ktor-io/jvm/src/io/ktor/utils/io/charsets/CharsetJVM.kt index 2e225471920..58261d2c480 100644 --- a/ktor-io/jvm/src/io/ktor/utils/io/charsets/CharsetJVM.kt +++ b/ktor-io/jvm/src/io/ktor/utils/io/charsets/CharsetJVM.kt @@ -78,7 +78,9 @@ public actual fun CharsetEncoder.encodeUTF8(input: ByteReadPacket, dst: Output) if (cb.hasRemaining()) { cb.put(ch) true - } else false + } else { + false + } } input.headPosition = chunk.readPosition @@ -91,8 +93,9 @@ public actual fun CharsetEncoder.encodeUTF8(input: ByteReadPacket, dst: Output) view.writeDirect(writeSize) { to -> val cr = encode(cb, to, false) if (cr.isUnmappable || cr.isMalformed) cr.throwExceptionWrapped() - if (cr.isOverflow && to.hasRemaining()) writeSize++ - else writeSize = 1 + if (cr.isOverflow && to.hasRemaining()) { + writeSize++ + } else writeSize = 1 } if (cb.hasRemaining()) writeSize else 0 } @@ -112,8 +115,9 @@ public actual fun CharsetEncoder.encodeUTF8(input: ByteReadPacket, dst: Output) chunk.writeDirect(completeSize) { to -> val cr = encode(cb, to, true) if (cr.isMalformed || cr.isUnmappable) cr.throwExceptionWrapped() - if (cr.isOverflow) completeSize++ - else completeSize = 0 + if (cr.isOverflow) { + completeSize++ + } else completeSize = 0 } completeSize diff --git a/ktor-io/jvm/src/io/ktor/utils/io/charsets/Strings.kt b/ktor-io/jvm/src/io/ktor/utils/io/charsets/Strings.kt index 6c8a6c69aea..d5216fa6454 100644 --- a/ktor-io/jvm/src/io/ktor/utils/io/charsets/Strings.kt +++ b/ktor-io/jvm/src/io/ktor/utils/io/charsets/Strings.kt @@ -10,13 +10,17 @@ internal inline fun ByteBuffer.decodeASCII( ): Int { return if (hasArray()) { decodeASCII3_array(out, offset, length, predicate) - } else decodeASCII3_buffer(out, offset, length, predicate) + } else { + decodeASCII3_buffer(out, offset, length, predicate) + } } internal fun ByteBuffer.decodeASCII(out: CharArray, offset: Int = 0, length: Int = out.size): Int { return if (hasArray()) { decodeASCII3_array(out, offset, length) - } else decodeASCII3_buffer(out, offset, length) + } else { + decodeASCII3_buffer(out, offset, length) + } } @Suppress("FunctionName") diff --git a/ktor-io/jvm/src/io/ktor/utils/io/core/ScannerJVM.kt b/ktor-io/jvm/src/io/ktor/utils/io/core/ScannerJVM.kt index 3bd774aa648..37ee37d69e0 100644 --- a/ktor-io/jvm/src/io/ktor/utils/io/core/ScannerJVM.kt +++ b/ktor-io/jvm/src/io/ktor/utils/io/core/ScannerJVM.kt @@ -3,8 +3,11 @@ package io.ktor.utils.io.core import java.nio.ByteBuffer internal actual fun Buffer.discardUntilDelimiterImpl(delimiter: Byte): Int { - return if (hasArray()) discardUntilDelimiterImplArrays(this, delimiter) - else discardUntilDelimiterImplMemory(this, delimiter) + return if (hasArray()) { + discardUntilDelimiterImplArrays(this, delimiter) + } else { + discardUntilDelimiterImplMemory(this, delimiter) + } } private fun discardUntilDelimiterImplArrays(buffer: Buffer, delimiter: Byte): Int { @@ -25,8 +28,11 @@ private fun discardUntilDelimiterImplArrays(buffer: Buffer, delimiter: Byte): In } internal actual fun Buffer.discardUntilDelimitersImpl(delimiter1: Byte, delimiter2: Byte): Int { - return if (hasArray()) discardUntilDelimitersImplArrays(this, delimiter1, delimiter2) - else discardUntilDelimitersImplMemory(this, delimiter1, delimiter2) + return if (hasArray()) { + discardUntilDelimitersImplArrays(this, delimiter1, delimiter2) + } else { + discardUntilDelimitersImplMemory(this, delimiter1, delimiter2) + } } private fun discardUntilDelimitersImplArrays(buffer: Buffer, delimiter1: Byte, delimiter2: Byte): Int { @@ -53,8 +59,11 @@ internal actual fun Buffer.readUntilDelimiterImpl(delimiter: Byte, dst: ByteArra assert(length >= 0) assert(offset + length <= dst.size) - return if (hasArray()) readUntilDelimiterArrays(this, delimiter, dst, offset, length) - else readUntilDelimiterDirect(delimiter, dst, offset, length) + return if (hasArray()) { + readUntilDelimiterArrays(this, delimiter, dst, offset, length) + } else { + readUntilDelimiterDirect(delimiter, dst, offset, length) + } } private fun Buffer.readUntilDelimiterDirect(delimiter: Byte, dst: ByteArray, offset: Int, length: Int): Int { @@ -87,8 +96,11 @@ internal actual fun Buffer.readUntilDelimitersImpl( assert(offset + length <= dst.size) assert(delimiter1 != delimiter2) - return if (hasArray()) readUntilDelimitersArrays(delimiter1, delimiter2, dst, offset, length) - else readUntilDelimitersDirect(delimiter1, delimiter2, dst, offset, length) + return if (hasArray()) { + readUntilDelimitersArrays(delimiter1, delimiter2, dst, offset, length) + } else { + readUntilDelimitersDirect(delimiter1, delimiter2, dst, offset, length) + } } private fun Buffer.readUntilDelimitersDirect( @@ -122,8 +134,11 @@ private fun Buffer.readUntilDelimitersArrays( } internal actual fun Buffer.readUntilDelimiterImpl(delimiter: Byte, dst: Output): Int { - return if (hasArray()) readUntilDelimiterArrays(delimiter, dst) - else readUntilDelimiterDirect(delimiter, dst) + return if (hasArray()) { + readUntilDelimiterArrays(delimiter, dst) + } else { + readUntilDelimiterDirect(delimiter, dst) + } } internal fun Buffer.readUntilDelimiterDirect(delimiter: Byte, dst: Output): Int { @@ -137,8 +152,11 @@ internal fun Buffer.readUntilDelimiterArrays(delimiter: Byte, dst: Output): Int internal actual fun Buffer.readUntilDelimitersImpl(delimiter1: Byte, delimiter2: Byte, dst: Output): Int { assert(delimiter1 != delimiter2) - return if (hasArray()) readUntilDelimitersArrays(delimiter1, delimiter2, dst) - else readUntilDelimitersDirect(delimiter1, delimiter2, dst) + return if (hasArray()) { + readUntilDelimitersArrays(delimiter1, delimiter2, dst) + } else { + readUntilDelimitersDirect(delimiter1, delimiter2, dst) + } } internal fun Buffer.readUntilDelimitersDirect(delimiter1: Byte, delimiter2: Byte, dst: Output): Int { diff --git a/ktor-io/jvm/src/io/ktor/utils/io/internal/Strings.kt b/ktor-io/jvm/src/io/ktor/utils/io/internal/Strings.kt index 7f6d7031b51..84f2a66fc86 100644 --- a/ktor-io/jvm/src/io/ktor/utils/io/internal/Strings.kt +++ b/ktor-io/jvm/src/io/ktor/utils/io/internal/Strings.kt @@ -7,7 +7,9 @@ import kotlin.math.* internal fun ByteBuffer.decodeASCII(out: CharArray, offset: Int = 0, length: Int = out.size): Int { return if (hasArray()) { decodeASCII3_array(out, offset, length) - } else decodeASCII3_buffer(out, offset, length) + } else { + decodeASCII3_buffer(out, offset, length) + } } internal fun ByteBuffer.decodeASCIILine(out: CharArray, offset: Int = 0, length: Int = out.size): Long { diff --git a/ktor-io/jvm/src/io/ktor/utils/io/jvm/javaio/Reading.kt b/ktor-io/jvm/src/io/ktor/utils/io/jvm/javaio/Reading.kt index 8a65733d200..62ed0c399a2 100644 --- a/ktor-io/jvm/src/io/ktor/utils/io/jvm/javaio/Reading.kt +++ b/ktor-io/jvm/src/io/ktor/utils/io/jvm/javaio/Reading.kt @@ -23,8 +23,9 @@ public suspend fun InputStream.copyTo(channel: ByteWriteChannel, limit: Long = L val bufferSize = buffer.size.toLong() while (copied < limit) { val rc = read(buffer, 0, minOf(limit - copied, bufferSize).toInt()) - if (rc == -1) break - else if (rc > 0) { + if (rc == -1) { + break + } else if (rc > 0) { channel.writeFully(buffer, 0, rc) copied += rc } diff --git a/ktor-io/jvm/src/io/ktor/utils/io/jvm/nio/Reading.kt b/ktor-io/jvm/src/io/ktor/utils/io/jvm/nio/Reading.kt index b9de1a736c0..97280095023 100644 --- a/ktor-io/jvm/src/io/ktor/utils/io/jvm/nio/Reading.kt +++ b/ktor-io/jvm/src/io/ktor/utils/io/jvm/nio/Reading.kt @@ -25,13 +25,15 @@ public suspend fun ReadableByteChannel.copyTo(ch: ByteWriteChannel, limit: Long val l = bb.limit() bb.limit(bb.position() + rem.toInt()) val rc = read(bb) - if (rc == -1) eof = true - else copied += rc + if (rc == -1) { + eof = true + } else copied += rc bb.limit(l) } else { val rc = read(bb) - if (rc == -1) eof = true - else copied += rc + if (rc == -1) { + eof = true + } else copied += rc } } diff --git a/ktor-io/jvm/test/io/ktor/utils/io/StreamTest.kt b/ktor-io/jvm/test/io/ktor/utils/io/StreamTest.kt index 0a674fff73e..401c8016aad 100644 --- a/ktor-io/jvm/test/io/ktor/utils/io/StreamTest.kt +++ b/ktor-io/jvm/test/io/ktor/utils/io/StreamTest.kt @@ -72,7 +72,9 @@ class StreamTest { if (th.state === Thread.State.BLOCKED || th.state === Thread.State.WAITING || th.state === Thread.State.TIMED_WAITING - ) break + ) { + break + } } outputStream.write(byteArrayOf(0x33, 0x44)) diff --git a/ktor-io/posix/src/io/ktor/utils/io/bits/MemoryPrimitivesNative.kt b/ktor-io/posix/src/io/ktor/utils/io/bits/MemoryPrimitivesNative.kt index 379c6f7ccaa..157e0d243df 100644 --- a/ktor-io/posix/src/io/ktor/utils/io/bits/MemoryPrimitivesNative.kt +++ b/ktor-io/posix/src/io/ktor/utils/io/bits/MemoryPrimitivesNative.kt @@ -9,80 +9,110 @@ public actual inline fun Memory.loadShortAt(offset: Int): Short { assertIndex(offset, 2) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadShortSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadShortSlowAt(pointer) + } } public actual inline fun Memory.loadShortAt(offset: Long): Short { assertIndex(offset, 2) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadShortSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadShortSlowAt(pointer) + } } public actual inline fun Memory.loadIntAt(offset: Int): Int { assertIndex(offset, 4) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadIntSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadIntSlowAt(pointer) + } } public actual inline fun Memory.loadIntAt(offset: Long): Int { assertIndex(offset, 4) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadIntSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadIntSlowAt(pointer) + } } public actual inline fun Memory.loadLongAt(offset: Int): Long { assertIndex(offset, 8) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadLongSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadLongSlowAt(pointer) + } } public actual inline fun Memory.loadLongAt(offset: Long): Long { assertIndex(offset, 8) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadLongSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadLongSlowAt(pointer) + } } public actual inline fun Memory.loadFloatAt(offset: Int): Float { assertIndex(offset, 4) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadFloatSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadFloatSlowAt(pointer) + } } public actual inline fun Memory.loadFloatAt(offset: Long): Float { assertIndex(offset, 4) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadFloatSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadFloatSlowAt(pointer) + } } public actual inline fun Memory.loadDoubleAt(offset: Int): Double { assertIndex(offset, 8) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadDoubleSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadDoubleSlowAt(pointer) + } } public actual inline fun Memory.loadDoubleAt(offset: Long): Double { assertIndex(offset, 8) val pointer = pointer.plus(offset)!! - return if (Platform.canAccessUnaligned) pointer.reinterpret().pointed.value.toBigEndian() - else loadDoubleSlowAt(pointer) + return if (Platform.canAccessUnaligned) { + pointer.reinterpret().pointed.value.toBigEndian() + } else { + loadDoubleSlowAt(pointer) + } } /** diff --git a/ktor-network/jvm/src/io/ktor/network/selector/ActorSelectorManager.kt b/ktor-network/jvm/src/io/ktor/network/selector/ActorSelectorManager.kt index f181d99a9dd..c827235b659 100644 --- a/ktor-network/jvm/src/io/ktor/network/selector/ActorSelectorManager.kt +++ b/ktor-network/jvm/src/io/ktor/network/selector/ActorSelectorManager.kt @@ -142,8 +142,11 @@ public class ActorSelectorManager(context: CoroutineContext) : SelectorManagerSu if (selectionQueue.addLast(selectable)) { continuation.resume(Unit) selectWakeup() - } else if (selectable.channel.isOpen) throw ClosedSelectorException() - else throw ClosedChannelException() + } else if (selectable.channel.isOpen) { + throw ClosedSelectorException() + } else { + throw ClosedChannelException() + } } catch (cause: Throwable) { cancelAllSuspensions(selectable, cause) } diff --git a/ktor-network/jvmAndNix/src/io/ktor/network/sockets/SocketAddress.kt b/ktor-network/jvmAndNix/src/io/ktor/network/sockets/SocketAddress.kt index a675dc916b4..a9217d86cd2 100644 --- a/ktor-network/jvmAndNix/src/io/ktor/network/sockets/SocketAddress.kt +++ b/ktor-network/jvmAndNix/src/io/ktor/network/sockets/SocketAddress.kt @@ -57,6 +57,7 @@ public expect class UnixSocketAddress( * The path of the socket address. */ public operator fun component1(): String + /** * Create a copy of [UnixSocketAddress]. */ diff --git a/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt b/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt index 39f82aa8845..dd8f2a0e1c4 100644 --- a/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt +++ b/ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt @@ -448,7 +448,7 @@ internal class TLSClientHandshake( """Handshake: ServerFinished verification failed: |Expected: ${expectedChecksum.joinToString()} |Actual: ${receivedChecksum.joinToString()} - """.trimMargin() + """.trimMargin() ) } } diff --git a/ktor-network/ktor-network-tls/jvmAndNix/src/io/ktor/network/tls/extensions/PointFormat.kt b/ktor-network/ktor-network-tls/jvmAndNix/src/io/ktor/network/tls/extensions/PointFormat.kt index df2cadc3042..609b6c03e6b 100644 --- a/ktor-network/ktor-network-tls/jvmAndNix/src/io/ktor/network/tls/extensions/PointFormat.kt +++ b/ktor-network/ktor-network-tls/jvmAndNix/src/io/ktor/network/tls/extensions/PointFormat.kt @@ -24,7 +24,7 @@ public enum class PointFormat(public val code: Byte) { /** * Point is compressed according to ANSI X9.62 */ - ANSIX962_COMPRESSED_CHAR2(2); + ANSIX962_COMPRESSED_CHAR2(2) } /** diff --git a/ktor-network/nix/src/io/ktor/network/sockets/CIOWriter.kt b/ktor-network/nix/src/io/ktor/network/sockets/CIOWriter.kt index f4028551f03..c754910722a 100644 --- a/ktor-network/nix/src/io/ktor/network/sockets/CIOWriter.kt +++ b/ktor-network/nix/src/io/ktor/network/sockets/CIOWriter.kt @@ -29,7 +29,9 @@ internal fun CoroutineScope.attachForWritingImpl( val remaining = stop - start val bytesWritten = if (remaining > 0) { send(descriptor, bufferStart, remaining.convert(), 0).toInt() - } else 0 + } else { + 0 + } when (bytesWritten) { 0 -> sockedClosed = true diff --git a/ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/internal/WeakTimeoutQueueJvm.kt b/ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/internal/WeakTimeoutQueueJvm.kt index 72864a58485..f3faecb76be 100644 --- a/ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/internal/WeakTimeoutQueueJvm.kt +++ b/ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/internal/WeakTimeoutQueueJvm.kt @@ -88,7 +88,9 @@ public actual class WeakTimeoutQueue actual constructor( if (wrapped.tryComplete()) { handle.dispose() throw t - } else COROUTINE_SUSPENDED + } else { + COROUTINE_SUSPENDED + } } if (result !== COROUTINE_SUSPENDED && wrapped.tryComplete()) { diff --git a/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/IntegrationTest.kt b/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/IntegrationTest.kt index cf38b95a330..29403d6492e 100644 --- a/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/IntegrationTest.kt +++ b/ktor-server/ktor-server-cio/jvm/test/io/ktor/tests/server/cio/IntegrationTest.kt @@ -35,8 +35,9 @@ class IntegrationTest { } s.invokeOnCompletion { t -> - if (t != null) server.completeExceptionally(t) - else server.complete(@OptIn(ExperimentalCoroutinesApi::class) s.getCompleted()) + if (t != null) { + server.completeExceptionally(t) + } else server.complete(@OptIn(ExperimentalCoroutinesApi::class) s.getCompleted()) } j.invokeOnCompletion { diff --git a/ktor-server/ktor-server-cio/jvmAndNix/src/io/ktor/server/cio/CIOApplicationEngine.kt b/ktor-server/ktor-server-cio/jvmAndNix/src/io/ktor/server/cio/CIOApplicationEngine.kt index 83c198d41a1..dfab8477198 100644 --- a/ktor-server/ktor-server-cio/jvmAndNix/src/io/ktor/server/cio/CIOApplicationEngine.kt +++ b/ktor-server/ktor-server-cio/jvmAndNix/src/io/ktor/server/cio/CIOApplicationEngine.kt @@ -35,6 +35,7 @@ public class CIOApplicationEngine( * A connection is IDLE if there are no active requests running. */ public var connectionIdleTimeoutSeconds: Int = 45 + /** * Allow the server to bind to an address that is already in use */ diff --git a/ktor-server/ktor-server-cio/jvmAndNix/src/io/ktor/server/cio/Pipeline.kt b/ktor-server/ktor-server-cio/jvmAndNix/src/io/ktor/server/cio/Pipeline.kt index 2229c05c8b0..6e172fda080 100644 --- a/ktor-server/ktor-server-cio/jvmAndNix/src/io/ktor/server/cio/Pipeline.kt +++ b/ktor-server/ktor-server-cio/jvmAndNix/src/io/ktor/server/cio/Pipeline.kt @@ -21,7 +21,6 @@ public typealias HttpRequestHandler = suspend ServerRequestScope.(request: Reque "This is an implementation detail and will become internal in future releases.", level = DeprecationLevel.ERROR ) - public val HttpPipelineCoroutine: CoroutineName = CoroutineName("http-pipeline") /** @@ -31,7 +30,6 @@ public val HttpPipelineCoroutine: CoroutineName = CoroutineName("http-pipeline") "This is an implementation detail and will become internal in future releases.", level = DeprecationLevel.ERROR ) - public val HttpPipelineWriterCoroutine: CoroutineName = CoroutineName("http-pipeline-writer") /** @@ -41,5 +39,4 @@ public val HttpPipelineWriterCoroutine: CoroutineName = CoroutineName("http-pipe "This is an implementation detail and will become internal in future releases.", level = DeprecationLevel.ERROR ) - public val RequestHandlerCoroutine: CoroutineName = CoroutineName("request-handler") diff --git a/ktor-server/ktor-server-config-yaml/jvmAndNix/src/io/ktor/server/config/yaml/YamlConfig.kt b/ktor-server/ktor-server-config-yaml/jvmAndNix/src/io/ktor/server/config/yaml/YamlConfig.kt index 8d1e565e740..e92f7701b63 100644 --- a/ktor-server/ktor-server-config-yaml/jvmAndNix/src/io/ktor/server/config/yaml/YamlConfig.kt +++ b/ktor-server/ktor-server-config-yaml/jvmAndNix/src/io/ktor/server/config/yaml/YamlConfig.kt @@ -33,7 +33,9 @@ public expect fun YamlConfig(path: String?): YamlConfig? * Implements [ApplicationConfig] by loading a configuration from a YAML file. * Values can reference to environment variables with `$ENV_VAR` or `"$ENV_VAR:default_value"` syntax. */ -public class YamlConfig @Deprecated("This will become internal") constructor( +public class YamlConfig +@Deprecated("This will become internal") +constructor( private val yaml: YamlMap ) : ApplicationConfig { @@ -169,10 +171,13 @@ private fun resolveValue(value: String, root: YamlConfig): String? { val isOptional = keyWithDefault.first() == '?' val key = if (isOptional) keyWithDefault.drop(1) else keyWithDefault - return getEnvironmentValue(key) ?: if (isOptional) null - else throw ApplicationConfigurationException( - "Required environment variable \"$key\" not found and no default value is present" - ) + return getEnvironmentValue(key) ?: if (isOptional) { + null + } else { + throw ApplicationConfigurationException( + "Required environment variable \"$key\" not found and no default value is present" + ) + } } internal expect fun getEnvironmentValue(key: String): String? diff --git a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/http/content/StaticContent.kt b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/http/content/StaticContent.kt index e0563947899..69b3cc3cd96 100644 --- a/ktor-server/ktor-server-core/jvm/src/io/ktor/server/http/content/StaticContent.kt +++ b/ktor-server/ktor-server-core/jvm/src/io/ktor/server/http/content/StaticContent.kt @@ -127,8 +127,11 @@ public class StaticContentConfig internal constructor() { public fun exclude(block: (Resource) -> Boolean) { val oldBlock = exclude exclude = { - if (oldBlock(it)) true - else block(it) + if (oldBlock(it)) { + true + } else { + block(it) + } } } diff --git a/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/application/ApplicationPlugin.kt b/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/application/ApplicationPlugin.kt index 1ada458b01e..9f8c8609fc1 100644 --- a/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/application/ApplicationPlugin.kt +++ b/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/application/ApplicationPlugin.kt @@ -21,7 +21,8 @@ import kotlinx.coroutines.* public interface Plugin< in TPipeline : Pipeline<*, ApplicationCall>, out TConfiguration : Any, - TPlugin : Any> { + TPlugin : Any + > { /** * A unique key that identifies a plugin. */ @@ -42,7 +43,8 @@ public interface Plugin< public interface BaseApplicationPlugin< in TPipeline : Pipeline<*, ApplicationCall>, out TConfiguration : Any, - TPlugin : Any> : Plugin + TPlugin : Any + > : Plugin /** * Defines a [Plugin](https://ktor.io/docs/plugins.html) that is installed into Application. diff --git a/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/plugins/OriginConnectionPoint.kt b/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/plugins/OriginConnectionPoint.kt index fed7bdb67e0..cc205a1bf9b 100644 --- a/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/plugins/OriginConnectionPoint.kt +++ b/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/plugins/OriginConnectionPoint.kt @@ -24,7 +24,6 @@ public val ApplicationRequest.origin: RequestConnectionPoint * A key to install a mutable [RequestConnectionPoint] */ @Deprecated("This API will be redesigned as per https://youtrack.jetbrains.com/issue/KTOR-2657") - public val MutableOriginConnectionPointKey: AttributeKey = AttributeKey("MutableOriginConnectionPointKey") diff --git a/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/response/ResponseType.kt b/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/response/ResponseType.kt index 3e1df17b604..cc504783b92 100644 --- a/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/response/ResponseType.kt +++ b/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/response/ResponseType.kt @@ -16,6 +16,7 @@ private val ResponseTypeAttributeKey: AttributeKey = AttributeKey("Res */ public var ApplicationResponse.responseType: TypeInfo? get() = call.attributes.getOrNull(ResponseTypeAttributeKey) + @InternalAPI set(value) { if (value != null) { call.attributes.put(ResponseTypeAttributeKey, value) diff --git a/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/routing/RouteSelector.kt b/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/routing/RouteSelector.kt index 639695f606f..898d0e93845 100644 --- a/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/routing/RouteSelector.kt +++ b/ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/routing/RouteSelector.kt @@ -459,8 +459,11 @@ public data class PathSegmentTailcardRouteSelector( else -> parametersOf( name, segments.drop(segmentIndex).mapIndexed { index, segment -> - if (index == 0) segment.drop(prefix.length) - else segment + if (index == 0) { + segment.drop(prefix.length) + } else { + segment + } } ) } diff --git a/ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/CommandLineTest.kt b/ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/CommandLineTest.kt index f0183f1c9ee..0284baa8766 100644 --- a/ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/CommandLineTest.kt +++ b/ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/CommandLineTest.kt @@ -91,8 +91,11 @@ class CommandLineTest { @Test fun testListPropertiesHocon() { val args = arrayOf( - "-P:array.first.0=first", "-P:array.first.1=second", "-P:array.first.2=third", - "-P:array.second.0=1", "-P:array.second.1=2", + "-P:array.first.0=first", + "-P:array.first.1=second", + "-P:array.first.2=third", + "-P:array.second.0=1", + "-P:array.second.1=2", "-P:array.third.0=zero" ) val config = commandLineEnvironment(args).config diff --git a/ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/ReceiveBlockingPrimitiveTest.kt b/ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/ReceiveBlockingPrimitiveTest.kt index 769c3262447..3b1f49831e5 100644 --- a/ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/ReceiveBlockingPrimitiveTest.kt +++ b/ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/ReceiveBlockingPrimitiveTest.kt @@ -76,6 +76,7 @@ class ReceiveBlockingPrimitiveTest { get() = TODO("Not yet implemented") override val version: String get() = TODO("Not yet implemented") + @Deprecated("Use localPort or serverPort instead") override val port: Int get() = TODO("Not yet implemented") @@ -83,6 +84,7 @@ class ReceiveBlockingPrimitiveTest { get() = TODO("Not yet implemented") override val serverPort: Int get() = TODO("Not yet implemented") + @Deprecated("Use localHost or serverHost instead") override val host: String get() = TODO("Not yet implemented") diff --git a/ktor-server/ktor-server-host-common/jvmAndNix/src/io/ktor/server/engine/EmbeddedServer.kt b/ktor-server/ktor-server-host-common/jvmAndNix/src/io/ktor/server/engine/EmbeddedServer.kt index 55bfb12c6fb..af15091b98b 100644 --- a/ktor-server/ktor-server-host-common/jvmAndNix/src/io/ktor/server/engine/EmbeddedServer.kt +++ b/ktor-server/ktor-server-host-common/jvmAndNix/src/io/ktor/server/engine/EmbeddedServer.kt @@ -12,8 +12,10 @@ import kotlin.coroutines.* /** * Factory interface for creating [ApplicationEngine] instances */ -public interface ApplicationEngineFactory { +public interface ApplicationEngineFactory< + out TEngine : ApplicationEngine, + TConfiguration : ApplicationEngine.Configuration + > { /** * Creates an engine from the given [environment] and [configure] script */ @@ -45,15 +47,15 @@ embeddedServer( * @param module application module function */ public fun -CoroutineScope.embeddedServer( - factory: ApplicationEngineFactory, - port: Int = 80, - host: String = "0.0.0.0", - watchPaths: List = listOf(WORKING_DIRECTORY_PATH), - parentCoroutineContext: CoroutineContext = EmptyCoroutineContext, - configure: TConfiguration.() -> Unit = {}, - module: Application.() -> Unit -): TEngine { + CoroutineScope.embeddedServer( + factory: ApplicationEngineFactory, + port: Int = 80, + host: String = "0.0.0.0", + watchPaths: List = listOf(WORKING_DIRECTORY_PATH), + parentCoroutineContext: CoroutineContext = EmptyCoroutineContext, + configure: TConfiguration.() -> Unit = {}, + module: Application.() -> Unit + ): TEngine { val connectors: Array = arrayOf( EngineConnectorBuilder().apply { this.port = port @@ -79,14 +81,14 @@ CoroutineScope.embeddedServer( * @param module application module function */ public fun -CoroutineScope.embeddedServer( - factory: ApplicationEngineFactory, - vararg connectors: EngineConnectorConfig = arrayOf(EngineConnectorBuilder()), - watchPaths: List = listOf(WORKING_DIRECTORY_PATH), - parentCoroutineContext: CoroutineContext = EmptyCoroutineContext, - configure: TConfiguration.() -> Unit = {}, - module: Application.() -> Unit -): TEngine { + CoroutineScope.embeddedServer( + factory: ApplicationEngineFactory, + vararg connectors: EngineConnectorConfig = arrayOf(EngineConnectorBuilder()), + watchPaths: List = listOf(WORKING_DIRECTORY_PATH), + parentCoroutineContext: CoroutineContext = EmptyCoroutineContext, + configure: TConfiguration.() -> Unit = {}, + module: Application.() -> Unit + ): TEngine { val environment = applicationEngineEnvironment { this.parentCoroutineContext = coroutineContext + parentCoroutineContext this.log = KtorSimpleLogger("ktor.application") diff --git a/ktor-server/ktor-server-netty/build.gradle.kts b/ktor-server/ktor-server-netty/build.gradle.kts index 5b5e4c76082..de6ae0ae9b3 100644 --- a/ktor-server/ktor-server-netty/build.gradle.kts +++ b/ktor-server/ktor-server-netty/build.gradle.kts @@ -11,7 +11,9 @@ val nativeClassifier: String? = if (enableAlpnProp) { osName.contains("mac") -> "osx-x86_64" else -> throw InvalidUserDataException("Unsupported os family $osName") } -} else null +} else { + null +} kotlin.sourceSets { jvmMain { diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/CIO.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/CIO.kt index 22c8fba8647..a7427cb50cd 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/CIO.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/CIO.kt @@ -28,8 +28,9 @@ public suspend fun Future.suspendAwait(): T { @Suppress("IMPLICIT_NOTHING_AS_TYPE_PARAMETER") private val wrappingErrorHandler = { t: Throwable, c: Continuation<*> -> - if (t is IOException) c.resumeWithException(ChannelWriteException("Write operation future failed", t)) - else c.resumeWithException(t) + if (t is IOException) { + c.resumeWithException(ChannelWriteException("Write operation future failed", t)) + } else c.resumeWithException(t) } /** diff --git a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt index d9f04905fa2..0efe027fc05 100644 --- a/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt +++ b/ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyDirectEncoder.kt @@ -16,8 +16,10 @@ internal class NettyDirectEncoder : MessageToByteEncoder() { override fun allocateBuffer(ctx: ChannelHandlerContext, msg: HttpContent?, preferDirect: Boolean): ByteBuf { val size = msg?.content()?.readableBytes() ?: 0 - return if (size == 0) Unpooled.EMPTY_BUFFER - else if (preferDirect) ctx.alloc().ioBuffer(size) - else ctx.alloc().heapBuffer(size) + return if (size == 0) { + Unpooled.EMPTY_BUFFER + } else if (preferDirect) { + ctx.alloc().ioBuffer(size) + } else ctx.alloc().heapBuffer(size) } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/Principal.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/Principal.kt index 045852cb1da..37457a37a66 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/Principal.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/Principal.kt @@ -27,8 +27,9 @@ internal class CombinedPrincipal : Principal { fun get(provider: String?, klass: KClass): T? { return principals .firstOrNull { (name, principal) -> - if (provider != null) name == provider && klass.isInstance(principal) - else klass.isInstance(principal) + if (provider != null) { + name == provider && klass.isInstance(principal) + } else klass.isInstance(principal) }?.second as? T } diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/SessionAuth.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/SessionAuth.kt index 8846b00aa00..f5c028afaa3 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/SessionAuth.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/SessionAuth.kt @@ -37,8 +37,9 @@ public class SessionAuthenticationProvider private constructor( context.principal(name, principal) } else { val cause = - if (session == null) AuthenticationFailedCause.NoCredentials - else AuthenticationFailedCause.InvalidCredentials + if (session == null) { + AuthenticationFailedCause.NoCredentials + } else AuthenticationFailedCause.InvalidCredentials @Suppress("NAME_SHADOWING") context.challenge(SessionAuthChallengeKey, cause) { challenge, call -> diff --git a/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/test/io/ktor/tests/auth/AuthorizeHeaderParserTest.kt b/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/test/io/ktor/tests/auth/AuthorizeHeaderParserTest.kt index 2179514e38b..2887c8b77be 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/test/io/ktor/tests/auth/AuthorizeHeaderParserTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/test/io/ktor/tests/auth/AuthorizeHeaderParserTest.kt @@ -146,6 +146,9 @@ class AuthorizeHeaderParserTest { private fun Random.nextString(length: Int, possible: String) = nextString(length, possible.toList()) private fun Random.nextFrom(possibleElements: List): T = - if (possibleElements.isEmpty()) throw NoSuchElementException() - else possibleElements[nextInt(possibleElements.size)] + if (possibleElements.isEmpty()) { + throw NoSuchElementException() + } else { + possibleElements[nextInt(possibleElements.size)] + } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/callloging/CallLoggingConfig.kt b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/callloging/CallLoggingConfig.kt index 97b77658f9e..0f0ea7df268 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/callloging/CallLoggingConfig.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/src/io/ktor/server/plugins/callloging/CallLoggingConfig.kt @@ -133,6 +133,7 @@ public class CallLoggingConfig { } private fun colored(value: Any, color: Ansi.Color): String = - if (isColorsEnabled) Ansi.ansi().fg(color).a(value).reset().toString() - else value.toString() // ignore color + if (isColorsEnabled) { + Ansi.ansi().fg(color).a(value).reset().toString() + } else value.toString() // ignore color } diff --git a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/test/io/ktor/server/plugins/callloging/CallLoggingTest.kt b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/test/io/ktor/server/plugins/callloging/CallLoggingTest.kt index 9cb1fc240b5..515f5e50ed3 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/test/io/ktor/server/plugins/callloging/CallLoggingTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-call-logging/jvm/test/io/ktor/server/plugins/callloging/CallLoggingTest.kt @@ -500,7 +500,7 @@ class CallLoggingTest { assertEquals(HttpStatusCode.BadRequest, status) assertContains( messages, - "DEBUG: Unhandled: GET - /. Exception class io.ktor.server.plugins.BadRequestException: Message of exception" + "DEBUG: Unhandled: GET - /. Exception class io.ktor.server.plugins.BadRequestException: Message of exception" // ktlint-disable max-line-length ) } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvmAndNix/src/io/ktor/server/plugins/contentnegotiation/ResponseConverter.kt b/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvmAndNix/src/io/ktor/server/plugins/contentnegotiation/ResponseConverter.kt index 897bdf422ab..105c61296d3 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvmAndNix/src/io/ktor/server/plugins/contentnegotiation/ResponseConverter.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-content-negotiation/jvmAndNix/src/io/ktor/server/plugins/contentnegotiation/ResponseConverter.kt @@ -27,7 +27,7 @@ internal fun PluginBuilder.convertResponseBody() = onC LOGGER.trace( "Skipping response body transformation from $sourceClass to OutgoingContent for the $requestInfo request" + - " because the $sourceClass type is ignored. See [ContentNegotiationConfig::ignoreType]." + " because the $sourceClass type is ignored. See [ContentNegotiationConfig::ignoreType]." ) return@onCallRespond } diff --git a/ktor-server/ktor-server-plugins/ktor-server-default-headers/jvm/src/io/ktor/server/plugins/defaultheaders/DefaultHeaders.kt b/ktor-server/ktor-server-plugins/ktor-server-default-headers/jvm/src/io/ktor/server/plugins/defaultheaders/DefaultHeaders.kt index e1927f14a15..7dfaa5580dd 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-default-headers/jvm/src/io/ktor/server/plugins/defaultheaders/DefaultHeaders.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-default-headers/jvm/src/io/ktor/server/plugins/defaultheaders/DefaultHeaders.kt @@ -66,7 +66,9 @@ public val DefaultHeaders: RouteScopedPlugin = createRoute ) { val ktorPackageVersion = if (pluginConfig.headers.getAll(HttpHeaders.Server) == null) { pluginConfig::class.java.`package`.implementationVersion ?: "debug" - } else "debug" + } else { + "debug" + } val headers = pluginConfig.headers.build() val DATE_CACHE_TIMEOUT_MILLISECONDS = 1000 diff --git a/ktor-server/ktor-server-plugins/ktor-server-forwarded-header/jvmAndNix/src/io/ktor/server/plugins/forwardedheaders/Utils.kt b/ktor-server/ktor-server-plugins/ktor-server-forwarded-header/jvmAndNix/src/io/ktor/server/plugins/forwardedheaders/Utils.kt index 51984485d5b..6aa9df25168 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-forwarded-header/jvmAndNix/src/io/ktor/server/plugins/forwardedheaders/Utils.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-forwarded-header/jvmAndNix/src/io/ktor/server/plugins/forwardedheaders/Utils.kt @@ -7,5 +7,7 @@ package io.ktor.server.plugins.forwardedheaders internal fun String.isNotHostAddress(): Boolean { return if (contains(':')) { return true - } else none { it.isLetter() } + } else { + none { it.isLetter() } + } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-html-builder/jvmAndNix/test/io/ktor/tests/html/HtmlTemplateTest.kt b/ktor-server/ktor-server-plugins/ktor-server-html-builder/jvmAndNix/test/io/ktor/tests/html/HtmlTemplateTest.kt index aa0a9fcd666..d86db35938c 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-html-builder/jvmAndNix/test/io/ktor/tests/html/HtmlTemplateTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-html-builder/jvmAndNix/test/io/ktor/tests/html/HtmlTemplateTest.kt @@ -20,8 +20,10 @@ class MenuTemplate : Template { ul { each(item) { li { - if (it.first) b { - insert(it) + if (it.first) { + b { + insert(it) + } } else { insert(it) } diff --git a/ktor-server/ktor-server-plugins/ktor-server-locations/jvm/src/io/ktor/server/locations/BackwardCompatibleImpl.kt b/ktor-server/ktor-server-plugins/ktor-server-locations/jvm/src/io/ktor/server/locations/BackwardCompatibleImpl.kt index 9aef3ed0618..ab1239fbd66 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-locations/jvm/src/io/ktor/server/locations/BackwardCompatibleImpl.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-locations/jvm/src/io/ktor/server/locations/BackwardCompatibleImpl.kt @@ -170,7 +170,9 @@ internal class BackwardCompatibleImpl( val pathElements = (path.split("/") + relativePath.split("/")).filterNot { it.isEmpty() } val combinedPath = if (pathElements.isNotEmpty()) { pathElements.joinToString("/", "/", if (trailingSlash) "/" else "") - } else "/" + } else { + "/" + } return ResolvedUriInfo(combinedPath, query + queryValues) } diff --git a/ktor-server/ktor-server-plugins/ktor-server-locations/jvm/test/io/ktor/tests/locations/LocationsTest.kt b/ktor-server/ktor-server-plugins/ktor-server-locations/jvm/test/io/ktor/tests/locations/LocationsTest.kt index d2a59e706a4..e31e15bc250 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-locations/jvm/test/io/ktor/tests/locations/LocationsTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-locations/jvm/test/io/ktor/tests/locations/LocationsTest.kt @@ -144,6 +144,7 @@ class LocationsTest { class pathContainer(val id: Int) { @Location("/items") class items(val container: pathContainer) + @Location("/items") class badItems } @@ -170,6 +171,7 @@ class LocationsTest { class queryContainer(val id: Int) { @Location("/items") class items(val container: queryContainer) + @Location("/items") class badItems } @@ -307,6 +309,7 @@ class LocationsTest { @Location("/") class multiquery(val value: List) + @Location("/") class multiquery2(val name: List) @@ -365,6 +368,7 @@ class LocationsTest { @Location("/space in") class SpaceInPath + @Location("/plus+in") class PlusInPath @@ -429,6 +433,7 @@ class LocationsTest { object users { @Location("/me") object me + @Location("/{id}") class user(val id: Int) } diff --git a/ktor-server/ktor-server-plugins/ktor-server-rate-limit/jvmAndNix/src/io/ktor/server/plugins/ratelimit/RateLimitConfig.kt b/ktor-server/ktor-server-plugins/ktor-server-rate-limit/jvmAndNix/src/io/ktor/server/plugins/ratelimit/RateLimitConfig.kt index 2e170585e42..2f084c5d78a 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-rate-limit/jvmAndNix/src/io/ktor/server/plugins/ratelimit/RateLimitConfig.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-rate-limit/jvmAndNix/src/io/ktor/server/plugins/ratelimit/RateLimitConfig.kt @@ -71,8 +71,9 @@ public class RateLimitProviderConfig(internal val name: RateLimitName) { } is RateLimiter.State.Exhausted -> { - if (!call.response.headers.contains(HttpHeaders.RetryAfter)) + if (!call.response.headers.contains(HttpHeaders.RetryAfter)) { call.response.header(HttpHeaders.RetryAfter, state.toWait.inWholeSeconds.toString()) + } } } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-request-validation/jvmAndNix/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt b/ktor-server/ktor-server-plugins/ktor-server-request-validation/jvmAndNix/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt index ffa85864d6b..734414f265c 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-request-validation/jvmAndNix/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-request-validation/jvmAndNix/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt @@ -23,12 +23,14 @@ class RequestValidationTest { fun testSimpleValidationByClass() = testApplication { install(RequestValidation) { validate { - if (!it.startsWith("+")) ValidationResult.Invalid(listOf("$it should start with \"+\"")) - else ValidationResult.Valid + if (!it.startsWith("+")) { + ValidationResult.Invalid(listOf("$it should start with \"+\"")) + } else ValidationResult.Valid } validate { - if (!it.endsWith("!")) ValidationResult.Invalid(listOf("$it should end with \"!\"")) - else ValidationResult.Valid + if (!it.endsWith("!")) { + ValidationResult.Invalid(listOf("$it should end with \"!\"")) + } else ValidationResult.Valid } } install(StatusPages) { @@ -94,8 +96,9 @@ class RequestValidationTest { validation { check(it is ByteArray) val intValue = String(it).toInt() - if (intValue < 0) ValidationResult.Invalid("Value is negative") - else ValidationResult.Valid + if (intValue < 0) { + ValidationResult.Invalid("Value is negative") + } else ValidationResult.Valid } } } diff --git a/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/SessionSerializerReflection.kt b/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/SessionSerializerReflection.kt index fd770b81119..5cca3ec5790 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/SessionSerializerReflection.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/SessionSerializerReflection.kt @@ -325,37 +325,40 @@ public class SessionSerializerReflection internal constructor( @Suppress("IMPLICIT_CAST_TO_ANY") private fun deserializeValue(owner: KClass<*>, value: String): Any? = - if (!value.startsWith("#")) throw IllegalArgumentException("Bad serialized value") - else when (value.getOrNull(1)) { - null, 'n' -> null - 'i' -> value.drop(2).toInt() - 'l' -> value.drop(2).toLong() - 'f' -> value.drop(2).toDouble() - 'b' -> when (value.getOrNull(2)) { - 'o' -> when (value.getOrNull(3)) { - 't' -> true - 'f' -> false - else -> throw IllegalArgumentException("Unsupported bo-value ${value.take(4)}") + if (!value.startsWith("#")) { + throw IllegalArgumentException("Bad serialized value") + } else { + when (value.getOrNull(1)) { + null, 'n' -> null + 'i' -> value.drop(2).toInt() + 'l' -> value.drop(2).toLong() + 'f' -> value.drop(2).toDouble() + 'b' -> when (value.getOrNull(2)) { + 'o' -> when (value.getOrNull(3)) { + 't' -> true + 'f' -> false + else -> throw IllegalArgumentException("Unsupported bo-value ${value.take(4)}") + } + 'd' -> BigDecimal(value.drop(3)) + 'i' -> BigInteger(value.drop(3)) + else -> throw IllegalArgumentException("Unsupported b-type ${value.take(3)}") } - 'd' -> BigDecimal(value.drop(3)) - 'i' -> BigInteger(value.drop(3)) - else -> throw IllegalArgumentException("Unsupported b-type ${value.take(3)}") - } - 'o' -> when (value.getOrNull(2)) { - 'm' -> Optional.empty() - 'p' -> Optional.ofNullable(deserializeValue(owner, value.drop(3))) - else -> throw IllegalArgumentException("Unsupported o-value ${value.take(3)}") - } - 's' -> value.drop(2) - 'c' -> when (value.getOrNull(2)) { - 'l' -> deserializeCollection(value.drop(3)) - 's' -> deserializeCollection(value.drop(3)).toSet() - 'h' -> value.drop(3).first() - else -> throw IllegalArgumentException("Unsupported c-type ${value.take(3)}") + 'o' -> when (value.getOrNull(2)) { + 'm' -> Optional.empty() + 'p' -> Optional.ofNullable(deserializeValue(owner, value.drop(3))) + else -> throw IllegalArgumentException("Unsupported o-value ${value.take(3)}") + } + 's' -> value.drop(2) + 'c' -> when (value.getOrNull(2)) { + 'l' -> deserializeCollection(value.drop(3)) + 's' -> deserializeCollection(value.drop(3)).toSet() + 'h' -> value.drop(3).first() + else -> throw IllegalArgumentException("Unsupported c-type ${value.take(3)}") + } + 'm' -> deserializeMap(value.drop(2)) + '#' -> deserializeObject(owner, value.drop(2)) + else -> throw IllegalArgumentException("Unsupported type ${value.take(2)}") } - 'm' -> deserializeMap(value.drop(2)) - '#' -> deserializeObject(owner, value.drop(2)) - else -> throw IllegalArgumentException("Unsupported type ${value.take(2)}") } private fun serializeValue(value: Any?): String = diff --git a/ktor-server/ktor-server-plugins/ktor-server-status-pages/jvmAndNix/src/io/ktor/server/plugins/statuspages/StatusPages.kt b/ktor-server/ktor-server-plugins/ktor-server-status-pages/jvmAndNix/src/io/ktor/server/plugins/statuspages/StatusPages.kt index c6a297218ce..02999f75e80 100644 --- a/ktor-server/ktor-server-plugins/ktor-server-status-pages/jvmAndNix/src/io/ktor/server/plugins/statuspages/StatusPages.kt +++ b/ktor-server/ktor-server-plugins/ktor-server-status-pages/jvmAndNix/src/io/ktor/server/plugins/statuspages/StatusPages.kt @@ -113,8 +113,10 @@ public class StatusPagesConfig { /** * Provides access to status handlers based on a status code. */ - public val statuses: MutableMap Unit> = + public val statuses: MutableMap< + HttpStatusCode, + suspend (call: ApplicationCall, content: OutgoingContent, code: HttpStatusCode) -> Unit + > = mutableMapOf() internal var unhandled: suspend (ApplicationCall) -> Unit = {} diff --git a/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletApplicationEngine.kt b/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletApplicationEngine.kt index 2ec1cdd9d59..2142154a5ad 100644 --- a/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletApplicationEngine.kt +++ b/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletApplicationEngine.kt @@ -83,7 +83,9 @@ public open class ServletApplicationEngine : KtorServlet() { override val upgrade: ServletUpgrade by lazy { if ("jetty" in servletContext.serverInfo?.toLowerCasePreservingASCIIRules() ?: "") { jettyUpgrade ?: DefaultServletUpgrade - } else DefaultServletUpgrade + } else { + DefaultServletUpgrade + } } override val coroutineContext: CoroutineContext diff --git a/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletWriter.kt b/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletWriter.kt index d704c2e2a70..0441cf18711 100644 --- a/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletWriter.kt +++ b/ktor-server/ktor-server-servlet-jakarta/jvm/src/io/ktor/server/servlet/jakarta/ServletWriter.kt @@ -121,6 +121,8 @@ private class ServletWriter(val output: ServletOutputStream) : WriteListener { private fun wrapException(cause: Throwable): Throwable { return if (cause is IOException || cause is TimeoutException) { ChannelWriteException("Failed to write to servlet async stream", exception = cause) - } else cause + } else { + cause + } } } diff --git a/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletApplicationEngine.kt b/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletApplicationEngine.kt index 053eccc1a59..e26b084a053 100644 --- a/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletApplicationEngine.kt +++ b/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletApplicationEngine.kt @@ -83,7 +83,9 @@ public open class ServletApplicationEngine : KtorServlet() { override val upgrade: ServletUpgrade by lazy { if ("jetty" in servletContext.serverInfo?.toLowerCasePreservingASCIIRules() ?: "") { jettyUpgrade ?: DefaultServletUpgrade - } else DefaultServletUpgrade + } else { + DefaultServletUpgrade + } } override val coroutineContext: CoroutineContext diff --git a/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletWriter.kt b/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletWriter.kt index 9217bcea39e..d8f3c787cd3 100644 --- a/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletWriter.kt +++ b/ktor-server/ktor-server-servlet/jvm/src/io/ktor/server/servlet/ServletWriter.kt @@ -121,6 +121,8 @@ private class ServletWriter(val output: ServletOutputStream) : WriteListener { private fun wrapException(cause: Throwable): Throwable { return if (cause is IOException || cause is TimeoutException) { ChannelWriteException("Failed to write to servlet async stream", exception = cause) - } else cause + } else { + cause + } } } diff --git a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/EngineTestBaseJvm.kt b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/EngineTestBaseJvm.kt index 0ce8737e219..6ddcbbd4e36 100644 --- a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/EngineTestBaseJvm.kt +++ b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/EngineTestBaseJvm.kt @@ -36,7 +36,8 @@ import kotlin.time.Duration.Companion.seconds @Suppress("KDocMissingDocumentation") actual abstract class EngineTestBase< TEngine : ApplicationEngine, - TConfiguration : ApplicationEngine.Configuration> actual constructor( + TConfiguration : ApplicationEngine.Configuration + > actual constructor( actual val applicationEngineFactory: ApplicationEngineFactory, ) : BaseTest(), CoroutineScope { private val testJob = Job() diff --git a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/HighLoadHttpGenerator.kt b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/HighLoadHttpGenerator.kt index 55c15e62d09..4f1606c8b45 100644 --- a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/HighLoadHttpGenerator.kt +++ b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/HighLoadHttpGenerator.kt @@ -401,7 +401,7 @@ public class HighLoadHttpGenerator( return false } - */ + */ } public fun shutdown() { diff --git a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestEngineWebsocketSession.kt b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestEngineWebsocketSession.kt index 182d3f168fa..8a0234194a3 100644 --- a/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestEngineWebsocketSession.kt +++ b/ktor-server/ktor-server-test-host/jvm/src/io/ktor/server/testing/client/TestEngineWebsocketSession.kt @@ -31,8 +31,9 @@ internal class TestEngineWebsocketSession( suspend fun run() { outgoing.invokeOnClose { - if (it != null) socketJob.completeExceptionally(it) - else socketJob.complete() + if (it != null) { + socketJob.completeExceptionally(it) + } else socketJob.complete() } socketJob.join() } diff --git a/ktor-server/ktor-server-tomcat-jakarta/jvm/src/io/ktor/server/tomcat/jakarta/TomcatApplicationEngine.kt b/ktor-server/ktor-server-tomcat-jakarta/jvm/src/io/ktor/server/tomcat/jakarta/TomcatApplicationEngine.kt index 1b3e01d5e60..aa0ab7492b7 100644 --- a/ktor-server/ktor-server-tomcat-jakarta/jvm/src/io/ktor/server/tomcat/jakarta/TomcatApplicationEngine.kt +++ b/ktor-server/ktor-server-tomcat-jakarta/jvm/src/io/ktor/server/tomcat/jakarta/TomcatApplicationEngine.kt @@ -94,31 +94,31 @@ public class TomcatApplicationEngine( addSslHostConfig( SSLHostConfig().apply { - if (ktorConnector.trustStorePath != null) { - setProperty("clientAuth", "true") - truststoreFile = ktorConnector.trustStorePath!!.absolutePath - } else { - setProperty("clientAuth", "false") - } - - sslProtocol = "TLS" - setProperty("SSLEnabled", "true") - addCertificate( - SSLHostConfigCertificate( - this, - SSLHostConfigCertificate.Type.UNDEFINED - ).apply { - certificateKeyAlias = ktorConnector.keyAlias - certificateKeystorePassword = String(ktorConnector.keyStorePassword()) - certificateKeyPassword = String(ktorConnector.privateKeyPassword()) - certificateKeystoreFile = ktorConnector.keyStorePath!!.absolutePath + if (ktorConnector.trustStorePath != null) { + setProperty("clientAuth", "true") + truststoreFile = ktorConnector.trustStorePath!!.absolutePath + } else { + setProperty("clientAuth", "false") } - ) - ktorConnector.enabledProtocols?.let { - enabledProtocols = it.toTypedArray() + sslProtocol = "TLS" + setProperty("SSLEnabled", "true") + addCertificate( + SSLHostConfigCertificate( + this, + SSLHostConfigCertificate.Type.UNDEFINED + ).apply { + certificateKeyAlias = ktorConnector.keyAlias + certificateKeystorePassword = String(ktorConnector.keyStorePassword()) + certificateKeyPassword = String(ktorConnector.privateKeyPassword()) + certificateKeystoreFile = ktorConnector.keyStorePath!!.absolutePath + } + ) + + ktorConnector.enabledProtocols?.let { + enabledProtocols = it.toTypedArray() + } } - } ) setProperty("SSLEnabled", "true") diff --git a/ktor-shared/ktor-serialization/ktor-serialization-jackson/jvm/src/JacksonConverter.kt b/ktor-shared/ktor-serialization/ktor-serialization-jackson/jvm/src/JacksonConverter.kt index 8744ed28534..97092ec7879 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-jackson/jvm/src/JacksonConverter.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-jackson/jvm/src/JacksonConverter.kt @@ -71,7 +71,7 @@ public class JacksonConverter( /* Jackson internally does special casing on UTF-8, presumably for performance reasons. Thus, we pass an InputStream instead of a Writer to let Jackson do its thing. - */ + */ if (charset == Charsets.UTF_8) { // specific behavior for kotlinx.coroutines.flow.Flow if (typeInfo.type == Flow::class) { diff --git a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/src/io/ktor/serialization/kotlinx/json/KotlinxSerializationJsonExtensions.kt b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/src/io/ktor/serialization/kotlinx/json/KotlinxSerializationJsonExtensions.kt index d443759ca65..c2b8155d8d6 100644 --- a/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/src/io/ktor/serialization/kotlinx/json/KotlinxSerializationJsonExtensions.kt +++ b/ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/src/io/ktor/serialization/kotlinx/json/KotlinxSerializationJsonExtensions.kt @@ -99,7 +99,9 @@ private class JsonArraySymbols(charset: Charset) { internal fun TypeInfo.argumentTypeInfo(): TypeInfo { val elementType = kotlinType!!.arguments[0].type!! return TypeInfo( - elementType.classifier as KClass<*>, elementType.platformType, elementType + elementType.classifier as KClass<*>, + elementType.platformType, + elementType ) } diff --git a/ktor-utils/jvm/src/io/ktor/util/Nonce.kt b/ktor-utils/jvm/src/io/ktor/util/Nonce.kt index 525f9ba226b..6056f0cf9d9 100644 --- a/ktor-utils/jvm/src/io/ktor/util/Nonce.kt +++ b/ktor-utils/jvm/src/io/ktor/util/Nonce.kt @@ -109,8 +109,11 @@ private fun lookupSecureRandom(): SecureRandom { } private fun getInstanceOrNull(name: String? = null) = try { - if (name != null) SecureRandom.getInstance(name) - else SecureRandom() + if (name != null) { + SecureRandom.getInstance(name) + } else { + SecureRandom() + } } catch (notFound: NoSuchAlgorithmException) { null } diff --git a/ktor-utils/jvm/test/io/ktor/tests/utils/DeflaterReadChannelTest.kt b/ktor-utils/jvm/test/io/ktor/tests/utils/DeflaterReadChannelTest.kt index 9989123f976..d7b397fad64 100644 --- a/ktor-utils/jvm/test/io/ktor/tests/utils/DeflaterReadChannelTest.kt +++ b/ktor-utils/jvm/test/io/ktor/tests/utils/DeflaterReadChannelTest.kt @@ -78,10 +78,10 @@ class DeflaterReadChannelTest : CoroutineScope { val bb = ByteBuffer.wrap(text.toByteArray(Charsets.ISO_8859_1)) for ( - step in generateSequence(1) { it * 2 } - .dropWhile { it < 64 } - .takeWhile { it <= 8192 } - .flatMap { sequenceOf(it, it - 1, it + 1) } + step in generateSequence(1) { it * 2 } + .dropWhile { it < 64 } + .takeWhile { it <= 8192 } + .flatMap { sequenceOf(it, it - 1, it + 1) } ) { bb.clear() testReadChannel(text, asyncOf(bb))