From bedb26b36be3f72ceb79e0000a0f8a186d34164b Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Sat, 6 Jan 2024 21:29:25 -0500 Subject: [PATCH 1/2] Prepare to enable Spotless I'm not super keen on any of these changes, but I am very keen on having automatic formatting. --- .editorconfig | 1 + build.gradle.kts | 16 +++- .../main/kotlin/{alpn.kt => AlpnVersions.kt} | 0 .../src/main/kotlin/{artifacts.kt => Osgi.kt} | 0 gradle/libs.versions.toml | 4 +- .../{bridge.kt => DeprecationBridge.kt} | 0 .../junit5/internal/ExtensionLifecycleTest.kt | 8 +- .../kotlin/mockwebserver3/MockResponse.kt | 43 +++++----- .../kotlin/mockwebserver3/MockWebServer.kt | 3 +- ...nseBodies.kt => BufferMockResponseBody.kt} | 0 .../internal/{sleep.kt => SleepNanos.kt} | 0 .../main/kotlin/okhttp3/GenerateClassList.kt | 8 +- okcurl/src/main/kotlin/okhttp3/curl/Main.kt | 2 +- .../okhttp3/curl/internal/-MainCommon.kt | 1 + .../internal/{brotli.kt => Uncompress.kt} | 0 .../okhttp3/dnsoverhttps/package-info.kt | 2 - .../internal/http2/HpackRoundTripTest.kt | 7 +- .../internal/idn/SimpleIdnaMappingTable.kt | 39 ++++++--- .../okhttp3/logging/HttpLoggingInterceptor.kt | 21 +++-- .../internal/{utf8.kt => IsProbablyUtf8.kt} | 0 .../logging/LoggingEventListenerTest.kt | 1 + .../kotlin/okhttp3/DelegatingSSLSocket.kt | 6 +- .../kotlin/okhttp3/OkHttpClientTestRule.kt | 30 ++++++- .../kotlin/okhttp3/tls/HeldCertificate.kt | 25 +++--- .../okhttp3/tls/internal/der/Adapters.kt | 6 +- .../der/{certificates.kt => Certificate.kt} | 17 ++-- .../tls/internal/der/CertificateAdapters.kt | 15 ++-- .../tls/internal/der/ObjectIdentifiers.kt | 16 ++-- .../okhttp3/tls/HandshakeCertificatesTest.kt | 4 +- .../tls/internal/der/DerCertificatesTest.kt | 79 +++++++++--------- .../java/okhttp3/tls/internal/der/DerTest.kt | 22 ++--- .../src/main/kotlin/okhttp3/-JvmPlatform.kt | 2 +- okhttp/src/main/kotlin/okhttp3/Cookie.kt | 12 ++- okhttp/src/main/kotlin/okhttp3/FormBody.kt | 6 +- .../main/kotlin/okhttp3/MultipartReader.kt | 15 +++- .../src/main/kotlin/okhttp3/OkHttpClient.kt | 5 +- okhttp/src/main/kotlin/okhttp3/Request.kt | 3 +- .../okhttp3/internal/-CacheControlCommon.kt | 2 +- .../okhttp3/internal/-ChallengeCommon.kt | 1 + .../kotlin/okhttp3/internal/-HeadersCommon.kt | 2 +- .../okhttp3/internal/-HostnamesCommon.kt | 1 + .../kotlin/okhttp3/internal/-HttpUrlCommon.kt | 1 + .../kotlin/okhttp3/internal/-HttpUrlJvm.kt | 1 + .../okhttp3/internal/-MediaTypeCommon.kt | 2 +- .../kotlin/okhttp3/internal/-NormalizeJvm.kt | 1 + .../okhttp3/internal/-RequestBodyCommon.kt | 2 +- .../kotlin/okhttp3/internal/-RequestCommon.kt | 2 +- .../okhttp3/internal/-ResponseBodyCommon.kt | 2 +- .../okhttp3/internal/-ResponseCommon.kt | 2 +- .../kotlin/okhttp3/internal/-UtilCommon.kt | 23 ++++-- .../main/kotlin/okhttp3/internal/-UtilJvm.kt | 1 + .../okhttp3/internal/concurrent/TaskQueue.kt | 14 +++- .../okhttp3/internal/concurrent/TaskRunner.kt | 9 ++- .../internal/connection/ConnectPlan.kt | 6 +- .../connection/ConnectionSpecSelector.kt | 25 ------ .../internal/connection/RealRoutePlanner.kt | 18 +++-- .../{tlsHandshake.kt => RetryTlsHandshake.kt} | 0 .../internal/graal/{svm.kt => GraalSvm.kt} | 0 .../internal/http/BridgeInterceptor.kt | 4 +- .../http/{dates.kt => DateFormatting.kt} | 43 +++++----- .../okhttp3/internal/http/HttpStatusCodes.kt | 12 ++- .../kotlin/okhttp3/internal/http2/Hpack.kt | 8 +- .../kotlin/okhttp3/internal/http2/Http2.kt | 1 - .../okhttp3/internal/http2/Http2Connection.kt | 4 +- .../kotlin/okhttp3/internal/idn/Punycode.kt | 54 ++++++------- .../main/kotlin/okhttp3/internal/internal.kt | 2 +- .../okhttp3/internal/ws/MessageDeflater.kt | 8 +- .../okhttp3/internal/ws/MessageInflater.kt | 7 +- .../okhttp3/internal/-InternalVersion.kt | 1 + .../src/test/java/okhttp3/AutobahnTester.kt | 4 +- .../test/java/okhttp3/CacheCorruptionTest.kt | 6 +- okhttp/src/test/java/okhttp3/CacheTest.kt | 13 ++- okhttp/src/test/java/okhttp3/CallTest.kt | 32 +++++--- .../java/okhttp3/ConnectionCoalescingTest.kt | 11 +-- .../src/test/java/okhttp3/MediaTypeJvmTest.kt | 2 +- .../test/java/okhttp3/URLConnectionTest.kt | 23 +++--- .../java/okhttp3/WebPlatformToAsciiTest.kt | 1 + .../internal/cache/DiskLruCacheTest.kt | 13 +-- .../connection/InetAddressOrderTest.kt | 1 + .../internal/connection/RouteSelectorTest.kt | 80 +++++++++---------- .../java/okhttp3/internal/http2/HpackTest.kt | 18 +++-- .../internal/http2/Http2ConnectionTest.kt | 7 +- .../internal/http2/HttpOverHttp2Test.kt | 6 +- .../idn/{stringprep.kt => IdnStringprep.kt} | 0 ...repTablesReader.kt => StringprepReader.kt} | 14 +++- .../idn/StringprepTablesReaderTest.kt | 20 +++-- .../java/okhttp3/recipes/kt/CacheResponse.kt | 3 +- .../main/kotlin/okhttp3/survey/RunSurvey.kt | 1 + 88 files changed, 545 insertions(+), 388 deletions(-) rename buildSrc/src/main/kotlin/{alpn.kt => AlpnVersions.kt} (100%) rename buildSrc/src/main/kotlin/{artifacts.kt => Osgi.kt} (100%) rename mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/{bridge.kt => DeprecationBridge.kt} (100%) rename mockwebserver/src/main/kotlin/mockwebserver3/internal/{mockResponseBodies.kt => BufferMockResponseBody.kt} (100%) rename mockwebserver/src/main/kotlin/mockwebserver3/internal/{sleep.kt => SleepNanos.kt} (100%) rename okhttp-brotli/src/main/kotlin/okhttp3/brotli/internal/{brotli.kt => Uncompress.kt} (100%) delete mode 100644 okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/package-info.kt rename okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/internal/{utf8.kt => IsProbablyUtf8.kt} (100%) rename okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/{certificates.kt => Certificate.kt} (92%) delete mode 100644 okhttp/src/main/kotlin/okhttp3/internal/connection/ConnectionSpecSelector.kt rename okhttp/src/main/kotlin/okhttp3/internal/connection/{tlsHandshake.kt => RetryTlsHandshake.kt} (100%) rename okhttp/src/main/kotlin/okhttp3/internal/graal/{svm.kt => GraalSvm.kt} (100%) rename okhttp/src/main/kotlin/okhttp3/internal/http/{dates.kt => DateFormatting.kt} (80%) rename okhttp/src/test/java/okhttp3/internal/idn/{stringprep.kt => IdnStringprep.kt} (100%) rename okhttp/src/test/java/okhttp3/internal/idn/{stringprepTablesReader.kt => StringprepReader.kt} (97%) diff --git a/.editorconfig b/.editorconfig index 6531d6787d2f..a17e1dd735b8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,6 +2,7 @@ root = true [*] indent_size = 2 +ij_continuation_indent_size = 2 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true diff --git a/build.gradle.kts b/build.gradle.kts index 781eea7553d9..f88ad212ab0e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,14 +1,14 @@ @file:Suppress("UnstableApiUsage") +import com.diffplug.gradle.spotless.SpotlessExtension import com.vanniktech.maven.publish.MavenPublishBaseExtension import com.vanniktech.maven.publish.SonatypeHost -import java.net.URL +import java.net.URI import kotlinx.validation.ApiValidationExtension import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.jetbrains.dokka.gradle.DokkaTaskPartial import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import ru.vyarus.gradle.plugin.animalsniffer.AnimalSnifferExtension -import java.net.URI buildscript { dependencies { @@ -22,7 +22,6 @@ buildscript { classpath(libs.gradlePlugin.shadow) classpath(libs.gradlePlugin.animalsniffer) classpath(libs.gradlePlugin.errorprone) - classpath(libs.gradlePlugin.spotless) classpath(libs.gradlePlugin.mavenPublish) classpath(libs.gradlePlugin.binaryCompatibilityValidator) } @@ -34,8 +33,19 @@ buildscript { } } +plugins { + alias(libs.plugins.spotless) +} + apply(plugin = "org.jetbrains.dokka") +configure { + kotlin { + target("**/*.kt") + ktlint() + } +} + allprojects { group = "com.squareup.okhttp3" version = "5.0.0-SNAPSHOT" diff --git a/buildSrc/src/main/kotlin/alpn.kt b/buildSrc/src/main/kotlin/AlpnVersions.kt similarity index 100% rename from buildSrc/src/main/kotlin/alpn.kt rename to buildSrc/src/main/kotlin/AlpnVersions.kt diff --git a/buildSrc/src/main/kotlin/artifacts.kt b/buildSrc/src/main/kotlin/Osgi.kt similarity index 100% rename from buildSrc/src/main/kotlin/artifacts.kt rename to buildSrc/src/main/kotlin/Osgi.kt diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 0f9b271d5552..5a2fd786fc3f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -45,7 +45,6 @@ gradlePlugin-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", ve gradlePlugin-kotlinSerialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "org-jetbrains-kotlin" } gradlePlugin-mavenPublish = "com.vanniktech:gradle-maven-publish-plugin:0.26.0" gradlePlugin-shadow = "gradle.plugin.com.github.johnrengelman:shadow:8.0.0" -gradlePlugin-spotless = "com.diffplug.spotless:spotless-plugin-gradle:6.23.3" guava-jre = "com.google.guava:guava:32.1.3-jre" hamcrestLibrary = "org.hamcrest:hamcrest-library:2.2" httpClient5 = "org.apache.httpcomponents.client5:httpclient5:5.2.3" @@ -88,3 +87,6 @@ squareup-okhttp-icu = "com.squareup.okhttpicu:okhttp-icu:0.2.0" squareup-kotlinPoet = "com.squareup:kotlinpoet:1.15.3" squareup-okio = { module = "com.squareup.okio:okio", version.ref = "com-squareup-okio" } squareup-okio-fakefilesystem = { module = "com.squareup.okio:okio-fakefilesystem", version.ref = "com-squareup-okio" } + +[plugins] +spotless = { id = "com.diffplug.spotless", version = "6.23.3" } diff --git a/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/bridge.kt b/mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt similarity index 100% rename from mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/bridge.kt rename to mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt diff --git a/mockwebserver-junit5/src/test/java/mockwebserver3/junit5/internal/ExtensionLifecycleTest.kt b/mockwebserver-junit5/src/test/java/mockwebserver3/junit5/internal/ExtensionLifecycleTest.kt index 989e11aae8bb..62a14c1130b8 100644 --- a/mockwebserver-junit5/src/test/java/mockwebserver3/junit5/internal/ExtensionLifecycleTest.kt +++ b/mockwebserver-junit5/src/test/java/mockwebserver3/junit5/internal/ExtensionLifecycleTest.kt @@ -34,25 +34,25 @@ class ExtensionLifecycleTest { @RegisterExtension val clientTestRule: OkHttpClientTestRule = OkHttpClientTestRule() - lateinit var _server: MockWebServer + lateinit var setUpServer: MockWebServer @BeforeEach fun setup(server: MockWebServer) { - _server = server + this.setUpServer = server assertThat(server.started).isTrue() server.enqueue(MockResponse()) } @AfterEach fun tearDown(server: MockWebServer) { - assertThat(_server).isSameAs(server) + assertThat(setUpServer).isSameAs(server) assertThat(server.started).isTrue() server.enqueue(MockResponse()) } @Test fun testClient(server: MockWebServer) { - assertThat(_server).isSameAs(server) + assertThat(setUpServer).isSameAs(server) assertThat(server.started).isTrue() clientTestRule.newClient().newCall(Request(server.url("/"))).execute().use { assertThat(it.code).isEqualTo(200) diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt b/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt index 6dc5ab5a1bc1..0c6aac9423b1 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt @@ -141,29 +141,30 @@ class MockResponse { internal var trailers: Headers.Builder // At most one of (body,webSocketListener,streamHandler) is non-null. - private var body_: MockResponseBody? = null - private var streamHandler_: StreamHandler? = null - private var webSocketListener_: WebSocketListener? = null + private var bodyVar: MockResponseBody? = null + private var streamHandlerVar: StreamHandler? = null + private var webSocketListenerVar: WebSocketListener? = null + var body: MockResponseBody? - get() = body_ + get() = bodyVar set(value) { - body_ = value - streamHandler_ = null - webSocketListener_ = null + bodyVar = value + streamHandlerVar = null + webSocketListenerVar = null } var streamHandler: StreamHandler? - get() = streamHandler_ + get() = streamHandlerVar set(value) { - streamHandler_ = value - body_ = null - webSocketListener_ = null + streamHandlerVar = value + bodyVar = null + webSocketListenerVar = null } var webSocketListener: WebSocketListener? - get() = webSocketListener_ + get() = webSocketListenerVar set(value) { - webSocketListener_ = value - body_ = null - streamHandler_ = null + webSocketListenerVar = value + bodyVar = null + streamHandlerVar = null } var throttleBytesPerPeriod: Long @@ -185,9 +186,9 @@ class MockResponse { this.inTunnel = false this.informationalResponses = mutableListOf() this.status = "HTTP/1.1 200 OK" - this.body_ = null - this.streamHandler_ = null - this.webSocketListener_ = null + this.bodyVar = null + this.streamHandlerVar = null + this.webSocketListenerVar = null this.headers = Headers.Builder() .add("Content-Length", "0") this.trailers = Headers.Builder() @@ -206,9 +207,9 @@ class MockResponse { this.status = mockResponse.status this.headers = mockResponse.headers.newBuilder() this.trailers = mockResponse.trailers.newBuilder() - this.body_ = mockResponse.body - this.streamHandler_ = mockResponse.streamHandler - this.webSocketListener_ = mockResponse.webSocketListener + this.bodyVar = mockResponse.body + this.streamHandlerVar = mockResponse.streamHandler + this.webSocketListenerVar = mockResponse.webSocketListener this.throttleBytesPerPeriod = mockResponse.throttleBytesPerPeriod this.throttlePeriodNanos = mockResponse.throttlePeriodNanos this.socketPolicy = mockResponse.socketPolicy diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt b/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt index abb657d0425a..3a1ff9d063ff 100644 --- a/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt +++ b/mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt @@ -773,7 +773,8 @@ class MockWebServer : Closeable { random = SecureRandom(), pingIntervalMillis = 0, extensions = WebSocketExtensions.parse(webSocketResponse.headers), - minimumDeflateSize = 0L // Compress all messages if compression is enabled. + // Compress all messages if compression is enabled. + minimumDeflateSize = 0L, ) val name = "MockWebServer WebSocket ${request.path!!}" webSocket.initReaderAndWriter(name, streams) diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/internal/mockResponseBodies.kt b/mockwebserver/src/main/kotlin/mockwebserver3/internal/BufferMockResponseBody.kt similarity index 100% rename from mockwebserver/src/main/kotlin/mockwebserver3/internal/mockResponseBodies.kt rename to mockwebserver/src/main/kotlin/mockwebserver3/internal/BufferMockResponseBody.kt diff --git a/mockwebserver/src/main/kotlin/mockwebserver3/internal/sleep.kt b/mockwebserver/src/main/kotlin/mockwebserver3/internal/SleepNanos.kt similarity index 100% rename from mockwebserver/src/main/kotlin/mockwebserver3/internal/sleep.kt rename to mockwebserver/src/main/kotlin/mockwebserver3/internal/SleepNanos.kt diff --git a/native-image-tests/src/main/kotlin/okhttp3/GenerateClassList.kt b/native-image-tests/src/main/kotlin/okhttp3/GenerateClassList.kt index 4da4d087f577..f18ae68f0653 100644 --- a/native-image-tests/src/main/kotlin/okhttp3/GenerateClassList.kt +++ b/native-image-tests/src/main/kotlin/okhttp3/GenerateClassList.kt @@ -30,8 +30,10 @@ val avoidedTests = setOf( "okhttp3.internal.platform.PlatformTest", "okhttp3.internal.platform.android.AndroidSocketAdapterTest", "okhttp3.osgi.OsgiTest", - "okhttp3.CookiesTest", // hanging - "okhttp3.WholeOperationTimeoutTest", // hanging + // Hanging. + "okhttp3.CookiesTest", + // Hanging. + "okhttp3.WholeOperationTimeoutTest", ) /** @@ -49,4 +51,4 @@ fun main() { .sorted() .distinct() knownTestFile.writeText(testClasses.joinToString("\n")) -} \ No newline at end of file +} diff --git a/okcurl/src/main/kotlin/okhttp3/curl/Main.kt b/okcurl/src/main/kotlin/okhttp3/curl/Main.kt index 773f5d676653..b3e4334e7886 100644 --- a/okcurl/src/main/kotlin/okhttp3/curl/Main.kt +++ b/okcurl/src/main/kotlin/okhttp3/curl/Main.kt @@ -23,7 +23,7 @@ import com.github.ajalt.clikt.parameters.options.multiple import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.types.int import java.security.cert.X509Certificate -import java.util.* +import java.util.Properties import java.util.concurrent.TimeUnit.SECONDS import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLSocketFactory diff --git a/okcurl/src/main/kotlin/okhttp3/curl/internal/-MainCommon.kt b/okcurl/src/main/kotlin/okhttp3/curl/internal/-MainCommon.kt index 194f22e15bec..a2a36415ad08 100644 --- a/okcurl/src/main/kotlin/okhttp3/curl/internal/-MainCommon.kt +++ b/okcurl/src/main/kotlin/okhttp3/curl/internal/-MainCommon.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.curl.internal import java.io.IOException diff --git a/okhttp-brotli/src/main/kotlin/okhttp3/brotli/internal/brotli.kt b/okhttp-brotli/src/main/kotlin/okhttp3/brotli/internal/Uncompress.kt similarity index 100% rename from okhttp-brotli/src/main/kotlin/okhttp3/brotli/internal/brotli.kt rename to okhttp-brotli/src/main/kotlin/okhttp3/brotli/internal/Uncompress.kt diff --git a/okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/package-info.kt b/okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/package-info.kt deleted file mode 100644 index b998f5b89965..000000000000 --- a/okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/package-info.kt +++ /dev/null @@ -1,2 +0,0 @@ -/** A DNS over HTTPS implementation for OkHttp. */ -package okhttp3.dnsoverhttps diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackRoundTripTest.kt b/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackRoundTripTest.kt index c96f3d4118fc..457d2923f9ed 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackRoundTripTest.kt +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackRoundTripTest.kt @@ -25,10 +25,11 @@ import org.junit.jupiter.params.provider.ArgumentsSource /** * Tests for round-tripping headers through hpack. + * + * TODO: update hpack-test-case with the output of our encoder. + * This test will hide complementary bugs in the encoder and decoder, + * We should test that the encoder is producing responses that are */ -// TODO: update hpack-test-case with the output of our encoder. -// This test will hide complementary bugs in the encoder and decoder, -// We should test that the encoder is producing responses that are class HpackRoundTripTest : HpackDecodeTestBase() { internal class StoriesTestProvider : SimpleProvider() { override fun arguments(): List = createStories(RAW_DATA) diff --git a/okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt b/okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt index 6c00f038489e..37290aba8442 100644 --- a/okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt +++ b/okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt @@ -79,15 +79,21 @@ class SimpleIdnaMappingTable internal constructor( private val optionsDelimiter = Options.of( - ".".encodeUtf8(), // 0. - " ".encodeUtf8(), // 1. - ";".encodeUtf8(), // 2. - "#".encodeUtf8(), // 3. - "\n".encodeUtf8(), // 4. + // 0. + ".".encodeUtf8(), + // 1. + " ".encodeUtf8(), + // 2. + ";".encodeUtf8(), + // 3. + "#".encodeUtf8(), + // 4. + "\n".encodeUtf8(), ) private val optionsDot = Options.of( - ".".encodeUtf8(), // 0. + // 0. + ".".encodeUtf8(), ) private const val DELIMITER_DOT = 0 @@ -97,13 +103,20 @@ private const val DELIMITER_HASH = 3 private const val DELIMITER_NEWLINE = 4 private val optionsType = Options.of( - "deviation ".encodeUtf8(), // 0. - "disallowed ".encodeUtf8(), // 1. - "disallowed_STD3_mapped ".encodeUtf8(), // 2. - "disallowed_STD3_valid ".encodeUtf8(), // 3. - "ignored ".encodeUtf8(), // 4. - "mapped ".encodeUtf8(), // 5. - "valid ".encodeUtf8(), // 6. + // 0. + "deviation ".encodeUtf8(), + // 1. + "disallowed ".encodeUtf8(), + // 2. + "disallowed_STD3_mapped ".encodeUtf8(), + // 3. + "disallowed_STD3_valid ".encodeUtf8(), + // 4. + "ignored ".encodeUtf8(), + // 5. + "mapped ".encodeUtf8(), + // 6. + "valid ".encodeUtf8(), ) internal const val TYPE_DEVIATION = 0 diff --git a/okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt b/okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt index 06752272a172..2761da7e29d2 100644 --- a/okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt +++ b/okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt @@ -243,7 +243,14 @@ class HttpLoggingInterceptor @JvmOverloads constructor( val contentLength = responseBody.contentLength() val bodySize = if (contentLength != -1L) "$contentLength-byte" else "unknown-length" logger.log( - "<-- ${response.code}${if (response.message.isEmpty()) "" else ' ' + response.message} ${response.request.url} (${tookMs}ms${if (!logHeaders) ", $bodySize body" else ""})") + buildString { + append("<-- ${response.code}") + if (response.message.isNotEmpty()) append(" ${response.message}") + append(" ${response.request.url} (${tookMs}ms") + if (!logHeaders) append(", $bodySize body") + append(")") + } + ) if (logHeaders) { val headers = response.headers @@ -287,11 +294,13 @@ class HttpLoggingInterceptor @JvmOverloads constructor( logger.log(buffer.clone().readString(charset)) } - if (gzippedLength != null) { - logger.log("<-- END HTTP (${totalMs}ms, ${buffer.size}-byte, $gzippedLength-gzipped-byte body)") - } else { - logger.log("<-- END HTTP (${totalMs}ms, ${buffer.size}-byte body)") - } + logger.log( + buildString { + append("<-- END HTTP (${totalMs}ms, ${buffer.size}-byte") + if (gzippedLength != null) append(", $gzippedLength-gzipped-byte") + append(" body)") + } + ) } } diff --git a/okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/internal/utf8.kt b/okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/internal/IsProbablyUtf8.kt similarity index 100% rename from okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/internal/utf8.kt rename to okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/internal/IsProbablyUtf8.kt diff --git a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt index c4871c6ddf7e..68924e07ae93 100644 --- a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt +++ b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt @@ -41,6 +41,7 @@ import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.extension.RegisterExtension @ExtendWith(MockWebServerExtension::class) +@Suppress("ktlint:standard:max-line-length") class LoggingEventListenerTest { @RegisterExtension val platform = PlatformRule() diff --git a/okhttp-testing-support/src/main/kotlin/okhttp3/DelegatingSSLSocket.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/DelegatingSSLSocket.kt index 50618660b09d..6164010a2681 100644 --- a/okhttp-testing-support/src/main/kotlin/okhttp3/DelegatingSSLSocket.kt +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/DelegatingSSLSocket.kt @@ -18,9 +18,9 @@ package okhttp3 import java.io.IOException import java.io.InputStream import java.io.OutputStream -import java.lang.AssertionError -import java.lang.reflect.InvocationTargetException -import java.net.* +import java.net.InetAddress +import java.net.SocketAddress +import java.net.SocketException import java.nio.channels.SocketChannel import java.util.function.BiFunction import javax.net.ssl.HandshakeCompletedListener diff --git a/okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt b/okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt index 89ed00066a51..4eb96e53150e 100644 --- a/okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt +++ b/okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt @@ -62,7 +62,24 @@ class OkHttpClientTestRule : BeforeEachCallback, AfterEachCallback { var recordFrames = false var recordSslDebug = false - private val sslExcludeFilter = "^(?:Inaccessible trust store|trustStore is|Reload the trust store|Reload trust certs|Reloaded|adding as trusted certificates|Ignore disabled cipher suite|Ignore unsupported cipher suite).*".toRegex() + private val sslExcludeFilter = Regex( + buildString { + append("^(?:") + append( + listOf( + "Inaccessible trust store", + "trustStore is", + "Reload the trust store", + "Reload trust certs", + "Reloaded", + "adding as trusted certificates", + "Ignore disabled cipher suite", + "Ignore unsupported cipher suite", + ).joinToString(separator = "|") + ) + append(").*") + } + ) private val testLogHandler = object : Handler() { override fun publish(record: LogRecord) { @@ -139,7 +156,12 @@ class OkHttpClientTestRule : BeforeEachCallback, AfterEachCallback { val taskRunner = TaskRunner(backend) OkHttpClient.Builder() - .connectionPool(buildConnectionPool(connectionListener = connectionListener, taskRunner = taskRunner)) + .connectionPool( + buildConnectionPool( + connectionListener = connectionListener, + taskRunner = taskRunner, + ) + ) .dispatcher(Dispatcher(backend.executor)) .taskRunnerInternal(taskRunner) } else { @@ -150,7 +172,9 @@ class OkHttpClientTestRule : BeforeEachCallback, AfterEachCallback { private fun loomThreadFactory(): ThreadFactory { val ofVirtual = Thread::class.java.getMethod("ofVirtual").invoke(null) - return Class.forName("java.lang.Thread\$Builder").getMethod("factory").invoke(ofVirtual) as ThreadFactory + return Class.forName("java.lang.Thread\$Builder") + .getMethod("factory") + .invoke(ofVirtual) as ThreadFactory } private fun isLoom(): Boolean { diff --git a/okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt b/okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt index 84b7701ce91b..efca939e6bfb 100644 --- a/okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt +++ b/okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt @@ -43,11 +43,11 @@ import okhttp3.tls.internal.der.CertificateAdapters.generalNameDnsName import okhttp3.tls.internal.der.CertificateAdapters.generalNameIpAddress import okhttp3.tls.internal.der.Extension import okhttp3.tls.internal.der.ObjectIdentifiers -import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints -import okhttp3.tls.internal.der.ObjectIdentifiers.organizationalUnitName -import okhttp3.tls.internal.der.ObjectIdentifiers.sha256WithRSAEncryption -import okhttp3.tls.internal.der.ObjectIdentifiers.sha256withEcdsa -import okhttp3.tls.internal.der.ObjectIdentifiers.subjectAlternativeName +import okhttp3.tls.internal.der.ObjectIdentifiers.BASIC_CONSTRAINTS +import okhttp3.tls.internal.der.ObjectIdentifiers.ORGANIZATIONAL_UNIT_NAME +import okhttp3.tls.internal.der.ObjectIdentifiers.SHA256_WITH_RSA_ENCRYPTION +import okhttp3.tls.internal.der.ObjectIdentifiers.SHA256_WITH_ECDSA +import okhttp3.tls.internal.der.ObjectIdentifiers.SUBJECT_ALTERNATIVE_NAME import okhttp3.tls.internal.der.TbsCertificate import okhttp3.tls.internal.der.Validity import okio.ByteString @@ -346,7 +346,8 @@ class HeldCertificate( // Subset of certificate data that's covered by the signature. val tbsCertificate = TbsCertificate( - version = 2L, // v3. + // v3: + version = 2L, serialNumber = serialNumber ?: BigInteger.ONE, signature = signatureAlgorithm, issuer = issuer, @@ -383,13 +384,13 @@ class HeldCertificate( if (organizationalUnit != null) { result += listOf(AttributeTypeAndValue( - type = organizationalUnitName, + type = ORGANIZATIONAL_UNIT_NAME, value = organizationalUnit )) } result += listOf(AttributeTypeAndValue( - type = ObjectIdentifiers.commonName, + type = ObjectIdentifiers.COMMON_NAME, value = commonName ?: UUID.randomUUID().toString() )) @@ -410,7 +411,7 @@ class HeldCertificate( if (maxIntermediateCas != -1) { result += Extension( - id = basicConstraints, + id = BASIC_CONSTRAINTS, critical = true, value = BasicConstraints( ca = true, @@ -431,7 +432,7 @@ class HeldCertificate( } } result += Extension( - id = subjectAlternativeName, + id = SUBJECT_ALTERNATIVE_NAME, critical = true, value = extensionValue ) @@ -443,11 +444,11 @@ class HeldCertificate( private fun signatureAlgorithm(signedByKeyPair: KeyPair): AlgorithmIdentifier { return when (signedByKeyPair.private) { is RSAPrivateKey -> AlgorithmIdentifier( - algorithm = sha256WithRSAEncryption, + algorithm = SHA256_WITH_RSA_ENCRYPTION, parameters = null ) else -> AlgorithmIdentifier( - algorithm = sha256withEcdsa, + algorithm = SHA256_WITH_ECDSA, parameters = ByteString.EMPTY ) } diff --git a/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt b/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt index a1f93b38b350..4aa724e9ee4a 100644 --- a/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt +++ b/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt @@ -115,8 +115,9 @@ internal object Adapters { * ``` * ' () + , - . / : = ? * ``` + * + * TODO(jwilson): constrain to printable string characters. */ - // TODO(jwilson): constrain to printable string characters. val PRINTABLE_STRING = BasicDerAdapter( name = "PRINTABLE STRING", tagClass = DerHeader.TAG_CLASS_UNIVERSAL, @@ -130,8 +131,9 @@ internal object Adapters { /** * Based on International Alphabet No. 5. Note that there are bytes that IA5 and US-ASCII * disagree on interpretation. + * + * TODO(jwilson): constrain to IA5 characters. */ - // TODO(jwilson): constrain to IA5 characters. val IA5_STRING = BasicDerAdapter( name = "IA5 STRING", tagClass = DerHeader.TAG_CLASS_UNIVERSAL, diff --git a/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/certificates.kt b/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Certificate.kt similarity index 92% rename from okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/certificates.kt rename to okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Certificate.kt index 9a468cba5b0b..36255a96197d 100644 --- a/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/certificates.kt +++ b/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Certificate.kt @@ -35,7 +35,7 @@ internal data class Certificate( get() { return tbsCertificate.subject .flatten() - .firstOrNull { it.type == ObjectIdentifiers.commonName } + .firstOrNull { it.type == ObjectIdentifiers.COMMON_NAME } ?.value } @@ -43,21 +43,21 @@ internal data class Certificate( get() { return tbsCertificate.subject .flatten() - .firstOrNull { it.type == ObjectIdentifiers.organizationalUnitName } + .firstOrNull { it.type == ObjectIdentifiers.ORGANIZATIONAL_UNIT_NAME } ?.value } val subjectAlternativeNames: Extension? get() { return tbsCertificate.extensions.firstOrNull { - it.id == ObjectIdentifiers.subjectAlternativeName + it.id == ObjectIdentifiers.SUBJECT_ALTERNATIVE_NAME } } val basicConstraints: Extension get() { return tbsCertificate.extensions.first { - it.id == ObjectIdentifiers.basicConstraints + it.id == ObjectIdentifiers.BASIC_CONSTRAINTS } } @@ -109,8 +109,8 @@ internal data class TbsCertificate( val signatureAlgorithmName: String get() { return when (signature.algorithm) { - ObjectIdentifiers.sha256WithRSAEncryption -> "SHA256WithRSA" - ObjectIdentifiers.sha256withEcdsa -> "SHA256withECDSA" + ObjectIdentifiers.SHA256_WITH_RSA_ENCRYPTION -> "SHA256WithRSA" + ObjectIdentifiers.SHA256_WITH_ECDSA -> "SHA256withECDSA" else -> error("unexpected signature algorithm: ${signature.algorithm}") } } @@ -180,8 +180,9 @@ internal data class BasicConstraints( /** A private key. Note that this class doesn't support attributes or an embedded public key. */ internal data class PrivateKeyInfo( - val version: Long, // v1(0), v2(1) - val algorithmIdentifier: AlgorithmIdentifier, // v1(0), v2(1) + // v1(0), v2(1). + val version: Long, + val algorithmIdentifier: AlgorithmIdentifier, val privateKey: ByteString ) { // Avoid Long.hashCode(long) which isn't available on Android 5. diff --git a/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt b/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt index 3af4ac68367f..fbd4f669f381 100644 --- a/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt +++ b/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt @@ -104,9 +104,9 @@ internal object CertificateAdapters { // This type is pretty strange. The spec says that for certain algorithms we must encode null // when it is present, and for others we must omit it! // https://tools.ietf.org/html/rfc4055#section-2.1 - ObjectIdentifiers.sha256WithRSAEncryption -> Adapters.NULL - ObjectIdentifiers.rsaEncryption -> Adapters.NULL - ObjectIdentifiers.ecPublicKey -> Adapters.OBJECT_IDENTIFIER + ObjectIdentifiers.SHA256_WITH_RSA_ENCRYPTION -> Adapters.NULL + ObjectIdentifiers.RSA_ENCRYPTION -> Adapters.NULL + ObjectIdentifiers.EC_PUBLIC_KEY -> Adapters.OBJECT_IDENTIFIER else -> null } } @@ -206,8 +206,8 @@ internal object CertificateAdapters { */ private val extensionValue: BasicDerAdapter = Adapters.usingTypeHint { typeHint -> when (typeHint) { - ObjectIdentifiers.subjectAlternativeName -> subjectAlternativeName - ObjectIdentifiers.basicConstraints -> basicConstraints + ObjectIdentifiers.SUBJECT_ALTERNATIVE_NAME -> subjectAlternativeName + ObjectIdentifiers.BASIC_CONSTRAINTS -> basicConstraints else -> null } }.withExplicitBox( @@ -349,7 +349,10 @@ internal object CertificateAdapters { */ internal val tbsCertificate: BasicDerAdapter = Adapters.sequence( "TBSCertificate", - Adapters.INTEGER_AS_LONG.withExplicitBox(tag = 0L).optional(defaultValue = 0), // v1 == 0 + Adapters.INTEGER_AS_LONG + .withExplicitBox(tag = 0L) + // v1 == 0. + .optional(defaultValue = 0), Adapters.INTEGER_AS_BIG_INTEGER, algorithmIdentifier, name, diff --git a/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/ObjectIdentifiers.kt b/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/ObjectIdentifiers.kt index 4bafafb7f7d7..e66a21815dc9 100644 --- a/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/ObjectIdentifiers.kt +++ b/okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/ObjectIdentifiers.kt @@ -17,12 +17,12 @@ package okhttp3.tls.internal.der /** ASN.1 object identifiers used internally by this implementation. */ internal object ObjectIdentifiers { - const val ecPublicKey = "1.2.840.10045.2.1" - const val sha256withEcdsa = "1.2.840.10045.4.3.2" - const val rsaEncryption = "1.2.840.113549.1.1.1" - const val sha256WithRSAEncryption = "1.2.840.113549.1.1.11" - const val subjectAlternativeName = "2.5.29.17" - const val basicConstraints = "2.5.29.19" - const val commonName = "2.5.4.3" - const val organizationalUnitName = "2.5.4.11" + const val EC_PUBLIC_KEY = "1.2.840.10045.2.1" + const val SHA256_WITH_ECDSA = "1.2.840.10045.4.3.2" + const val RSA_ENCRYPTION = "1.2.840.113549.1.1.1" + const val SHA256_WITH_RSA_ENCRYPTION = "1.2.840.113549.1.1.11" + const val SUBJECT_ALTERNATIVE_NAME = "2.5.29.17" + const val BASIC_CONSTRAINTS = "2.5.29.19" + const val COMMON_NAME = "2.5.4.3" + const val ORGANIZATIONAL_UNIT_NAME = "2.5.4.11" } diff --git a/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt b/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt index 9b41e767aa20..e2479d924994 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt +++ b/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt @@ -155,7 +155,7 @@ class HandshakeCertificatesTest { rawSocket, rawSocket.inetAddress.hostAddress, rawSocket.port, - true /* autoClose */ + true ) as SSLSocket sslSocket.use { sslSocket.useClientMode = false @@ -177,7 +177,7 @@ class HandshakeCertificatesTest { rawSocket, rawSocket.inetAddress.hostAddress, rawSocket.port, - true /* autoClose */ + true ) as SSLSocket sslSocket.use { sslSocket.startHandshake() diff --git a/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt b/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt index 5a47fc4454d9..c4e0cce03dfe 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt +++ b/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt @@ -29,12 +29,12 @@ import java.util.Date import java.util.TimeZone import okhttp3.tls.HeldCertificate import okhttp3.tls.decodeCertificatePem -import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints -import okhttp3.tls.internal.der.ObjectIdentifiers.commonName -import okhttp3.tls.internal.der.ObjectIdentifiers.organizationalUnitName -import okhttp3.tls.internal.der.ObjectIdentifiers.rsaEncryption -import okhttp3.tls.internal.der.ObjectIdentifiers.sha256WithRSAEncryption -import okhttp3.tls.internal.der.ObjectIdentifiers.subjectAlternativeName +import okhttp3.tls.internal.der.ObjectIdentifiers.BASIC_CONSTRAINTS +import okhttp3.tls.internal.der.ObjectIdentifiers.COMMON_NAME +import okhttp3.tls.internal.der.ObjectIdentifiers.ORGANIZATIONAL_UNIT_NAME +import okhttp3.tls.internal.der.ObjectIdentifiers.RSA_ENCRYPTION +import okhttp3.tls.internal.der.ObjectIdentifiers.SHA256_WITH_RSA_ENCRYPTION +import okhttp3.tls.internal.der.ObjectIdentifiers.SUBJECT_ALTERNATIVE_NAME import okio.Buffer import okio.ByteString import okio.ByteString.Companion.decodeBase64 @@ -100,16 +100,17 @@ internal class DerCertificatesTest { assertThat(okHttpCertificate).isEqualTo( Certificate( tbsCertificate = TbsCertificate( - version = 2L, // v3. + // v3. + version = 2L, serialNumber = BigInteger.ONE, signature = AlgorithmIdentifier( - algorithm = sha256WithRSAEncryption, + algorithm = SHA256_WITH_RSA_ENCRYPTION, parameters = null ), issuer = listOf( listOf( AttributeTypeAndValue( - type = commonName, + type = COMMON_NAME, value = "cash.app" ) ) @@ -121,14 +122,14 @@ internal class DerCertificatesTest { subject = listOf( listOf( AttributeTypeAndValue( - type = commonName, + type = COMMON_NAME, value = "cash.app" ) ) ), subjectPublicKeyInfo = SubjectPublicKeyInfo( algorithm = AlgorithmIdentifier( - algorithm = rsaEncryption, + algorithm = RSA_ENCRYPTION, parameters = null ), subjectPublicKey = BitString( @@ -141,7 +142,7 @@ internal class DerCertificatesTest { extensions = listOf() ), signatureAlgorithm = AlgorithmIdentifier( - algorithm = sha256WithRSAEncryption, + algorithm = SHA256_WITH_RSA_ENCRYPTION, parameters = null ), signatureValue = BitString( @@ -215,10 +216,11 @@ internal class DerCertificatesTest { assertThat(okHttpCertificate).isEqualTo( Certificate( tbsCertificate = TbsCertificate( - version = 2L, // v3. + // v3. + version = 2L, serialNumber = BigInteger("1372799044"), signature = AlgorithmIdentifier( - algorithm = sha256WithRSAEncryption, + algorithm = SHA256_WITH_RSA_ENCRYPTION, parameters = null ), issuer = listOf( @@ -236,19 +238,19 @@ internal class DerCertificatesTest { ), listOf( AttributeTypeAndValue( - type = organizationalUnitName, + type = ORGANIZATIONAL_UNIT_NAME, value = "www.entrust.net/CPS is incorporated by reference" ) ), listOf( AttributeTypeAndValue( - type = organizationalUnitName, + type = ORGANIZATIONAL_UNIT_NAME, value = "(c) 2006 Entrust, Inc." ) ), listOf( AttributeTypeAndValue( - type = commonName, + type = COMMON_NAME, value = "Entrust Root Certification Authority" ) ) @@ -272,26 +274,26 @@ internal class DerCertificatesTest { ), listOf( AttributeTypeAndValue( - type = organizationalUnitName, + type = ORGANIZATIONAL_UNIT_NAME, value = "See www.entrust.net/legal-terms" ) ), listOf( AttributeTypeAndValue( - type = organizationalUnitName, + type = ORGANIZATIONAL_UNIT_NAME, value = "(c) 2009 Entrust, Inc. - for authorized use only" ) ), listOf( AttributeTypeAndValue( - type = commonName, + type = COMMON_NAME, value = "Entrust Root Certification Authority - G2" ) ) ), subjectPublicKeyInfo = SubjectPublicKeyInfo( algorithm = AlgorithmIdentifier( - algorithm = rsaEncryption, + algorithm = RSA_ENCRYPTION, parameters = null ), subjectPublicKey = BitString( @@ -308,7 +310,7 @@ internal class DerCertificatesTest { value = "03020106".decodeHex() ), Extension( - id = basicConstraints, + id = BASIC_CONSTRAINTS, critical = true, value = BasicConstraints( ca = true, @@ -346,7 +348,7 @@ internal class DerCertificatesTest { ) ), signatureAlgorithm = AlgorithmIdentifier( - algorithm = sha256WithRSAEncryption, + algorithm = SHA256_WITH_RSA_ENCRYPTION, parameters = null ), signatureValue = BitString( @@ -432,10 +434,11 @@ internal class DerCertificatesTest { assertThat(okHttpCertificate).isEqualTo( Certificate( tbsCertificate = TbsCertificate( - version = 2L, // v3. + // v3. + version = 2L, serialNumber = BigInteger("253093332781973022312510445874391888413"), signature = AlgorithmIdentifier( - algorithm = sha256WithRSAEncryption, + algorithm = SHA256_WITH_RSA_ENCRYPTION, parameters = null ), issuer = listOf( @@ -453,19 +456,19 @@ internal class DerCertificatesTest { ), listOf( AttributeTypeAndValue( - type = organizationalUnitName, + type = ORGANIZATIONAL_UNIT_NAME, value = "See www.entrust.net/legal-terms" ) ), listOf( AttributeTypeAndValue( - type = organizationalUnitName, + type = ORGANIZATIONAL_UNIT_NAME, value = "(c) 2014 Entrust, Inc. - for authorized use only" ) ), listOf( AttributeTypeAndValue( - type = commonName, + type = COMMON_NAME, value = "Entrust Certification Authority - L1M" ) ) @@ -525,14 +528,14 @@ internal class DerCertificatesTest { ), listOf( AttributeTypeAndValue( - type = commonName, + type = COMMON_NAME, value = "cash.app" ) ) ), subjectPublicKeyInfo = SubjectPublicKeyInfo( algorithm = AlgorithmIdentifier( - algorithm = rsaEncryption, + algorithm = RSA_ENCRYPTION, parameters = null ), subjectPublicKey = BitString( @@ -544,7 +547,7 @@ internal class DerCertificatesTest { subjectUniqueID = null, extensions = listOf( Extension( - id = subjectAlternativeName, + id = SUBJECT_ALTERNATIVE_NAME, critical = false, value = listOf( CertificateAdapters.generalNameDnsName to "cash.app", @@ -608,7 +611,7 @@ internal class DerCertificatesTest { value = "041475fd24c2df592599e32f3373e18c0450dd1b87b6".decodeHex() ), Extension( - id = basicConstraints, + id = BASIC_CONSTRAINTS, critical = false, value = BasicConstraints( ca = false, @@ -618,7 +621,7 @@ internal class DerCertificatesTest { ) ), signatureAlgorithm = AlgorithmIdentifier( - algorithm = sha256WithRSAEncryption, + algorithm = SHA256_WITH_RSA_ENCRYPTION, parameters = null ), signatureValue = BitString( @@ -647,14 +650,14 @@ internal class DerCertificatesTest { .fromDer(certificateByteString) assertThat(okHttpCertificate.basicConstraints).isEqualTo(Extension( - id = basicConstraints, + id = BASIC_CONSTRAINTS, critical = true, value = BasicConstraints(true, 3) )) assertThat(okHttpCertificate.commonName).isEqualTo("Jurassic Park") assertThat(okHttpCertificate.organizationalUnitName).isEqualTo("Gene Research") assertThat(okHttpCertificate.subjectAlternativeNames).isEqualTo(Extension( - id = subjectAlternativeName, + id = SUBJECT_ALTERNATIVE_NAME, critical = true, value = listOf( CertificateAdapters.generalNameDnsName to "*.example.com", @@ -701,7 +704,7 @@ internal class DerCertificatesTest { "mIE65swMM5/RNhS4aFjez/MwxFNOHaxc9VgCwYPXCLOtdf7AVovdyG0XWgbUXH+NyxKwboE").decodeBase64()!! val x509PublicKey = encodeKey( - algorithm = rsaEncryption, + algorithm = RSA_ENCRYPTION, publicKeyBytes = publicKeyBytes ) val keyFactory = KeyFactory.getInstance("RSA") @@ -817,7 +820,7 @@ internal class DerCertificatesTest { val decoded = CertificateAdapters.privateKeyInfo.fromDer(privateKeyInfoByteString) assertThat(decoded.version).isEqualTo(0L) - assertThat(decoded.algorithmIdentifier).isEqualTo(AlgorithmIdentifier(rsaEncryption, null)) + assertThat(decoded.algorithmIdentifier).isEqualTo(AlgorithmIdentifier(RSA_ENCRYPTION, null)) assertThat(decoded.privateKey.size).isEqualTo(607) val encoded = CertificateAdapters.privateKeyInfo.toDer(decoded) @@ -915,7 +918,7 @@ internal class DerCertificatesTest { val decoded = CertificateAdapters.certificate.fromDer(certificateByteString) assertThat(decoded.subjectAlternativeNames).isEqualTo(Extension( - id = subjectAlternativeName, + id = SUBJECT_ALTERNATIVE_NAME, critical = false, value = listOf( Adapters.ANY_VALUE to AnyValue( diff --git a/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt b/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt index fafff4efcd29..aeac49e19a9a 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt +++ b/okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt @@ -30,17 +30,16 @@ import java.util.TimeZone import kotlin.test.assertFailsWith import okhttp3.tls.internal.der.CertificateAdapters.generalNameDnsName import okhttp3.tls.internal.der.CertificateAdapters.generalNameIpAddress -import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints -import okhttp3.tls.internal.der.ObjectIdentifiers.commonName -import okhttp3.tls.internal.der.ObjectIdentifiers.sha256WithRSAEncryption -import okhttp3.tls.internal.der.ObjectIdentifiers.subjectAlternativeName +import okhttp3.tls.internal.der.ObjectIdentifiers.BASIC_CONSTRAINTS +import okhttp3.tls.internal.der.ObjectIdentifiers.COMMON_NAME +import okhttp3.tls.internal.der.ObjectIdentifiers.SHA256_WITH_RSA_ENCRYPTION +import okhttp3.tls.internal.der.ObjectIdentifiers.SUBJECT_ALTERNATIVE_NAME import okio.Buffer import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.encodeUtf8 import okio.ByteString.Companion.toByteString import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test -import org.junit.jupiter.api.fail internal class DerTest { @Test fun `decode tag and length`() { @@ -740,8 +739,8 @@ internal class DerTest { @Test fun `decode object identifier`() { val bytes = "06092a864886f70d01010b".decodeHex() - assertThat(Adapters.OBJECT_IDENTIFIER.fromDer(bytes)).isEqualTo(sha256WithRSAEncryption) - assertThat(Adapters.OBJECT_IDENTIFIER.toDer(sha256WithRSAEncryption)).isEqualTo(bytes) + assertThat(Adapters.OBJECT_IDENTIFIER.fromDer(bytes)).isEqualTo(SHA256_WITH_RSA_ENCRYPTION) + assertThat(Adapters.OBJECT_IDENTIFIER.toDer(SHA256_WITH_RSA_ENCRYPTION)).isEqualTo(bytes) } @Test fun `null value`() { @@ -753,7 +752,7 @@ internal class DerTest { @Test fun `sequence algorithm`() { val bytes = "300d06092a864886f70d01010b0500".decodeHex() val algorithmIdentifier = AlgorithmIdentifier( - algorithm = sha256WithRSAEncryption, + algorithm = SHA256_WITH_RSA_ENCRYPTION, parameters = null ) assertThat(CertificateAdapters.algorithmIdentifier.fromDer(bytes)) @@ -856,7 +855,7 @@ internal class DerTest { @Test fun `extension with type hint for basic constraints`() { val extension = Extension( - basicConstraints, + BASIC_CONSTRAINTS, false, BasicConstraints(true, 4) ) @@ -870,7 +869,7 @@ internal class DerTest { @Test fun `extension with type hint for subject alternative names`() { val extension = Extension( - subjectAlternativeName, + SUBJECT_ALTERNATIVE_NAME, false, listOf( generalNameDnsName to "cash.app", @@ -887,7 +886,8 @@ internal class DerTest { @Test fun `extension with unknown type hint`() { val extension = Extension( - commonName, // common name is not an extension. + // common name is not an extension. + COMMON_NAME, false, "3006800109810109".decodeHex() ) diff --git a/okhttp/src/main/kotlin/okhttp3/-JvmPlatform.kt b/okhttp/src/main/kotlin/okhttp3/-JvmPlatform.kt index 4e238d6e506d..ca0f158f1d7b 100644 --- a/okhttp/src/main/kotlin/okhttp3/-JvmPlatform.kt +++ b/okhttp/src/main/kotlin/okhttp3/-JvmPlatform.kt @@ -14,7 +14,7 @@ * limitations under the License. * */ - +@file:Suppress("ktlint:standard:filename") package okhttp3 typealias ProtocolException = java.net.ProtocolException diff --git a/okhttp/src/main/kotlin/okhttp3/Cookie.kt b/okhttp/src/main/kotlin/okhttp3/Cookie.kt index bd94aa4fe0b2..3663fc6c560d 100644 --- a/okhttp/src/main/kotlin/okhttp3/Cookie.kt +++ b/okhttp/src/main/kotlin/okhttp3/Cookie.kt @@ -81,8 +81,12 @@ class Cookie private constructor( */ @get:JvmName("httpOnly") val httpOnly: Boolean, - /** Returns true if this cookie does not expire at the end of the current session. */ - @get:JvmName("persistent") val persistent: Boolean, // True if 'expires' or 'max-age' is present. + /** + * Returns true if this cookie does not expire at the end of the current session. + * + * This is true if either 'expires' or 'max-age' is present. + */ + @get:JvmName("persistent") val persistent: Boolean, /** * Returns true if this cookie's domain should be interpreted as a single host name, or false if @@ -92,8 +96,10 @@ class Cookie private constructor( * For example, suppose the cookie's domain is `example.com`. If this flag is true it matches * **only** `example.com`. If this flag is false it matches `example.com` and all subdomains * including `api.example.com`, `www.example.com`, and `beta.api.example.com`. + * + * This is true unless 'domain' is present. */ - @get:JvmName("hostOnly") val hostOnly: Boolean, // True unless 'domain' is present. + @get:JvmName("hostOnly") val hostOnly: Boolean, /** * Returns a string describing whether this cookie is sent for cross-site calls. diff --git a/okhttp/src/main/kotlin/okhttp3/FormBody.kt b/okhttp/src/main/kotlin/okhttp3/FormBody.kt index 117b3cff9a59..b9a7c2a80a42 100644 --- a/okhttp/src/main/kotlin/okhttp3/FormBody.kt +++ b/okhttp/src/main/kotlin/okhttp3/FormBody.kt @@ -92,12 +92,14 @@ class FormBody internal constructor( fun add(name: String, value: String) = apply { names += name.canonicalizeWithCharset( encodeSet = FORM_ENCODE_SET, - plusIsSpace = false, // plus is encoded as `%2B`, space is encoded as plus. + // Plus is encoded as `%2B`, space is encoded as plus. + plusIsSpace = false, charset = charset ) values += value.canonicalizeWithCharset( encodeSet = FORM_ENCODE_SET, - plusIsSpace = false, // plus is encoded as `%2B`, space is encoded as plus. + // Plus is encoded as `%2B`, space is encoded as plus. + plusIsSpace = false, charset = charset ) } diff --git a/okhttp/src/main/kotlin/okhttp3/MultipartReader.kt b/okhttp/src/main/kotlin/okhttp3/MultipartReader.kt index f8956671a26b..2a7bf6beae60 100644 --- a/okhttp/src/main/kotlin/okhttp3/MultipartReader.kt +++ b/okhttp/src/main/kotlin/okhttp3/MultipartReader.kt @@ -200,10 +200,17 @@ class MultipartReader @Throws(IOException::class) constructor( internal companion object { /** These options follow the boundary. */ val afterBoundaryOptions = Options.of( - "\r\n".encodeUtf8(), // 0. "\r\n" More parts. - "--".encodeUtf8(), // 1. "--" No more parts. - " ".encodeUtf8(), // 2. " " Optional whitespace. Only used if there are more parts. - "\t".encodeUtf8() // 3. "\t" Optional whitespace. Only used if there are more parts. + // 0. "\r\n" More parts. + "\r\n".encodeUtf8(), + + // 1. "--" No more parts. + "--".encodeUtf8(), + + // 2. " " Optional whitespace. Only used if there are more parts. + " ".encodeUtf8(), + + // 3. "\t" Optional whitespace. Only used if there are more parts. + "\t".encodeUtf8(), ) } } diff --git a/okhttp/src/main/kotlin/okhttp3/OkHttpClient.kt b/okhttp/src/main/kotlin/okhttp3/OkHttpClient.kt index 97b23a905ec7..ad694ca4585a 100644 --- a/okhttp/src/main/kotlin/okhttp3/OkHttpClient.kt +++ b/okhttp/src/main/kotlin/okhttp3/OkHttpClient.kt @@ -29,6 +29,7 @@ import javax.net.SocketFactory import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLSocketFactory import javax.net.ssl.X509TrustManager +import kotlin.time.Duration as KotlinDuration import okhttp3.Protocol.HTTP_1_1 import okhttp3.Protocol.HTTP_2 import okhttp3.internal.asFactory @@ -45,7 +46,6 @@ import okhttp3.internal.toImmutableList import okhttp3.internal.ws.RealWebSocket import okio.Sink import okio.Source -import kotlin.time.Duration as KotlinDuration import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement /** @@ -290,7 +290,8 @@ open class OkHttpClient internal constructor( listener = listener, random = Random(), pingIntervalMillis = pingIntervalMillis.toLong(), - extensions = null, // Always null for clients. + // extensions is always null for clients: + extensions = null, minimumDeflateSize = minWebSocketMessageToCompress ) webSocket.connect(this) diff --git a/okhttp/src/main/kotlin/okhttp3/Request.kt b/okhttp/src/main/kotlin/okhttp3/Request.kt index 5e8bf27af87f..1976fd536641 100644 --- a/okhttp/src/main/kotlin/okhttp3/Request.kt +++ b/okhttp/src/main/kotlin/okhttp3/Request.kt @@ -71,7 +71,8 @@ class Request internal constructor(builder: Builder) { constructor( url: HttpUrl, headers: Headers = headersOf(), - method: String = "\u0000", // Sentinel value chooses based on what the body is. + // '\u0000' is a sentinel value that'll choose based on what the body is: + method: String = "\u0000", body: RequestBody? = null, ) : this( Builder() diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-CacheControlCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-CacheControlCommon.kt index 8871efa3a24a..c91ba7a2eac4 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-CacheControlCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-CacheControlCommon.kt @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal -import kotlin.time.Duration import kotlin.time.DurationUnit import kotlin.time.toDuration import okhttp3.CacheControl diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-ChallengeCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-ChallengeCommon.kt index 88fdcdbc2100..46b49f88968c 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-ChallengeCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-ChallengeCommon.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import okhttp3.Challenge diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-HeadersCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-HeadersCommon.kt index 79d2b3920fcc..cf799e96bb0c 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-HeadersCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-HeadersCommon.kt @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import okhttp3.Headers diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-HostnamesCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-HostnamesCommon.kt index b1f7539338c3..bd6525edb03d 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-HostnamesCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-HostnamesCommon.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import okhttp3.internal.idn.IDNA_MAPPING_TABLE diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-HttpUrlCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-HttpUrlCommon.kt index e2981b5f3ab6..01b476228c62 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-HttpUrlCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-HttpUrlCommon.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import kotlin.jvm.JvmStatic diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-HttpUrlJvm.kt b/okhttp/src/main/kotlin/okhttp3/internal/-HttpUrlJvm.kt index dc9cdc951264..285c448679df 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-HttpUrlJvm.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-HttpUrlJvm.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import java.nio.charset.Charset diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-MediaTypeCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-MediaTypeCommon.kt index 9932062dd340..26bfa772c423 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-MediaTypeCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-MediaTypeCommon.kt @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import okhttp3.MediaType diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-NormalizeJvm.kt b/okhttp/src/main/kotlin/okhttp3/internal/-NormalizeJvm.kt index 8367e035898b..ee73bef04566 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-NormalizeJvm.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-NormalizeJvm.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import java.text.Normalizer diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-RequestBodyCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-RequestBodyCommon.kt index 37d085f6710e..432e76b99ea2 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-RequestBodyCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-RequestBodyCommon.kt @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import okhttp3.MediaType diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-RequestCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-RequestCommon.kt index 6c0cb6e3bdd8..ce3bcb111880 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-RequestCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-RequestCommon.kt @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import kotlin.reflect.KClass diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-ResponseBodyCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-ResponseBodyCommon.kt index 7b91488ad70c..e2a951f4db75 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-ResponseBodyCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-ResponseBodyCommon.kt @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import okhttp3.MediaType diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-ResponseCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-ResponseCommon.kt index 9899dfea5cf2..62dd823aa18c 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-ResponseCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-ResponseCommon.kt @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import kotlin.jvm.JvmOverloads diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-UtilCommon.kt b/okhttp/src/main/kotlin/okhttp3/internal/-UtilCommon.kt index d7c68db737da..18f701887403 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-UtilCommon.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-UtilCommon.kt @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal -import kotlin.jvm.JvmField import okhttp3.Headers import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody @@ -46,11 +46,20 @@ val EMPTY_BYTE_ARRAY: ByteArray = ByteArray(0) /** Byte order marks. */ internal val UNICODE_BOMS = Options.of( - "efbbbf".decodeHex(), // UTF-8 - "feff".decodeHex(), // UTF-16BE - "fffe".decodeHex(), // UTF-16LE - "0000ffff".decodeHex(), // UTF-32BE - "ffff0000".decodeHex() // UTF-32LE + // UTF-8. + "efbbbf".decodeHex(), + + // UTF-16BE. + "feff".decodeHex(), + + // UTF-16LE. + "fffe".decodeHex(), + + // UTF-32BE. + "0000ffff".decodeHex(), + + // UTF-32LE. + "ffff0000".decodeHex(), ) /** @@ -364,7 +373,7 @@ internal inline fun Iterable.filterList(predicate: T.() -> Boolean): List return result } -internal const val userAgent: String = "okhttp/${CONST_VERSION}" +internal const val USER_AGENT: String = "okhttp/${CONST_VERSION}" internal fun checkOffsetAndCount(arrayLength: Long, offset: Long, count: Long) { if (offset or count < 0L || offset > arrayLength || arrayLength - offset < count) { diff --git a/okhttp/src/main/kotlin/okhttp3/internal/-UtilJvm.kt b/okhttp/src/main/kotlin/okhttp3/internal/-UtilJvm.kt index b239b279180b..ee21dfe5d220 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/-UtilJvm.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/-UtilJvm.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import java.io.IOException diff --git a/okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskQueue.kt b/okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskQueue.kt index bfaa329cc35d..1e2258e4b046 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskQueue.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskQueue.kt @@ -79,8 +79,11 @@ class TaskQueue internal constructor( } } - /** Overload of [schedule] that uses a lambda for a repeating task. */ - // TODO: make this inline once this is fixed: https://github.com/oracle/graal/issues/3466 + /** + * Overload of [schedule] that uses a lambda for a repeating task. + * + * TODO: make this inline once this is fixed: https://github.com/oracle/graal/issues/3466 + */ fun schedule( name: String, delayNanos: Long = 0L, @@ -93,8 +96,11 @@ class TaskQueue internal constructor( }, delayNanos) } - /** Executes [block] once on a task runner thread. */ - // TODO: make this inline once this is fixed: https://github.com/oracle/graal/issues/3466 + /** + * Executes [block] once on a task runner thread. + * + * TODO: make this inline once this is fixed: https://github.com/oracle/graal/issues/3466 + */ fun execute( name: String, delayNanos: Long = 0L, diff --git a/okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskRunner.kt b/okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskRunner.kt index 109e49e8fd01..7d86a5f90c75 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskRunner.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskRunner.kt @@ -272,9 +272,12 @@ class TaskRunner( class RealBackend(threadFactory: ThreadFactory) : Backend { val executor = ThreadPoolExecutor( - 0, // corePoolSize. - Int.MAX_VALUE, // maximumPoolSize. - 60L, TimeUnit.SECONDS, // keepAliveTime. + // corePoolSize: + 0, + // maximumPoolSize: + Int.MAX_VALUE, + // keepAliveTime: + 60L, TimeUnit.SECONDS, SynchronousQueue(), threadFactory ) diff --git a/okhttp/src/main/kotlin/okhttp3/internal/connection/ConnectPlan.kt b/okhttp/src/main/kotlin/okhttp3/internal/connection/ConnectPlan.kt index 8941b024147d..89d8bb72b377 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/connection/ConnectPlan.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/connection/ConnectPlan.kt @@ -184,7 +184,8 @@ class ConnectPlan( rawSocket, route.address.url.host, route.address.url.port, - true /* autoClose */ + // autoClose: + true ) as SSLSocket val tlsEquipPlan = planWithCurrentOrInitialConnectionSpec(connectionSpecs, sslSocket) @@ -409,7 +410,8 @@ class ConnectPlan( val source = this.source!! val sink = this.sink!! val tunnelCodec = Http1ExchangeCodec( - client = null, // No client for CONNECT tunnels. + // No client for CONNECT tunnels: + client = null, carrier = this, source = source, sink = sink diff --git a/okhttp/src/main/kotlin/okhttp3/internal/connection/ConnectionSpecSelector.kt b/okhttp/src/main/kotlin/okhttp3/internal/connection/ConnectionSpecSelector.kt deleted file mode 100644 index 27e42cb59341..000000000000 --- a/okhttp/src/main/kotlin/okhttp3/internal/connection/ConnectionSpecSelector.kt +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2015 Square, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package okhttp3.internal.connection - -import java.io.IOException -import java.io.InterruptedIOException -import java.net.ProtocolException -import java.security.cert.CertificateException -import javax.net.ssl.SSLException -import javax.net.ssl.SSLHandshakeException -import javax.net.ssl.SSLPeerUnverifiedException - diff --git a/okhttp/src/main/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt b/okhttp/src/main/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt index bfbbcd05944e..19c45b7a93e0 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt @@ -28,13 +28,13 @@ import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import okhttp3.Route +import okhttp3.internal.USER_AGENT import okhttp3.internal.canReuseConnectionFor import okhttp3.internal.closeQuietly import okhttp3.internal.connection.RoutePlanner.Plan import okhttp3.internal.http.RealInterceptorChain import okhttp3.internal.platform.Platform import okhttp3.internal.toHostHeader -import okhttp3.internal.userAgent class RealRoutePlanner( private val client: OkHttpClient, @@ -249,7 +249,7 @@ class RealRoutePlanner( .method("CONNECT", null) .header("Host", route.address.url.toHostHeader(includeDefaultPort = true)) .header("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid. - .header("User-Agent", userAgent) + .header("User-Agent", USER_AGENT) .build() val fakeAuthChallengeResponse = Response.Builder() @@ -303,10 +303,16 @@ class RealRoutePlanner( */ private fun retryRoute(connection: RealConnection): Route? { return synchronized(connection) { - if (connection.routeFailureCount != 0) null - else if (!connection.noNewExchanges) null // This route is still in use. - else if (!connection.route().address.url.canReuseConnectionFor(address.url)) null - else connection.route() + when { + connection.routeFailureCount != 0 -> null + + // This route is still in use. + !connection.noNewExchanges -> null + + !connection.route().address.url.canReuseConnectionFor(address.url) -> null + + else -> connection.route() + } } } diff --git a/okhttp/src/main/kotlin/okhttp3/internal/connection/tlsHandshake.kt b/okhttp/src/main/kotlin/okhttp3/internal/connection/RetryTlsHandshake.kt similarity index 100% rename from okhttp/src/main/kotlin/okhttp3/internal/connection/tlsHandshake.kt rename to okhttp/src/main/kotlin/okhttp3/internal/connection/RetryTlsHandshake.kt diff --git a/okhttp/src/main/kotlin/okhttp3/internal/graal/svm.kt b/okhttp/src/main/kotlin/okhttp3/internal/graal/GraalSvm.kt similarity index 100% rename from okhttp/src/main/kotlin/okhttp3/internal/graal/svm.kt rename to okhttp/src/main/kotlin/okhttp3/internal/graal/GraalSvm.kt diff --git a/okhttp/src/main/kotlin/okhttp3/internal/http/BridgeInterceptor.kt b/okhttp/src/main/kotlin/okhttp3/internal/http/BridgeInterceptor.kt index 08a175545cab..53bfee9743d3 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/http/BridgeInterceptor.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/http/BridgeInterceptor.kt @@ -22,7 +22,7 @@ import okhttp3.CookieJar import okhttp3.Interceptor import okhttp3.Response import okhttp3.internal.toHostHeader -import okhttp3.internal.userAgent +import okhttp3.internal.USER_AGENT import okio.GzipSource import okio.buffer @@ -77,7 +77,7 @@ class BridgeInterceptor(private val cookieJar: CookieJar) : Interceptor { } if (userRequest.header("User-Agent") == null) { - requestBuilder.header("User-Agent", userAgent) + requestBuilder.header("User-Agent", USER_AGENT) } val networkRequest = requestBuilder.build() diff --git a/okhttp/src/main/kotlin/okhttp3/internal/http/dates.kt b/okhttp/src/main/kotlin/okhttp3/internal/http/DateFormatting.kt similarity index 80% rename from okhttp/src/main/kotlin/okhttp3/internal/http/dates.kt rename to okhttp/src/main/kotlin/okhttp3/internal/http/DateFormatting.kt index d3bfad1f3ef0..08f96aa77e60 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/http/dates.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/http/DateFormatting.kt @@ -41,25 +41,32 @@ private val STANDARD_DATE_FORMAT = object : ThreadLocal() { /** If we fail to parse a date in a non-standard format, try each of these formats in sequence. */ private val BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS = arrayOf( - // HTTP formats required by RFC2616 but with any timezone. - "EEE, dd MMM yyyy HH:mm:ss zzz", // RFC 822, updated by RFC 1123 with any TZ - "EEEE, dd-MMM-yy HH:mm:ss zzz", // RFC 850, obsoleted by RFC 1036 with any TZ. - "EEE MMM d HH:mm:ss yyyy", // ANSI C's asctime() format - // Alternative formats. - "EEE, dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MMM-yyyy HH-mm-ss z", - "EEE, dd MMM yy HH:mm:ss z", - "EEE dd-MMM-yyyy HH:mm:ss z", - "EEE dd MMM yyyy HH:mm:ss z", - "EEE dd-MMM-yyyy HH-mm-ss z", - "EEE dd-MMM-yy HH:mm:ss z", - "EEE dd MMM yy HH:mm:ss z", - "EEE,dd-MMM-yy HH:mm:ss z", - "EEE,dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MM-yyyy HH:mm:ss z", + // HTTP formats required by RFC2616 but with any timezone: - /* RI bug 6641315 claims a cookie of this format was once served by www.yahoo.com */ - "EEE MMM d yyyy HH:mm:ss z" + // RFC 822, updated by RFC 1123 with any TZ. + "EEE, dd MMM yyyy HH:mm:ss zzz", + + // RFC 850, obsoleted by RFC 1036 with any TZ. + "EEEE, dd-MMM-yy HH:mm:ss zzz", + + // ANSI C's asctime() format + "EEE MMM d HH:mm:ss yyyy", + + // Alternative formats: + "EEE, dd-MMM-yyyy HH:mm:ss z", + "EEE, dd-MMM-yyyy HH-mm-ss z", + "EEE, dd MMM yy HH:mm:ss z", + "EEE dd-MMM-yyyy HH:mm:ss z", + "EEE dd MMM yyyy HH:mm:ss z", + "EEE dd-MMM-yyyy HH-mm-ss z", + "EEE dd-MMM-yy HH:mm:ss z", + "EEE dd MMM yy HH:mm:ss z", + "EEE,dd-MMM-yy HH:mm:ss z", + "EEE,dd-MMM-yyyy HH:mm:ss z", + "EEE, dd-MM-yyyy HH:mm:ss z", + + // RI bug 6641315 claims a cookie of this format was once served by www.yahoo.com: + "EEE MMM d yyyy HH:mm:ss z" ) private val BROWSER_COMPATIBLE_DATE_FORMATS = diff --git a/okhttp/src/main/kotlin/okhttp3/internal/http/HttpStatusCodes.kt b/okhttp/src/main/kotlin/okhttp3/internal/http/HttpStatusCodes.kt index 1ed5982510ea..04baa39b8f64 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/http/HttpStatusCodes.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/http/HttpStatusCodes.kt @@ -26,13 +26,11 @@ package okhttp3.internal.http -/** - * HTTP Status Codes - * - * https://datatracker.ietf.org/doc/html/rfc7231#page-47 - * - * From https://github.com/apache/httpcomponents-core/blob/master/httpcore5/src/main/java/org/apache/hc/core5/http/HttpStatus.java - */ +// HTTP Status Codes +// +// https://datatracker.ietf.org/doc/html/rfc7231#page-47 +// +// From https://github.com/apache/httpcomponents-core/blob/master/httpcore5/src/main/java/org/apache/hc/core5/http/HttpStatus.java // --- 1xx Informational --- // /** `100 1xx Informational` (HTTP/1.1 - RFC 7231) */ diff --git a/okhttp/src/main/kotlin/okhttp3/internal/http2/Hpack.kt b/okhttp/src/main/kotlin/okhttp3/internal/http2/Hpack.kt index 6ec4e3ea53a1..8407c8118821 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/http2/Hpack.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/http2/Hpack.kt @@ -18,7 +18,6 @@ package okhttp3.internal.http2 import java.io.IOException import java.util.Arrays import java.util.Collections -import java.util.LinkedHashMap import okhttp3.internal.and import okhttp3.internal.http2.Header.Companion.RESPONSE_STATUS import okhttp3.internal.http2.Header.Companion.TARGET_AUTHORITY @@ -463,8 +462,11 @@ object Hpack { dynamicTableByteCount += delta } - /** This does not use "never indexed" semantics for sensitive headers. */ - // http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#section-6.2.3 + /** + * This does not use "never indexed" semantics for sensitive headers. + * + * http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#section-6.2.3 + */ @Throws(IOException::class) fun writeHeaders(headerBlock: List
) { if (emitDynamicTableSizeUpdate) { diff --git a/okhttp/src/main/kotlin/okhttp3/internal/http2/Http2.kt b/okhttp/src/main/kotlin/okhttp3/internal/http2/Http2.kt index 42f81d2c3907..e022fa4dd05e 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/http2/Http2.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/http2/Http2.kt @@ -142,7 +142,6 @@ object Http2 { * Looks up valid string representing flags from the table. Invalid combinations are represented * in binary. */ - // Visible for testing. fun formatFlags(type: Int, flags: Int): String { if (flags == 0) return "" when (type) { diff --git a/okhttp/src/main/kotlin/okhttp3/internal/http2/Http2Connection.kt b/okhttp/src/main/kotlin/okhttp3/internal/http2/Http2Connection.kt index d1c9d8b1097d..45d5aad00a7d 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/http2/Http2Connection.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/http2/Http2Connection.kt @@ -394,7 +394,9 @@ class Http2Connection internal constructor(builder: Builder) : Closeable { synchronized(this) { awaitPingsSent++ } - writePing(false, AWAIT_PING, 0x4f4b6f6b /* "OKok" */) + + /* 0x4f 0x4b 0x6f 0x6b is "OKok". */ + writePing(false, AWAIT_PING, 0x4f4b6f6b) } /** For testing: awaits a pong. */ diff --git a/okhttp/src/main/kotlin/okhttp3/internal/idn/Punycode.kt b/okhttp/src/main/kotlin/okhttp3/internal/idn/Punycode.kt index c2d02567d403..1fe36dc378c1 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/idn/Punycode.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/idn/Punycode.kt @@ -34,13 +34,13 @@ object Punycode { val PREFIX_STRING = "xn--" val PREFIX = PREFIX_STRING.encodeUtf8() - private const val base = 36 - private const val tmin = 1 - private const val tmax = 26 - private const val skew = 38 - private const val damp = 700 - private const val initial_bias = 72 - private const val initial_n = 0x80 + private const val BASE = 36 + private const val TMIN = 1 + private const val TMAX = 26 + private const val SKEW = 38 + private const val DAMP = 700 + private const val INITIAL_BIAS = 72 + private const val INITIAL_N = 0x80 /** * Returns null if any label is oversized so much that the encoder cannot encode it without @@ -90,7 +90,7 @@ object Punycode { // Copy all the basic code points to the output. var b = 0 for (codePoint in input) { - if (codePoint < initial_n) { + if (codePoint < INITIAL_N) { result.writeByte(codePoint) b++ } @@ -99,9 +99,9 @@ object Punycode { // Copy a delimiter if any basic code points were emitted. if (b > 0) result.writeByte('-'.code) - var n = initial_n + var n = INITIAL_N var delta = 0 - var bias = initial_bias + var bias = INITIAL_BIAS var h = b while (h < input.size) { val m = input.minBy { if (it >= n) it else Int.MAX_VALUE } @@ -119,15 +119,15 @@ object Punycode { } else if (c == n) { var q = delta - for (k in base until Int.MAX_VALUE step base) { + for (k in BASE until Int.MAX_VALUE step BASE) { val t = when { - k <= bias -> tmin - k >= bias + tmax -> tmax + k <= bias -> TMIN + k >= bias + TMAX -> TMAX else -> k - bias } if (q < t) break - result.writeByte((t + ((q - t) % (base - t))).punycodeDigit) - q = (q - t) / (base - t) + result.writeByte((t + ((q - t) % (BASE - t))).punycodeDigit) + q = (q - t) / (BASE - t) } result.writeByte(q.punycodeDigit) @@ -208,14 +208,14 @@ object Punycode { pos++ // Consume '-'. } - var n = initial_n + var n = INITIAL_N var i = 0 - var bias = initial_bias + var bias = INITIAL_BIAS while (pos < limit) { val oldi = i var w = 1 - for (k in base until Int.MAX_VALUE step base) { + for (k in BASE until Int.MAX_VALUE step BASE) { if (pos == limit) return false // Malformed. val c = string[pos++] val digit = when (c) { @@ -228,12 +228,12 @@ object Punycode { if (i > Int.MAX_VALUE - deltaI) return false // Prevent overflow. i += deltaI val t = when { - k <= bias -> tmin - k >= bias + tmax -> tmax + k <= bias -> TMIN + k >= bias + TMAX -> TMAX else -> k - bias } if (digit < t) break - val scaleW = base - t + val scaleW = BASE - t if (w > Int.MAX_VALUE / scaleW) return false // Prevent overflow. w *= scaleW } @@ -260,21 +260,21 @@ object Punycode { /** Returns a new bias. */ private fun adapt(delta: Int, numpoints: Int, first: Boolean): Int { var delta = when { - first -> delta / damp + first -> delta / DAMP else -> delta / 2 } delta += (delta / numpoints) var k = 0 - while (delta > ((base - tmin) * tmax) / 2) { - delta /= (base - tmin) - k += base + while (delta > ((BASE - TMIN) * TMAX) / 2) { + delta /= (BASE - TMIN) + k += BASE } - return k + (((base - tmin + 1) * delta) / (delta + skew)) + return k + (((BASE - TMIN + 1) * delta) / (delta + SKEW)) } private fun String.requiresEncode(pos: Int, limit: Int): Boolean { for (i in pos until limit) { - if (this[i].code >= initial_n) return true + if (this[i].code >= INITIAL_N) return true } return false } diff --git a/okhttp/src/main/kotlin/okhttp3/internal/internal.kt b/okhttp/src/main/kotlin/okhttp3/internal/internal.kt index 1e212811fc4a..835511e1795c 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/internal.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/internal.kt @@ -16,7 +16,7 @@ /** Exposes Kotlin-internal APIs to Java test code and code in other modules. */ @file:JvmName("Internal") - +@file:Suppress("ktlint:standard:filename") package okhttp3.internal import java.nio.charset.Charset diff --git a/okhttp/src/main/kotlin/okhttp3/internal/ws/MessageDeflater.kt b/okhttp/src/main/kotlin/okhttp3/internal/ws/MessageDeflater.kt index 362fb07e5778..1b324c557602 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/ws/MessageDeflater.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/ws/MessageDeflater.kt @@ -30,7 +30,13 @@ class MessageDeflater( private val noContextTakeover: Boolean ) : Closeable { private val deflatedBytes = Buffer() - private val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true /* omit zlib header */) + + private val deflater = Deflater( + Deflater.DEFAULT_COMPRESSION, + // nowrap (omits zlib header): + true, + ) + private val deflaterSink = DeflaterSink(deflatedBytes, deflater) /** Deflates [buffer] in place as described in RFC 7692 section 7.2.1. */ diff --git a/okhttp/src/main/kotlin/okhttp3/internal/ws/MessageInflater.kt b/okhttp/src/main/kotlin/okhttp3/internal/ws/MessageInflater.kt index f9fcb956fff9..2f51016cf64f 100644 --- a/okhttp/src/main/kotlin/okhttp3/internal/ws/MessageInflater.kt +++ b/okhttp/src/main/kotlin/okhttp3/internal/ws/MessageInflater.kt @@ -27,7 +27,12 @@ class MessageInflater( private val noContextTakeover: Boolean ) : Closeable { private val deflatedBytes = Buffer() - private val inflater = Inflater(true /* omit zlib header */) + + private val inflater = Inflater( + // nowrap (omits zlib header): + true, + ) + private val inflaterSource = InflaterSource(deflatedBytes, inflater) /** Inflates [buffer] in place as described in RFC 7692 section 7.2.2. */ diff --git a/okhttp/src/main/kotlinTemplates/okhttp3/internal/-InternalVersion.kt b/okhttp/src/main/kotlinTemplates/okhttp3/internal/-InternalVersion.kt index b49a166bf066..fac79c90d16c 100644 --- a/okhttp/src/main/kotlinTemplates/okhttp3/internal/-InternalVersion.kt +++ b/okhttp/src/main/kotlinTemplates/okhttp3/internal/-InternalVersion.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3.internal internal const val CONST_VERSION = "$projectVersion" diff --git a/okhttp/src/test/java/okhttp3/AutobahnTester.kt b/okhttp/src/test/java/okhttp3/AutobahnTester.kt index b3565ce074da..cb309de3327d 100644 --- a/okhttp/src/test/java/okhttp3/AutobahnTester.kt +++ b/okhttp/src/test/java/okhttp3/AutobahnTester.kt @@ -19,7 +19,7 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference -import okhttp3.internal.userAgent +import okhttp3.internal.USER_AGENT import okio.ByteString /** @@ -116,7 +116,7 @@ class AutobahnTester { private fun updateReports() { val latch = CountDownLatch(1) - newWebSocket("/updateReports?agent=$userAgent", object : WebSocketListener() { + newWebSocket("/updateReports?agent=$USER_AGENT", object : WebSocketListener() { override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { webSocket.close(1000, null) latch.countDown() diff --git a/okhttp/src/test/java/okhttp3/CacheCorruptionTest.kt b/okhttp/src/test/java/okhttp3/CacheCorruptionTest.kt index 5a1596f1a362..f0bfc54a0cc9 100644 --- a/okhttp/src/test/java/okhttp3/CacheCorruptionTest.kt +++ b/okhttp/src/test/java/okhttp3/CacheCorruptionTest.kt @@ -56,7 +56,7 @@ class CacheCorruptionTest { private val handshakeCertificates = platform.localhostHandshakeCertificates() private lateinit var client: OkHttpClient private lateinit var cache: Cache - private val NULL_HOSTNAME_VERIFIER = HostnameVerifier { _: String?, _: SSLSession? -> true } + private val nullHostnameVerifier = HostnameVerifier { _: String?, _: SSLSession? -> true } private val cookieManager = CookieManager() private lateinit var server: MockWebServer @@ -168,7 +168,7 @@ class CacheCorruptionTest { .sslSocketFactory( handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager ) - .hostnameVerifier(NULL_HOSTNAME_VERIFIER) + .hostnameVerifier(nullHostnameVerifier) .build() val request = Request(server.url("/")) val response1: Response = client.newCall(request).execute() @@ -182,7 +182,7 @@ class CacheCorruptionTest { /** * @param delta the offset from the current date to use. Negative values yield dates in the past; - * positive values yield dates in the future. + * positive values yield dates in the future. */ private fun formatDate(delta: Long, timeUnit: TimeUnit): String? { return formatDate(Date(System.currentTimeMillis() + timeUnit.toMillis(delta))) diff --git a/okhttp/src/test/java/okhttp3/CacheTest.kt b/okhttp/src/test/java/okhttp3/CacheTest.kt index b8569a9447dd..fd8d4ce95123 100644 --- a/okhttp/src/test/java/okhttp3/CacheTest.kt +++ b/okhttp/src/test/java/okhttp3/CacheTest.kt @@ -24,7 +24,6 @@ import assertk.assertions.isFalse import assertk.assertions.isNotNull import assertk.assertions.isNull import assertk.assertions.isTrue -import assertk.fail import java.io.IOException import java.net.CookieManager import java.net.HttpURLConnection @@ -319,8 +318,8 @@ class CacheTest { .build() val request = Request.Builder().url(server.url("/")).build() val response1 = client.newCall(request).execute() - val `in` = response1.body.source() - assertThat(`in`.readUtf8()).isEqualTo("ABC") + val source = response1.body.source() + assertThat(source.readUtf8()).isEqualTo("ABC") // OpenJDK 6 fails on this line, complaining that the connection isn't open yet val cipherSuite = response1.handshake!!.cipherSuite @@ -734,11 +733,11 @@ class CacheTest { .build() ) val response1 = get(server.url("/")) - val `in` = response1.body.source() - assertThat(`in`.readUtf8(5)).isEqualTo("ABCDE") - `in`.close() + val source = response1.body.source() + assertThat(source.readUtf8(5)).isEqualTo("ABCDE") + source.close() assertFailsWith { - `in`.readByte() + source.readByte() } assertThat(cache.writeAbortCount()).isEqualTo(1) assertThat(cache.writeSuccessCount()).isEqualTo(0) diff --git a/okhttp/src/test/java/okhttp3/CallTest.kt b/okhttp/src/test/java/okhttp3/CallTest.kt index ca8698e1933b..013cf25524d8 100644 --- a/okhttp/src/test/java/okhttp3/CallTest.kt +++ b/okhttp/src/test/java/okhttp3/CallTest.kt @@ -90,12 +90,12 @@ import okhttp3.TestUtil.assumeNotWindows import okhttp3.TestUtil.awaitGarbageCollection import okhttp3.internal.DoubleInetAddressDns import okhttp3.internal.RecordingOkAuthenticator +import okhttp3.internal.USER_AGENT import okhttp3.internal.addHeaderLenient import okhttp3.internal.closeQuietly import okhttp3.internal.http.HTTP_EARLY_HINTS import okhttp3.internal.http.HTTP_PROCESSING import okhttp3.internal.http.RecordingProxySelector -import okhttp3.internal.userAgent import okhttp3.java.net.cookiejar.JavaNetCookieJar import okhttp3.okio.LoggingFilesystem import okhttp3.testing.Flaky @@ -1222,9 +1222,14 @@ open class CallTest { server.enqueue(MockResponse(body = "response that will never be received")) val response = executeSynchronously("/") response.assertFailure( - SSLException::class.java, // JDK 11 response to the FAIL_HANDSHAKE - SSLProtocolException::class.java, // RI response to the FAIL_HANDSHAKE - SSLHandshakeException::class.java // Android's response to the FAIL_HANDSHAKE + // JDK 11 response to the FAIL_HANDSHAKE: + SSLException::class.java, + + // RI response to the FAIL_HANDSHAKE: + SSLProtocolException::class.java, + + // Android's response to the FAIL_HANDSHAKE: + SSLHandshakeException::class.java ) assertThat(client.connectionSpecs).doesNotContain(ConnectionSpec.COMPATIBLE_TLS) } @@ -1237,12 +1242,17 @@ open class CallTest { server.enqueue(MockResponse(socketPolicy = FailHandshake)) server.enqueue(MockResponse(body = "abc")) client = client.newBuilder() - .hostnameVerifier( - RecordingHostnameVerifier() - ) // Attempt RESTRICTED_TLS then fall back to MODERN_TLS. - .connectionSpecs(listOf(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) + .hostnameVerifier(RecordingHostnameVerifier()) + .connectionSpecs( + // Attempt RESTRICTED_TLS then fall back to MODERN_TLS. + listOf( + ConnectionSpec.RESTRICTED_TLS, + ConnectionSpec.MODERN_TLS, + ) + ) .sslSocketFactory( - suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager + suppressTlsFallbackClientSocketFactory(), + handshakeCertificates.trustManager ) .build() executeSynchronously("/").assertBody("abc") @@ -2844,7 +2854,7 @@ open class CallTest { server.enqueue(MockResponse()) executeSynchronously("/") val recordedRequest = server.takeRequest() - assertThat(recordedRequest.headers["User-Agent"]!!).isEqualTo(userAgent) + assertThat(recordedRequest.headers["User-Agent"]!!).isEqualTo(USER_AGENT) } @Test @@ -3205,7 +3215,7 @@ open class CallTest { ) val connect = server.takeRequest() assertThat(connect.headers["Private"]).isNull() - assertThat(connect.headers["User-Agent"]).isEqualTo(userAgent) + assertThat(connect.headers["User-Agent"]).isEqualTo(USER_AGENT) assertThat(connect.headers["Proxy-Connection"]).isEqualTo("Keep-Alive") assertThat(connect.headers["Host"]).isEqualTo("android.com:443") val get = server.takeRequest() diff --git a/okhttp/src/test/java/okhttp3/ConnectionCoalescingTest.kt b/okhttp/src/test/java/okhttp3/ConnectionCoalescingTest.kt index 1ccaf03a02e8..6d4d2b59cbf5 100644 --- a/okhttp/src/test/java/okhttp3/ConnectionCoalescingTest.kt +++ b/okhttp/src/test/java/okhttp3/ConnectionCoalescingTest.kt @@ -17,6 +17,7 @@ package okhttp3 import assertk.assertThat import assertk.assertions.isEqualTo +import assertk.fail import java.io.IOException import java.net.InetAddress import java.net.InetSocketAddress @@ -30,14 +31,13 @@ import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLSession import javax.net.ssl.X509TrustManager +import kotlin.test.assertFailsWith import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import okhttp3.CertificatePinner.Companion.pin import okhttp3.testing.PlatformRule import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HeldCertificate -import assertk.fail -import kotlin.test.assertFailsWith import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @@ -492,7 +492,7 @@ class ConnectionCoalescingTest { */ @Test fun redirectWithDevSetup() { - val TRUST_MANAGER: X509TrustManager = object : X509TrustManager { + val trustManager: X509TrustManager = object : X509TrustManager { override fun checkClientTrusted(x509Certificates: Array, s: String) { } @@ -503,8 +503,9 @@ class ConnectionCoalescingTest { return arrayOf() } } - client = - client.newBuilder().sslSocketFactory(client.sslSocketFactory, TRUST_MANAGER).build() + client = client.newBuilder() + .sslSocketFactory(client.sslSocketFactory, trustManager) + .build() server.enqueue(MockResponse()) server.enqueue(MockResponse()) assert200Http2Response(execute(url), server.hostName) diff --git a/okhttp/src/test/java/okhttp3/MediaTypeJvmTest.kt b/okhttp/src/test/java/okhttp3/MediaTypeJvmTest.kt index d2e87b88c521..ee2b5b93c540 100644 --- a/okhttp/src/test/java/okhttp3/MediaTypeJvmTest.kt +++ b/okhttp/src/test/java/okhttp3/MediaTypeJvmTest.kt @@ -15,7 +15,7 @@ */ package okhttp3 -import java.util.* +import java.util.Locale import kotlin.test.assertEquals import kotlin.test.assertNull import okhttp3.MediaType.Companion.toMediaType diff --git a/okhttp/src/test/java/okhttp3/URLConnectionTest.kt b/okhttp/src/test/java/okhttp3/URLConnectionTest.kt index 1f74424239b8..4715444a9840 100644 --- a/okhttp/src/test/java/okhttp3/URLConnectionTest.kt +++ b/okhttp/src/test/java/okhttp3/URLConnectionTest.kt @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:Suppress("ktlint:standard:filename") package okhttp3 import assertk.assertThat @@ -88,7 +89,7 @@ import okhttp3.internal.authenticator.JavaNetAuthenticator import okhttp3.internal.http.HTTP_PERM_REDIRECT import okhttp3.internal.http.HTTP_TEMP_REDIRECT import okhttp3.internal.platform.Platform.Companion.get -import okhttp3.internal.userAgent +import okhttp3.internal.USER_AGENT import okhttp3.java.net.cookiejar.JavaNetCookieJar import okhttp3.testing.Flaky import okhttp3.testing.PlatformRule @@ -988,7 +989,7 @@ class URLConnectionTest { val connect = server.takeRequest() assertThat(connect.headers["Private"]).isNull() assertThat(connect.headers["Proxy-Authorization"]).isNull() - assertThat(connect.headers["User-Agent"]).isEqualTo(userAgent) + assertThat(connect.headers["User-Agent"]).isEqualTo(USER_AGENT) assertThat(connect.headers["Host"]).isEqualTo("android.com:443") assertThat(connect.headers["Proxy-Connection"]).isEqualTo("Keep-Alive") val get = server.takeRequest() @@ -2761,18 +2762,18 @@ class URLConnectionTest { val server = MockWebServer() // Sockets on some platforms can have large buffers that mean writes do not block when // required. These socket factories explicitly set the buffer sizes on sockets created. - val SOCKET_BUFFER_SIZE = 4 * 1024 + val socketBufferSize = 4 * 1024 server.serverSocketFactory = object : DelegatingServerSocketFactory(getDefault()) { override fun configureServerSocket(serverSocket: ServerSocket): ServerSocket { - serverSocket.receiveBufferSize = SOCKET_BUFFER_SIZE + serverSocket.receiveBufferSize = socketBufferSize return serverSocket } } client = client.newBuilder() .socketFactory(object : DelegatingSocketFactory(getDefault()) { override fun configureSocket(socket: Socket): Socket { - socket.receiveBufferSize = SOCKET_BUFFER_SIZE - socket.sendBufferSize = SOCKET_BUFFER_SIZE + socket.receiveBufferSize = socketBufferSize + socket.sendBufferSize = socketBufferSize return socket } }) @@ -3026,11 +3027,11 @@ class URLConnectionTest { .build() ) val response = getResponse(newRequest("/")) - val `in` = response.body.byteStream() - assertThat(readAscii(`in`, 3)).isEqualTo("ABC") - assertThat(`in`.read()).isEqualTo(-1) + val inputStream = response.body.byteStream() + assertThat(readAscii(inputStream, 3)).isEqualTo("ABC") + assertThat(inputStream.read()).isEqualTo(-1) // throws IOException in Gingerbread. - assertThat(`in`.read()).isEqualTo(-1) + assertThat(inputStream.read()).isEqualTo(-1) } @Test @@ -3796,7 +3797,7 @@ class URLConnectionTest { ) assertContent("abc", getResponse(newRequest("/"))) val request = server.takeRequest() - assertThat(request.headers["User-Agent"]).isEqualTo(userAgent) + assertThat(request.headers["User-Agent"]).isEqualTo(USER_AGENT) } @Test diff --git a/okhttp/src/test/java/okhttp3/WebPlatformToAsciiTest.kt b/okhttp/src/test/java/okhttp3/WebPlatformToAsciiTest.kt index 8ab6b20ecb6c..74cd2740d06d 100644 --- a/okhttp/src/test/java/okhttp3/WebPlatformToAsciiTest.kt +++ b/okhttp/src/test/java/okhttp3/WebPlatformToAsciiTest.kt @@ -22,6 +22,7 @@ import okhttp3.HttpUrl.Companion.toHttpUrlOrNull /** Runs the web platform ToAscii tests. */ class WebPlatformToAsciiTest { + @Suppress("ktlint:standard:max-line-length") val knownFailures = setOf( // OkHttp rejects empty labels. "x..xn--zca", diff --git a/okhttp/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.kt b/okhttp/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.kt index 63fcc37a3744..2ee326caf488 100644 --- a/okhttp/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.kt @@ -502,13 +502,14 @@ class DiskLruCacheTest { writeFile(getCleanFile("k1", 1), "B") filesystem.write(journalFile) { writeUtf8( + // No trailing newline. """ - |${DiskLruCache.MAGIC} - |${DiskLruCache.VERSION_1} - |100 - |2 - | - |CLEAN k1 1 1""".trimMargin() // no trailing newline + |${DiskLruCache.MAGIC} + |${DiskLruCache.VERSION_1} + |100 + |2 + | + |CLEAN k1 1 1""".trimMargin() ) } createNewCache() diff --git a/okhttp/src/test/java/okhttp3/internal/connection/InetAddressOrderTest.kt b/okhttp/src/test/java/okhttp3/internal/connection/InetAddressOrderTest.kt index 98b52fa47578..85590a976177 100644 --- a/okhttp/src/test/java/okhttp3/internal/connection/InetAddressOrderTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/connection/InetAddressOrderTest.kt @@ -22,6 +22,7 @@ import java.net.Inet4Address import java.net.Inet6Address import org.junit.jupiter.api.Test +@Suppress("ktlint:standard:property-naming") class InetAddressOrderTest { val ipv4_10_0_0_6 = Inet4Address.getByName("10.0.0.6") val ipv4_10_0_0_1 = Inet4Address.getByName("10.0.0.1") diff --git a/okhttp/src/test/java/okhttp3/internal/connection/RouteSelectorTest.kt b/okhttp/src/test/java/okhttp3/internal/connection/RouteSelectorTest.kt index 495252d098c2..3f8851bae6b5 100644 --- a/okhttp/src/test/java/okhttp3/internal/connection/RouteSelectorTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/connection/RouteSelectorTest.kt @@ -124,13 +124,13 @@ class RouteSelectorTest { ) val routeSelector = newRouteSelector(address) assertThat(routeSelector.hasNext()).isTrue() - dns[proxyAHost] = dns.allocate(2) + dns[PROXY_A_HOST] = dns.allocate(2) val selection = routeSelector.next() - assertRoute(selection.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort) - assertRoute(selection.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort) + assertRoute(selection.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 0), PROXY_A_PORT) + assertRoute(selection.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 1), PROXY_A_PORT) assertThat(selection.hasNext()).isFalse() assertThat(routeSelector.hasNext()).isFalse() - dns.assertRequests(proxyAHost) + dns.assertRequests(PROXY_A_HOST) proxySelector.assertRequests() // No proxy selector requests! } @@ -221,19 +221,19 @@ class RouteSelectorTest { // First try the IP addresses of the first proxy, in sequence. assertThat(routeSelector.hasNext()).isTrue() - dns[proxyAHost] = dns.allocate(2) + dns[PROXY_A_HOST] = dns.allocate(2) val selection1 = routeSelector.next() - assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort) - assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort) - dns.assertRequests(proxyAHost) + assertRoute(selection1.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 0), PROXY_A_PORT) + assertRoute(selection1.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 1), PROXY_A_PORT) + dns.assertRequests(PROXY_A_HOST) assertThat(selection1.hasNext()).isFalse() // Next try the IP address of the second proxy. assertThat(routeSelector.hasNext()).isTrue() - dns[proxyBHost] = dns.allocate(1) + dns[PROXY_B_HOST] = dns.allocate(1) val selection2 = routeSelector.next() - assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort) - dns.assertRequests(proxyBHost) + assertRoute(selection2.next(), address, proxyB, dns.lookup(PROXY_B_HOST, 0), PROXY_B_PORT) + dns.assertRequests(PROXY_B_HOST) assertThat(selection2.hasNext()).isFalse() // No more proxies to try. @@ -264,22 +264,22 @@ class RouteSelectorTest { val routeSelector = newRouteSelector(address) proxySelector.assertRequests(address.url.toUri()) assertThat(routeSelector.hasNext()).isTrue() - dns[proxyAHost] = dns.allocate(1) + dns[PROXY_A_HOST] = dns.allocate(1) val selection1 = routeSelector.next() - assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort) - dns.assertRequests(proxyAHost) + assertRoute(selection1.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 0), PROXY_A_PORT) + dns.assertRequests(PROXY_A_HOST) assertThat(selection1.hasNext()).isFalse() assertThat(routeSelector.hasNext()).isTrue() - dns.clear(proxyBHost) + dns.clear(PROXY_B_HOST) assertFailsWith { routeSelector.next() } - dns.assertRequests(proxyBHost) + dns.assertRequests(PROXY_B_HOST) assertThat(routeSelector.hasNext()).isTrue() - dns[proxyAHost] = dns.allocate(1) + dns[PROXY_A_HOST] = dns.allocate(1) val selection2 = routeSelector.next() - assertRoute(selection2.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort) - dns.assertRequests(proxyAHost) + assertRoute(selection2.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 0), PROXY_A_PORT) + dns.assertRequests(PROXY_A_HOST) assertThat(selection2.hasNext()).isFalse() assertThat(routeSelector.hasNext()).isFalse() } @@ -291,19 +291,19 @@ class RouteSelectorTest { val routeSelector = newRouteSelector(address) // Proxy A - dns[proxyAHost] = dns.allocate(2) + dns[PROXY_A_HOST] = dns.allocate(2) val selection1 = routeSelector.next() - assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort) - dns.assertRequests(proxyAHost) - assertRoute(selection1.next(), address, proxyA, dns.lookup(proxyAHost, 1), proxyAPort) + assertRoute(selection1.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 0), PROXY_A_PORT) + dns.assertRequests(PROXY_A_HOST) + assertRoute(selection1.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 1), PROXY_A_PORT) assertThat(selection1.hasNext()).isFalse() // Proxy B - dns[proxyBHost] = dns.allocate(2) + dns[PROXY_B_HOST] = dns.allocate(2) val selection2 = routeSelector.next() - assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort) - dns.assertRequests(proxyBHost) - assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 1), proxyBPort) + assertRoute(selection2.next(), address, proxyB, dns.lookup(PROXY_B_HOST, 0), PROXY_B_PORT) + dns.assertRequests(PROXY_B_HOST) + assertRoute(selection2.next(), address, proxyB, dns.lookup(PROXY_B_HOST, 1), PROXY_B_PORT) assertThat(selection2.hasNext()).isFalse() // No more proxies to attempt. @@ -344,27 +344,27 @@ class RouteSelectorTest { proxySelector.proxies.add(proxyA) proxySelector.proxies.add(proxyB) var routeSelector = newRouteSelector(address) - dns[proxyAHost] = dns.allocate(1) - dns[proxyBHost] = dns.allocate(1) + dns[PROXY_A_HOST] = dns.allocate(1) + dns[PROXY_B_HOST] = dns.allocate(1) // Mark the ProxyA route as failed. val selection = routeSelector.next() - dns.assertRequests(proxyAHost) + dns.assertRequests(PROXY_A_HOST) val route = selection.next() - assertRoute(route, address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort) + assertRoute(route, address, proxyA, dns.lookup(PROXY_A_HOST, 0), PROXY_A_PORT) routeDatabase.failed(route) routeSelector = newRouteSelector(address) // Confirm we enumerate both proxies, giving preference to the route from ProxyB. val selection2 = routeSelector.next() - dns.assertRequests(proxyAHost, proxyBHost) - assertRoute(selection2.next(), address, proxyB, dns.lookup(proxyBHost, 0), proxyBPort) + dns.assertRequests(PROXY_A_HOST, PROXY_B_HOST) + assertRoute(selection2.next(), address, proxyB, dns.lookup(PROXY_B_HOST, 0), PROXY_B_PORT) assertThat(selection2.hasNext()).isFalse() // Confirm the last selection contains the postponed route from ProxyA. val selection3 = routeSelector.next() dns.assertRequests() - assertRoute(selection3.next(), address, proxyA, dns.lookup(proxyAHost, 0), proxyAPort) + assertRoute(selection3.next(), address, proxyA, dns.lookup(PROXY_A_HOST, 0), PROXY_A_PORT) assertThat(selection3.hasNext()).isFalse() assertThat(routeSelector.hasNext()).isFalse() } @@ -544,18 +544,18 @@ class RouteSelectorTest { } companion object { - private const val proxyAPort = 1001 - private const val proxyAHost = "proxya" + private const val PROXY_A_PORT = 1001 + private const val PROXY_A_HOST = "proxya" private val proxyA = Proxy( Proxy.Type.HTTP, - InetSocketAddress.createUnresolved(proxyAHost, proxyAPort) + InetSocketAddress.createUnresolved(PROXY_A_HOST, PROXY_A_PORT) ) - private const val proxyBPort = 1002 - private const val proxyBHost = "proxyb" + private const val PROXY_B_PORT = 1002 + private const val PROXY_B_HOST = "proxyb" private val proxyB = Proxy( Proxy.Type.HTTP, - InetSocketAddress.createUnresolved(proxyBHost, proxyBPort) + InetSocketAddress.createUnresolved(PROXY_B_HOST, PROXY_B_PORT) ) } } diff --git a/okhttp/src/test/java/okhttp3/internal/http2/HpackTest.kt b/okhttp/src/test/java/okhttp3/internal/http2/HpackTest.kt index 0d031b350e63..a0d3472c2845 100644 --- a/okhttp/src/test/java/okhttp3/internal/http2/HpackTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/http2/HpackTest.kt @@ -847,13 +847,15 @@ class HpackTest { hpackWriter!!.resizeHeaderTable(2048) hpackWriter!!.writeHeaders(listOf(Header("foo", "bar"))) assertBytes( - 0x3F, 0xE1, 0xF, // Dynamic table size update (size = 2048). + // Dynamic table size update (size = 2048). + 0x3F, 0xE1, 0xF, 0x40, 3, 'f'.code, 'o'.code, 'o'.code, 3, 'b'.code, 'a'.code, 'r'.code ) hpackWriter!!.resizeHeaderTable(8192) hpackWriter!!.writeHeaders(listOf(Header("bar", "foo"))) assertBytes( - 0x3F, 0xE1, 0x3F, // Dynamic table size update (size = 8192). + // Dynamic table size update (size = 8192). + 0x3F, 0xE1, 0x3F, 0x40, 3, 'b'.code, 'a'.code, 'r'.code, 3, 'f'.code, 'o'.code, 'o'.code ) @@ -876,7 +878,8 @@ class HpackTest { hpackWriter!!.resizeHeaderTable(16384) hpackWriter!!.writeHeaders(listOf(Header("foo", "bar"))) assertBytes( - 0x3F, 0xE1, 0x7F, // Dynamic table size update (size = 16384). + // Dynamic table size update (size = 16384). + 0x3F, 0xE1, 0x7F, 0x40, 3, 'f'.code, 'o'.code, 'o'.code, 3, 'b'.code, 'a'.code, 'r'.code ) } @@ -887,7 +890,8 @@ class HpackTest { hpackWriter!!.resizeHeaderTable(0) hpackWriter!!.writeHeaders(listOf(Header("foo", "bar"))) assertBytes( - 0x20, // Dynamic size update (size = 0). + // Dynamic size update (size = 0). + 0x20, 0x40, 3, 'f'.code, 'o'.code, 'o'.code, 3, 'b'.code, 'a'.code, 'r'.code ) } @@ -901,8 +905,10 @@ class HpackTest { hpackWriter!!.resizeHeaderTable(2048) hpackWriter!!.writeHeaders(listOf(Header("foo", "bar"))) assertBytes( - 0x20, // Dynamic size update (size = 0). - 0x3F, 0xE1, 0xF, // Dynamic size update (size = 2048). + // Dynamic size update (size = 0). + 0x20, + // Dynamic size update (size = 2048). + 0x3F, 0xE1, 0xF, 0x40, 3, 'f'.code, 'o'.code, 'o'.code, 3, 'b'.code, 'a'.code, 'r'.code ) } diff --git a/okhttp/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.kt b/okhttp/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.kt index 4a68c71050a7..e458cc02aa32 100644 --- a/okhttp/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.kt @@ -30,6 +30,7 @@ import java.io.InterruptedIOException import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger +import kotlin.test.assertFailsWith import okhttp3.Headers.Companion.headersOf import okhttp3.TestUtil.headerEntries import okhttp3.TestUtil.repeat @@ -46,8 +47,6 @@ import okio.Source import okio.buffer import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertArrayEquals -import assertk.fail -import kotlin.test.assertFailsWith import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout @@ -490,7 +489,7 @@ class Http2ConnectionTest { .socket(socket) .pushObserver(IGNORE) .build() - connection.start( /* sendConnectionPreface = */false) + connection.start(sendConnectionPreface = false) socket.shutdownOutput() assertFailsWith { connection.newStream(headerEntries("a", longString), false) @@ -1875,7 +1874,7 @@ class Http2ConnectionTest { val connection = Http2Connection.Builder(true, TaskRunner.INSTANCE) .socket(peer.openSocket()) .build() - connection.start( /* sendConnectionPreface = */false) + connection.start(sendConnectionPreface = false) val stream = connection.newStream(headerEntries("b", "banana"), false) assertFailsWith { stream.takeHeaders() diff --git a/okhttp/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.kt b/okhttp/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.kt index c5395fd9ad93..3390ed743ca5 100644 --- a/okhttp/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.kt +++ b/okhttp/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.kt @@ -1035,7 +1035,8 @@ class HttpOverHttp2Test { fun recoverFromCancelReusesConnection(protocol: Protocol, mockWebServer: MockWebServer) { setUp(protocol, mockWebServer) val responseDequeuedLatches = listOf( - CountDownLatch(1), // No synchronization for the last request, which is not canceled. + // No synchronization for the last request, which is not canceled: + CountDownLatch(1), CountDownLatch(0) ) val requestCanceledLatches = listOf( @@ -1070,7 +1071,8 @@ class HttpOverHttp2Test { setUp(protocol, mockWebServer) val responseDequeuedLatches = Arrays.asList( CountDownLatch(1), - CountDownLatch(1), // No synchronization for the last request, which is not canceled. + // No synchronization for the last request, which is not canceled: + CountDownLatch(1), CountDownLatch(0) ) val requestCanceledLatches = Arrays.asList( diff --git a/okhttp/src/test/java/okhttp3/internal/idn/stringprep.kt b/okhttp/src/test/java/okhttp3/internal/idn/IdnStringprep.kt similarity index 100% rename from okhttp/src/test/java/okhttp3/internal/idn/stringprep.kt rename to okhttp/src/test/java/okhttp3/internal/idn/IdnStringprep.kt diff --git a/okhttp/src/test/java/okhttp3/internal/idn/stringprepTablesReader.kt b/okhttp/src/test/java/okhttp3/internal/idn/StringprepReader.kt similarity index 97% rename from okhttp/src/test/java/okhttp3/internal/idn/stringprepTablesReader.kt rename to okhttp/src/test/java/okhttp3/internal/idn/StringprepReader.kt index 17a092c3b1a2..e76957bdb1d8 100644 --- a/okhttp/src/test/java/okhttp3/internal/idn/stringprepTablesReader.kt +++ b/okhttp/src/test/java/okhttp3/internal/idn/StringprepReader.kt @@ -103,13 +103,19 @@ class StringprepTablesReader( } private val optionsSemicolon = Options.of( - ";".encodeUtf8(), // 0 is ';'. + // 0 is ';'. + ";".encodeUtf8(), ) private val optionsSemicolonOrNewlineOrDash = Options.of( - ";".encodeUtf8(), // 0 is ';'. - "\n".encodeUtf8(), // 1 is '\n'. - "-".encodeUtf8(), // 2 is '-'. + // 0 is ';'. + ";".encodeUtf8(), + + // 1 is '\n'. + "\n".encodeUtf8(), + + // 2 is '-'. + "-".encodeUtf8(), ) internal fun BufferedSource.readCodePointSet(): RangeListCodePointSet { diff --git a/okhttp/src/test/java/okhttp3/internal/idn/StringprepTablesReaderTest.kt b/okhttp/src/test/java/okhttp3/internal/idn/StringprepTablesReaderTest.kt index 58389758f3d9..25f8c77f1f4d 100644 --- a/okhttp/src/test/java/okhttp3/internal/idn/StringprepTablesReaderTest.kt +++ b/okhttp/src/test/java/okhttp3/internal/idn/StringprepTablesReaderTest.kt @@ -49,9 +49,14 @@ class StringprepTablesReaderTest { assertEquals( listOf( 0x0221..0x0221, + 0x0234..0x024f, - 0x0000..0x001f, // [CONTROL CHARACTERS] - 0x007f..0x007f, // DELETE + + // [CONTROL CHARACTERS]. + 0x0000..0x001f, + + // DELETE. + 0x007f..0x007f, ), rangeList.ranges ) @@ -70,9 +75,14 @@ class StringprepTablesReaderTest { val mappings = buffer.readCodePointMappings() assertEquals( mapOf( - 0x180c to "", // Map to nothing - 'A'.code to "a", // Case map - 'ΐ'.code to "\u03B9\u0308\u0301" // Case map + // Map to nothing. + 0x180c to "", + + // Case map. + 'A'.code to "a", + + // Case map. + 'ΐ'.code to "\u03B9\u0308\u0301" ), mappings.mappings ) diff --git a/samples/guide/src/main/java/okhttp3/recipes/kt/CacheResponse.kt b/samples/guide/src/main/java/okhttp3/recipes/kt/CacheResponse.kt index f402f39d9adc..21f2353970fe 100644 --- a/samples/guide/src/main/java/okhttp3/recipes/kt/CacheResponse.kt +++ b/samples/guide/src/main/java/okhttp3/recipes/kt/CacheResponse.kt @@ -25,7 +25,8 @@ class CacheResponse(cacheDirectory: File) { private val client: OkHttpClient = OkHttpClient.Builder() .cache(Cache( directory = cacheDirectory, - maxSize = 10L * 1024L * 1024L // 1 MiB + // 1 MiB. + maxSize = 10L * 1024L * 1024L )) .build() diff --git a/samples/tlssurvey/src/main/kotlin/okhttp3/survey/RunSurvey.kt b/samples/tlssurvey/src/main/kotlin/okhttp3/survey/RunSurvey.kt index bf4361dae0e5..8e01caecb7fe 100644 --- a/samples/tlssurvey/src/main/kotlin/okhttp3/survey/RunSurvey.kt +++ b/samples/tlssurvey/src/main/kotlin/okhttp3/survey/RunSurvey.kt @@ -25,6 +25,7 @@ import okio.FileSystem import okio.Path.Companion.toPath import org.conscrypt.Conscrypt +@Suppress("ktlint:standard:property-naming") suspend fun main() { val includeConscrypt = false From 7ae395c95515bbe0027e4513f5c82924c8fa72d2 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Sat, 6 Jan 2024 22:52:58 -0500 Subject: [PATCH 2/2] Don't actually enable Spotless yet --- .editorconfig | 1 - build.gradle.kts | 16 +++------------- gradle/libs.versions.toml | 4 +--- 3 files changed, 4 insertions(+), 17 deletions(-) diff --git a/.editorconfig b/.editorconfig index a17e1dd735b8..6531d6787d2f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,7 +2,6 @@ root = true [*] indent_size = 2 -ij_continuation_indent_size = 2 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true diff --git a/build.gradle.kts b/build.gradle.kts index f88ad212ab0e..781eea7553d9 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,14 +1,14 @@ @file:Suppress("UnstableApiUsage") -import com.diffplug.gradle.spotless.SpotlessExtension import com.vanniktech.maven.publish.MavenPublishBaseExtension import com.vanniktech.maven.publish.SonatypeHost -import java.net.URI +import java.net.URL import kotlinx.validation.ApiValidationExtension import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.jetbrains.dokka.gradle.DokkaTaskPartial import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import ru.vyarus.gradle.plugin.animalsniffer.AnimalSnifferExtension +import java.net.URI buildscript { dependencies { @@ -22,6 +22,7 @@ buildscript { classpath(libs.gradlePlugin.shadow) classpath(libs.gradlePlugin.animalsniffer) classpath(libs.gradlePlugin.errorprone) + classpath(libs.gradlePlugin.spotless) classpath(libs.gradlePlugin.mavenPublish) classpath(libs.gradlePlugin.binaryCompatibilityValidator) } @@ -33,19 +34,8 @@ buildscript { } } -plugins { - alias(libs.plugins.spotless) -} - apply(plugin = "org.jetbrains.dokka") -configure { - kotlin { - target("**/*.kt") - ktlint() - } -} - allprojects { group = "com.squareup.okhttp3" version = "5.0.0-SNAPSHOT" diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5a2fd786fc3f..0f9b271d5552 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -45,6 +45,7 @@ gradlePlugin-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", ve gradlePlugin-kotlinSerialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "org-jetbrains-kotlin" } gradlePlugin-mavenPublish = "com.vanniktech:gradle-maven-publish-plugin:0.26.0" gradlePlugin-shadow = "gradle.plugin.com.github.johnrengelman:shadow:8.0.0" +gradlePlugin-spotless = "com.diffplug.spotless:spotless-plugin-gradle:6.23.3" guava-jre = "com.google.guava:guava:32.1.3-jre" hamcrestLibrary = "org.hamcrest:hamcrest-library:2.2" httpClient5 = "org.apache.httpcomponents.client5:httpclient5:5.2.3" @@ -87,6 +88,3 @@ squareup-okhttp-icu = "com.squareup.okhttpicu:okhttp-icu:0.2.0" squareup-kotlinPoet = "com.squareup:kotlinpoet:1.15.3" squareup-okio = { module = "com.squareup.okio:okio", version.ref = "com-squareup-okio" } squareup-okio-fakefilesystem = { module = "com.squareup.okio:okio-fakefilesystem", version.ref = "com-squareup-okio" } - -[plugins] -spotless = { id = "com.diffplug.spotless", version = "6.23.3" }