From 68105a48324a3c39566fe43dc9cbe7b74d600513 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Quenaudon?= Date: Mon, 18 Dec 2023 10:49:23 -0500 Subject: [PATCH] Removing all JS variants (#8145) --- .github/workflows/build.yml | 37 +- buildSrc/src/main/kotlin/deps.kt | 19 - gradle/libs.versions.toml | 1 - okcurl/build.gradle.kts | 1 - okhttp-coroutines/build.gradle.kts | 48 -- okhttp-testing-support/build.gradle.kts | 10 - .../src/jsMain/kotlin/okhttp3/TestUtilJs.kt | 25 - okhttp/build.gradle.kts | 46 -- .../kotlin/okhttp3/internal/-JsAsync.kt | 49 -- .../jsTest/kotlin/okhttp3/HeadersJsTest.kt | 30 -- .../jsTest/kotlin/okhttp3/MediaTypeJsTest.kt | 45 -- .../jsTest/kotlin/okhttp3/SuspendCallTest.kt | 71 --- okhttp/src/jsTest/kotlin/okhttp3/TestCall.kt | 59 --- .../jsTest/kotlin/okhttp3/TestCallFactory.kt | 26 - .../okhttp3/UrlComponentEncodingTesterJs.kt | 22 - .../kotlin/okhttp3/-NonJvmPlatform.kt | 22 - .../nonJvmMain/kotlin/okhttp3/CacheControl.kt | 86 ---- okhttp/src/nonJvmMain/kotlin/okhttp3/Call.kt | 64 --- .../nonJvmMain/kotlin/okhttp3/Challenge.kt | 48 -- .../src/nonJvmMain/kotlin/okhttp3/Headers.kt | 111 ---- .../src/nonJvmMain/kotlin/okhttp3/HttpUrl.kt | 479 ------------------ .../nonJvmMain/kotlin/okhttp3/MediaType.kt | 47 -- .../src/nonJvmMain/kotlin/okhttp3/Request.kt | 154 ------ .../nonJvmMain/kotlin/okhttp3/RequestBody.kt | 60 --- .../src/nonJvmMain/kotlin/okhttp3/Response.kt | 242 --------- .../nonJvmMain/kotlin/okhttp3/ResponseBody.kt | 66 --- .../nonJvmMain/kotlin/okhttp3/TlsVersion.kt | 24 - .../kotlin/okhttp3/internal/-HttpUrlNonJvm.kt | 148 ------ .../okhttp3/internal/-NormalizeNonJvm.kt | 21 - .../kotlin/okhttp3/ResponseBodyNonJvmTest.kt | 38 -- .../kotlin/okhttp3/ResponseNonJvmTest.kt | 61 --- 31 files changed, 1 insertion(+), 2159 deletions(-) delete mode 100644 buildSrc/src/main/kotlin/deps.kt delete mode 100644 okhttp-testing-support/src/jsMain/kotlin/okhttp3/TestUtilJs.kt delete mode 100644 okhttp/src/jsMain/kotlin/okhttp3/internal/-JsAsync.kt delete mode 100644 okhttp/src/jsTest/kotlin/okhttp3/HeadersJsTest.kt delete mode 100644 okhttp/src/jsTest/kotlin/okhttp3/MediaTypeJsTest.kt delete mode 100644 okhttp/src/jsTest/kotlin/okhttp3/SuspendCallTest.kt delete mode 100644 okhttp/src/jsTest/kotlin/okhttp3/TestCall.kt delete mode 100644 okhttp/src/jsTest/kotlin/okhttp3/TestCallFactory.kt delete mode 100644 okhttp/src/jsTest/kotlin/okhttp3/UrlComponentEncodingTesterJs.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/-NonJvmPlatform.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/CacheControl.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/Call.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/Challenge.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/Headers.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/HttpUrl.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/MediaType.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/Request.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/RequestBody.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/Response.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/ResponseBody.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/TlsVersion.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/internal/-HttpUrlNonJvm.kt delete mode 100644 okhttp/src/nonJvmMain/kotlin/okhttp3/internal/-NormalizeNonJvm.kt delete mode 100644 okhttp/src/nonJvmTest/kotlin/okhttp3/ResponseBodyNonJvmTest.kt delete mode 100644 okhttp/src/nonJvmTest/kotlin/okhttp3/ResponseNonJvmTest.kt diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3583e93155db..9ca5e32439dd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -80,7 +80,7 @@ jobs: - name: Run Checks uses: gradle/gradle-build-action@v2 with: - arguments: check -PandroidBuild=true -PgraalBuild=true -x test -x jvmTest -x jsTest + arguments: check -PandroidBuild=true -PgraalBuild=true -x test -x jvmTest testopenjdk11: permissions: @@ -117,41 +117,6 @@ jobs: report_paths: '**/build/test-results/*/TEST-*.xml' check_name: OpenJDK 11 Test Report - testjs: - permissions: - checks: write # for mikepenz/action-junit-report - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Configure JDK - uses: actions/setup-java@v3 - with: - distribution: 'zulu' - java-version: 11 - - - name: Configure JDK - uses: actions/setup-java@v3 - with: - distribution: 'zulu' - java-version: 17 - - - name: Run Checks - uses: gradle/gradle-build-action@v2 - with: - arguments: jsTest - - - name: Publish Test Report - if: success() || failure() - uses: mikepenz/action-junit-report@v4 - with: - report_paths: '**/build/test-results/test/TEST-*.xml' - check_name: JS Test Report - testzulu11: runs-on: ubuntu-latest if: contains(github.event.pull_request.labels.*.name, 'zulu') diff --git a/buildSrc/src/main/kotlin/deps.kt b/buildSrc/src/main/kotlin/deps.kt deleted file mode 100644 index e6ace9d037d8..000000000000 --- a/buildSrc/src/main/kotlin/deps.kt +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2021 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 - * - * https://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. - */ - -// If false - JS targets will not be configured in multiplatform projects. -val kmpJsEnabled = System.getProperty("kjs", "true").toBoolean() - diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ee0adcbd9d65..4319f6abaecc 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -88,4 +88,3 @@ squareup-okhttp-icu = "com.squareup.okhttpicu:okhttp-icu:0.2.0" squareup-kotlinPoet = "com.squareup:kotlinpoet:1.15.2" 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" } -squareup-okio-nodefilesystem = { module = "com.squareup.okio:okio-nodefilesystem", version.ref = "com-squareup-okio" } diff --git a/okcurl/build.gradle.kts b/okcurl/build.gradle.kts index 63c29dcad02e..240cbdb60279 100644 --- a/okcurl/build.gradle.kts +++ b/okcurl/build.gradle.kts @@ -1,4 +1,3 @@ -import com.android.build.gradle.internal.tasks.factory.dependsOn import com.vanniktech.maven.publish.JavadocJar import com.vanniktech.maven.publish.KotlinMultiplatform import org.apache.tools.ant.taskdefs.condition.Os diff --git a/okhttp-coroutines/build.gradle.kts b/okhttp-coroutines/build.gradle.kts index 1f0f41a21c59..29759afc8a44 100644 --- a/okhttp-coroutines/build.gradle.kts +++ b/okhttp-coroutines/build.gradle.kts @@ -12,26 +12,6 @@ kotlin { jvm { withJava() } - if (kmpJsEnabled) { - js { - compilations.all { - kotlinOptions { - moduleKind = "umd" - sourceMap = true - metaInfo = true - } - } - nodejs { - testTask { - useMocha { - timeout = "30s" - } - } - } - browser { - } - } - } sourceSets { commonMain { @@ -48,18 +28,6 @@ kotlin { api(libs.assertk) } } - val nonJvmMain = create("nonJvmMain") { - dependencies { - dependsOn(sourceSets.commonMain.get()) - api(projects.okhttp) - implementation(libs.kotlinx.coroutines.core) - } - } - val nonJvmTest = create("nonJvmTest") { - dependencies { - dependsOn(sourceSets.commonTest.get()) - } - } getByName("jvmMain") { dependencies { @@ -74,22 +42,6 @@ kotlin { implementation(libs.kotlinx.coroutines.test) implementation(projects.mockwebserver3Junit5) } - - getByName("jsMain") { - dependencies { - dependsOn(nonJvmMain) - api(projects.okhttp) - api(libs.squareup.okio) - api(libs.kotlin.stdlib) - } - } - - getByName("jsTest") { - dependencies { - dependsOn(nonJvmTest) - implementation(libs.kotlin.test.js) - } - } } } } diff --git a/okhttp-testing-support/build.gradle.kts b/okhttp-testing-support/build.gradle.kts index fe8915e5ef9c..1af42e66e6f8 100644 --- a/okhttp-testing-support/build.gradle.kts +++ b/okhttp-testing-support/build.gradle.kts @@ -7,11 +7,6 @@ kotlin { jvm { withJava() } - if (kmpJsEnabled) { - js(IR) { - nodejs() - } - } sourceSets { val commonMain by getting { @@ -19,11 +14,6 @@ kotlin { api(libs.squareup.okio) } } - val jsMain by getting { - dependencies { - implementation(libs.squareup.okio.nodefilesystem) - } - } val jvmMain by getting { dependencies { api(projects.okhttp) diff --git a/okhttp-testing-support/src/jsMain/kotlin/okhttp3/TestUtilJs.kt b/okhttp-testing-support/src/jsMain/kotlin/okhttp3/TestUtilJs.kt deleted file mode 100644 index f77acbd229a6..000000000000 --- a/okhttp-testing-support/src/jsMain/kotlin/okhttp3/TestUtilJs.kt +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2023 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 - -import okio.FileSystem -import okio.NodeJsFileSystem - -actual fun getEnv(name: String) = js("globalThis.process.env[name]") as String? - -actual val SYSTEM_FILE_SYSTEM: FileSystem = NodeJsFileSystem - -actual val isJvm = false diff --git a/okhttp/build.gradle.kts b/okhttp/build.gradle.kts index 87e09f9d295a..a387f548d1a9 100644 --- a/okhttp/build.gradle.kts +++ b/okhttp/build.gradle.kts @@ -38,24 +38,6 @@ kotlin { jvm { withJava() } - if (kmpJsEnabled) { - js(IR) { - compilations.all { - kotlinOptions { - moduleKind = "umd" - sourceMap = true - metaInfo = true - } - } - nodejs { - testTask { - useMocha { - timeout = "30s" - } - } - } - } - } sourceSets { commonMain { @@ -75,18 +57,6 @@ kotlin { implementation(libs.kotlinx.serialization.json) } } - val nonJvmMain = create("nonJvmMain") { - dependencies { - dependsOn(sourceSets.commonMain.get()) - implementation(libs.kotlinx.coroutines.core) - implementation(libs.squareup.okhttp.icu) - } - } - val nonJvmTest = create("nonJvmTest") { - dependencies { - dependsOn(sourceSets.commonTest.get()) - } - } getByName("jvmMain") { dependencies { @@ -137,22 +107,6 @@ kotlin { compileOnly(libs.findbugs.jsr305) } } - - getByName("jsMain") { - dependencies { - dependsOn(nonJvmMain) - api(libs.squareup.okio) - api(libs.kotlin.stdlib) - } - } - - getByName("jsTest") { - dependencies { - dependsOn(nonJvmTest) - implementation(libs.kotlin.test.js) - implementation(libs.kotlinx.coroutines.test) - } - } } } diff --git a/okhttp/src/jsMain/kotlin/okhttp3/internal/-JsAsync.kt b/okhttp/src/jsMain/kotlin/okhttp3/internal/-JsAsync.kt deleted file mode 100644 index 91db3fa6ba0c..000000000000 --- a/okhttp/src/jsMain/kotlin/okhttp3/internal/-JsAsync.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2022 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 - -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.suspendCancellableCoroutine -import okhttp3.Call -import okhttp3.Callback -import okhttp3.Response -import okio.IOException -import kotlin.coroutines.resumeWithException - -/** - * An external implementation of Call.executeAsync, useful in - * implementations of Call that implement enqueue and don't - * generally use coroutines in the implementation. - */ -@OptIn(ExperimentalCoroutinesApi::class) -suspend fun Call.jsExecuteAsync(): Response { - return suspendCancellableCoroutine { continuation -> - continuation.invokeOnCancellation { - cancel() - } - enqueue(object : Callback { - override fun onFailure(call: Call, e: IOException) { - continuation.resumeWithException(e) - } - - override fun onResponse(call: Call, response: Response) { - continuation.resume(value = response, onCancellation = { call.cancel() }) - } - }) - } -} diff --git a/okhttp/src/jsTest/kotlin/okhttp3/HeadersJsTest.kt b/okhttp/src/jsTest/kotlin/okhttp3/HeadersJsTest.kt deleted file mode 100644 index 74bea2c9512f..000000000000 --- a/okhttp/src/jsTest/kotlin/okhttp3/HeadersJsTest.kt +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2022 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 - -import assertk.assertThat -import assertk.assertions.isEqualTo -import kotlin.test.Test - -class HeadersJsTest { - @Test - fun names() { - val headers = Headers.headersOf("a", "b", "c", "d") - - assertThat(headers.names()).isEqualTo(setOf("a", "c")) - } -} diff --git a/okhttp/src/jsTest/kotlin/okhttp3/MediaTypeJsTest.kt b/okhttp/src/jsTest/kotlin/okhttp3/MediaTypeJsTest.kt deleted file mode 100644 index 40f44458a62a..000000000000 --- a/okhttp/src/jsTest/kotlin/okhttp3/MediaTypeJsTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2022 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 - -import kotlin.test.Test -import kotlin.test.assertEquals -import okhttp3.MediaType.Companion.toMediaType - -class MediaTypeJsTest { - fun MediaType.charsetName(): String? = parameter("charset") - - @Test - fun testIllegalCharsetName() { - val mediaType = "text/plain; charset=\"!@#$%^&*()\"".toMediaType() - assertEquals("!@#\$%^&*()", mediaType.charsetName()) - } - - @Test fun testUnsupportedCharset() { - val mediaType = "text/plain; charset=us-wtf".toMediaType() - assertEquals("us-wtf", mediaType.charsetName()) - } - - @Test fun testCharsetNameIsDoubleQuotedAndSingleQuoted() { - val mediaType = "text/plain;charset=\"'utf-8'\"".toMediaType() - assertEquals("'utf-8'", mediaType.charsetName()) - } - - @Test fun testCharsetNameIsDoubleQuotedSingleQuote() { - val mediaType = "text/plain;charset=\"'\"".toMediaType() - assertEquals("'", mediaType.charsetName()) - } -} diff --git a/okhttp/src/jsTest/kotlin/okhttp3/SuspendCallTest.kt b/okhttp/src/jsTest/kotlin/okhttp3/SuspendCallTest.kt deleted file mode 100644 index 580cf40ae6a8..000000000000 --- a/okhttp/src/jsTest/kotlin/okhttp3/SuspendCallTest.kt +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2022 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. - * - */ - -@file:OptIn(ExperimentalCoroutinesApi::class) - -package okhttp3 - -import assertk.assertThat -import assertk.assertions.isEqualTo -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runTest -import okhttp3.ResponseBody.Companion.toResponseBody -import okio.use -import kotlin.test.Test - -class SuspendCallTest { - val request = Request.Builder().url("https://example.org/test").build() - - val client = TestCallFactory { call, callback -> - callbackHandler.invoke(call, callback) - } - - lateinit var callbackHandler: (Call, Callback) -> Unit - - @Test - fun suspendCall() = runTest { - val call = client.newCall(request) - - callbackHandler = { _, callback -> - callback.onResponse( - call, - buildResponse(call) { - body("abc".toResponseBody()) - } - ) - } - - val response = call.executeAsync() - response.use { - assertThat(it.body.string()).isEqualTo("abc") - } - - assertThat(response.code).isEqualTo(200) - } - - private fun buildResponse( - call: Call, - fn: Response.Builder.() -> Unit = {} - ) = Response.Builder() - .code(200) - .message("OK") - .body("".toResponseBody()) - .request(call.request()) - .protocol(Protocol.HTTP_2) - .apply(fn) - .build() -} diff --git a/okhttp/src/jsTest/kotlin/okhttp3/TestCall.kt b/okhttp/src/jsTest/kotlin/okhttp3/TestCall.kt deleted file mode 100644 index 714e23848151..000000000000 --- a/okhttp/src/jsTest/kotlin/okhttp3/TestCall.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2022 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 - -import okhttp3.internal.jsExecuteAsync -import okio.IOException - -class TestCall( - private val request: Request, - private val callbackHandler: (Call, Callback) -> Unit -) : Call { - var cancelled = false - var executed = false - - override fun request(): Request = request - - override suspend fun executeAsync(): Response = jsExecuteAsync() - - override fun enqueue(responseCallback: Callback) { - check(!executed) { "Already Executed" } - - if (cancelled) { - responseCallback.onFailure(this, IOException("Canceled")) - } else { - callbackHandler.invoke(this, responseCallback) - } - } - - override fun cancel() { - cancelled = true - } - - override fun isExecuted(): Boolean { - return executed - } - - override fun isCanceled(): Boolean { - return cancelled - } - - override fun clone(): Call { - return TestCall(request, callbackHandler) - } -} diff --git a/okhttp/src/jsTest/kotlin/okhttp3/TestCallFactory.kt b/okhttp/src/jsTest/kotlin/okhttp3/TestCallFactory.kt deleted file mode 100644 index 54fd61e1a4c3..000000000000 --- a/okhttp/src/jsTest/kotlin/okhttp3/TestCallFactory.kt +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2022 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 - -class TestCallFactory( - private val callbackHandler: (Call, Callback) -> Unit -) : Call.Factory { - override fun newCall(request: Request): Call { - return TestCall(request, callbackHandler) - } -} diff --git a/okhttp/src/jsTest/kotlin/okhttp3/UrlComponentEncodingTesterJs.kt b/okhttp/src/jsTest/kotlin/okhttp3/UrlComponentEncodingTesterJs.kt deleted file mode 100644 index 20a5874fe94c..000000000000 --- a/okhttp/src/jsTest/kotlin/okhttp3/UrlComponentEncodingTesterJs.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2023 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 - -import okhttp3.UrlComponentEncodingTester.Component - -actual fun urlComponentEncodingTesterJvmPlatform( - component: Component, -) = UrlComponentEncodingTester.Platform() diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/-NonJvmPlatform.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/-NonJvmPlatform.kt deleted file mode 100644 index 47040116709c..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/-NonJvmPlatform.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2022 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 - -import okio.IOException - -actual class ProtocolException actual constructor(message: String): IOException(message) diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/CacheControl.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/CacheControl.kt deleted file mode 100644 index c269c7e01525..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/CacheControl.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2019 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 - -import kotlin.time.DurationUnit -import okhttp3.internal.commonBuild -import okhttp3.internal.commonForceCache -import okhttp3.internal.commonForceNetwork -import okhttp3.internal.commonImmutable -import okhttp3.internal.commonMaxAge -import okhttp3.internal.commonMaxStale -import okhttp3.internal.commonMinFresh -import okhttp3.internal.commonNoCache -import okhttp3.internal.commonNoStore -import okhttp3.internal.commonNoTransform -import okhttp3.internal.commonOnlyIfCached -import okhttp3.internal.commonParse -import okhttp3.internal.commonToString - -actual class CacheControl internal actual constructor( - actual val noCache: Boolean, - actual val noStore: Boolean, - actual val maxAgeSeconds: Int, - actual val sMaxAgeSeconds: Int, - actual val isPrivate: Boolean, - actual val isPublic: Boolean, - actual val mustRevalidate: Boolean, - actual val maxStaleSeconds: Int, - actual val minFreshSeconds: Int, - actual val onlyIfCached: Boolean, - actual val noTransform: Boolean, - actual val immutable: Boolean, - internal actual var headerValue: String? -) { - actual override fun toString(): String = commonToString() - - actual class Builder { - internal actual var noCache: Boolean = false - internal actual var noStore: Boolean = false - internal actual var maxAgeSeconds = -1 - internal actual var maxStaleSeconds = -1 - internal actual var minFreshSeconds = -1 - internal actual var onlyIfCached: Boolean = false - internal actual var noTransform: Boolean = false - internal actual var immutable: Boolean = false - - actual fun noCache() = commonNoCache() - - actual fun noStore() = commonNoStore() - - actual fun onlyIfCached() = commonOnlyIfCached() - - actual fun noTransform() = commonNoTransform() - - actual fun immutable() = commonImmutable() - - actual fun maxAge(maxAge: Int, timeUnit: DurationUnit) = commonMaxAge(maxAge, timeUnit) - - actual fun maxStale(maxStale: Int, timeUnit: DurationUnit) = commonMaxStale(maxStale, timeUnit) - - actual fun minFresh(minFresh: Int, timeUnit: DurationUnit) = commonMinFresh(minFresh, timeUnit) - - actual fun build(): CacheControl = commonBuild() - } - - actual companion object { - actual val FORCE_NETWORK = commonForceNetwork() - - actual val FORCE_CACHE = commonForceCache() - - actual fun parse(headers: Headers): CacheControl = commonParse(headers) - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/Call.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/Call.kt deleted file mode 100644 index ef166b6db8af..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/Call.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2022 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 - -import okio.IOException - -actual interface Call { - actual fun request(): Request - - /** - * Invokes the request immediately, and blocks until the response can be processed or is in error. - * - * To avoid leaking resources callers should close the [Response] which in turn will close the - * underlying [ResponseBody]. - * - * ```kotlin - * // ensure the response (and underlying response body) is closed - * client.newCall(request).executeAsync().use { - * ... - * } - * ``` - * - * The caller may read the response body with the response's [Response.body] method. To avoid - * leaking resources callers must [close the response body][ResponseBody] or the response. - * - * Note that transport-layer success (receiving a HTTP response code, headers and body) does not - * necessarily indicate application-layer success: `response` may still indicate an unhappy HTTP - * response code like 404 or 500. - * - * @throws IOException if the request could not be executed due to cancellation, a connectivity - * problem or timeout. Because networks can fail during an exchange, it is possible that the - * remote server accepted the request before the failure. - * @throws IllegalStateException when the call has already been executed. - */ - suspend fun executeAsync(): Response - - actual fun enqueue(responseCallback: Callback) - - actual fun cancel() - - actual fun isExecuted(): Boolean - - actual fun isCanceled(): Boolean - - actual fun clone(): Call - - actual fun interface Factory { - actual fun newCall(request: Request): Call - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/Challenge.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/Challenge.kt deleted file mode 100644 index 8b0cda5a57f8..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/Challenge.kt +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2014 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 - -import okhttp3.internal.commonEquals -import okhttp3.internal.commonHashCode -import okhttp3.internal.commonToString - -actual class Challenge actual constructor( - actual val scheme: String, - - authParams: Map -) { - actual val authParams: Map - - actual val realm: String? - get() = authParams["realm"] - - actual constructor(scheme: String, realm: String) : this(scheme, mapOf("realm" to realm)) - - init { - val newAuthParams = mutableMapOf() - for ((key, value) in authParams) { - val newKey = key?.lowercase() - newAuthParams[newKey] = value - } - this.authParams = newAuthParams.toMap() - } - - actual override fun equals(other: Any?): Boolean = commonEquals(other) - - actual override fun hashCode(): Int = commonHashCode() - - actual override fun toString(): String = commonToString() -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/Headers.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/Headers.kt deleted file mode 100644 index d6f989799223..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/Headers.kt +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 - -import okhttp3.internal.commonAdd -import okhttp3.internal.commonAddAll -import okhttp3.internal.commonAddLenient -import okhttp3.internal.commonBuild -import okhttp3.internal.commonEquals -import okhttp3.internal.commonGet -import okhttp3.internal.commonHashCode -import okhttp3.internal.commonHeadersGet -import okhttp3.internal.commonHeadersOf -import okhttp3.internal.commonIterator -import okhttp3.internal.commonName -import okhttp3.internal.commonNewBuilder -import okhttp3.internal.commonRemoveAll -import okhttp3.internal.commonSet -import okhttp3.internal.commonToHeaders -import okhttp3.internal.commonToString -import okhttp3.internal.commonValue -import okhttp3.internal.commonValues - -@Suppress("NAME_SHADOWING") -actual class Headers internal actual constructor( - internal actual val namesAndValues: Array -) : Iterable> { - actual operator fun get(name: String): String? = commonHeadersGet(namesAndValues, name) - - actual val size: Int - get() = namesAndValues.size / 2 - - actual fun name(index: Int): String = commonName(index) - - actual fun value(index: Int): String = commonValue(index) - - actual fun names(): Set { - return (0 until size).map { name(it) }.distinctBy { it.lowercase() }.toSet() - } - - actual fun values(name: String): List = commonValues(name) - - /** - * Returns the number of bytes required to encode these headers using HTTP/1.1. This is also the - * approximate size of HTTP/2 headers before they are compressed with HPACK. This value is - * intended to be used as a metric: smaller headers are more efficient to encode and transmit. - */ - fun byteCount(): Long { - // Each header name has 2 bytes of overhead for ': ' and every header value has 2 bytes of - // overhead for '\r\n'. - var result = (namesAndValues.size * 2).toLong() - - for (i in 0 until namesAndValues.size) { - result += namesAndValues[i].length.toLong() - } - - return result - } - - actual override operator fun iterator(): Iterator> = commonIterator() - - actual fun newBuilder(): Builder = commonNewBuilder() - - actual override fun equals(other: Any?): Boolean = commonEquals(other) - - override fun hashCode(): Int = commonHashCode() - - actual override fun toString(): String = commonToString() - - actual class Builder { - internal actual val namesAndValues: MutableList = ArrayList(20) - - actual fun add(name: String, value: String) = commonAdd(name, value) - - actual fun addAll(headers: Headers) = commonAddAll(headers) - - actual fun removeAll(name: String) = commonRemoveAll(name) - - /** - * Set a field with the specified value. If the field is not found, it is added. If the field is - * found, the existing values are replaced. - */ - actual operator fun set(name: String, value: String) = commonSet(name, value) - - /** Equivalent to `build().get(name)`, but potentially faster. */ - actual operator fun get(name: String): String? = commonGet(name) - - actual fun build(): Headers = commonBuild() - } - - actual companion object { - actual fun headersOf(vararg namesAndValues: String): Headers = commonHeadersOf(*namesAndValues) - - actual fun Map.toHeaders(): Headers = commonToHeaders() - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/HttpUrl.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/HttpUrl.kt deleted file mode 100644 index 6c8f464ac723..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/HttpUrl.kt +++ /dev/null @@ -1,479 +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 - -import okhttp3.HttpUrl.Companion.toHttpUrl -import okhttp3.HttpUrl.Companion.toHttpUrlOrNull -import okhttp3.internal.CommonHttpUrl -import okhttp3.internal.CommonHttpUrl.commonAddEncodedPathSegment -import okhttp3.internal.CommonHttpUrl.commonAddEncodedPathSegments -import okhttp3.internal.CommonHttpUrl.commonAddEncodedQueryParameter -import okhttp3.internal.CommonHttpUrl.commonAddPathSegment -import okhttp3.internal.CommonHttpUrl.commonAddPathSegments -import okhttp3.internal.CommonHttpUrl.commonAddQueryParameter -import okhttp3.internal.CommonHttpUrl.commonBuild -import okhttp3.internal.CommonHttpUrl.commonEncodedFragment -import okhttp3.internal.CommonHttpUrl.commonEncodedPassword -import okhttp3.internal.CommonHttpUrl.commonEncodedPath -import okhttp3.internal.CommonHttpUrl.commonEncodedPathSegments -import okhttp3.internal.CommonHttpUrl.commonEncodedQuery -import okhttp3.internal.CommonHttpUrl.commonEncodedUsername -import okhttp3.internal.CommonHttpUrl.commonEquals -import okhttp3.internal.CommonHttpUrl.commonFragment -import okhttp3.internal.CommonHttpUrl.commonHashCode -import okhttp3.internal.CommonHttpUrl.commonHost -import okhttp3.internal.CommonHttpUrl.commonIsHttps -import okhttp3.internal.CommonHttpUrl.commonNewBuilder -import okhttp3.internal.CommonHttpUrl.commonParse -import okhttp3.internal.CommonHttpUrl.commonPassword -import okhttp3.internal.CommonHttpUrl.commonPathSize -import okhttp3.internal.CommonHttpUrl.commonPort -import okhttp3.internal.CommonHttpUrl.commonQuery -import okhttp3.internal.CommonHttpUrl.commonQueryParameter -import okhttp3.internal.CommonHttpUrl.commonQueryParameterName -import okhttp3.internal.CommonHttpUrl.commonQueryParameterNames -import okhttp3.internal.CommonHttpUrl.commonQueryParameterValue -import okhttp3.internal.CommonHttpUrl.commonQueryParameterValues -import okhttp3.internal.CommonHttpUrl.commonQuerySize -import okhttp3.internal.CommonHttpUrl.commonRedact -import okhttp3.internal.CommonHttpUrl.commonRemoveAllEncodedQueryParameters -import okhttp3.internal.CommonHttpUrl.commonRemoveAllQueryParameters -import okhttp3.internal.CommonHttpUrl.commonRemovePathSegment -import okhttp3.internal.CommonHttpUrl.commonResolve -import okhttp3.internal.CommonHttpUrl.commonScheme -import okhttp3.internal.CommonHttpUrl.commonSetEncodedPathSegment -import okhttp3.internal.CommonHttpUrl.commonSetEncodedQueryParameter -import okhttp3.internal.CommonHttpUrl.commonSetPathSegment -import okhttp3.internal.CommonHttpUrl.commonSetQueryParameter -import okhttp3.internal.CommonHttpUrl.commonToHttpUrl -import okhttp3.internal.CommonHttpUrl.commonToHttpUrlOrNull -import okhttp3.internal.CommonHttpUrl.commonToString -import okhttp3.internal.CommonHttpUrl.commonUsername - -/** - * A uniform resource locator (URL) with a scheme of either `http` or `https`. Use this class to - * compose and decompose Internet addresses. For example, this code will compose and print a URL for - * Google search: - * - * ```java - * HttpUrl url = new HttpUrl.Builder() - * .scheme("https") - * .host("www.google.com") - * .addPathSegment("search") - * .addQueryParameter("q", "polar bears") - * .build(); - * System.out.println(url); - * ``` - * - * which prints: - * - * ``` - * https://www.google.com/search?q=polar%20bears - * ``` - * - * As another example, this code prints the human-readable query parameters of a Twitter search: - * - * ```java - * HttpUrl url = HttpUrl.parse("https://twitter.com/search?q=cute%20%23puppies&f=images"); - * for (int i = 0, size = url.querySize(); i < size; i++) { - * System.out.println(url.queryParameterName(i) + ": " + url.queryParameterValue(i)); - * } - * ``` - * - * which prints: - * - * ``` - * q: cute #puppies - * f: images - * ``` - * - * In addition to composing URLs from their component parts and decomposing URLs into their - * component parts, this class implements relative URL resolution: what address you'd reach by - * clicking a relative link on a specified page. For example: - * - * ```java - * HttpUrl base = HttpUrl.parse("https://www.youtube.com/user/WatchTheDaily/videos"); - * HttpUrl link = base.resolve("../../watch?v=cbP2N1BQdYc"); - * System.out.println(link); - * ``` - * - * which prints: - * - * ``` - * https://www.youtube.com/watch?v=cbP2N1BQdYc - * ``` - * - * ## What's in a URL? - * - * A URL has several components. - * - * ### Scheme - * - * Sometimes referred to as *protocol*, A URL's scheme describes what mechanism should be used to - * retrieve the resource. Although URLs have many schemes (`mailto`, `file`, `ftp`), this class only - * supports `http` and `https`. Use [java.net.URI][URI] for URLs with arbitrary schemes. - * - * ### Username and Password - * - * Username and password are either present, or the empty string `""` if absent. This class offers - * no mechanism to differentiate empty from absent. Neither of these components are popular in - * practice. Typically HTTP applications use other mechanisms for user identification and - * authentication. - * - * ### Host - * - * The host identifies the webserver that serves the URL's resource. It is either a hostname like - * `square.com` or `localhost`, an IPv4 address like `192.168.0.1`, or an IPv6 address like `::1`. - * - * Usually a webserver is reachable with multiple identifiers: its IP addresses, registered - * domain names, and even `localhost` when connecting from the server itself. Each of a web server's - * names is a distinct URL and they are not interchangeable. For example, even if - * `http://square.github.io/dagger` and `http://google.github.io/dagger` are served by the same IP - * address, the two URLs identify different resources. - * - * ### Port - * - * The port used to connect to the web server. By default this is 80 for HTTP and 443 for HTTPS. - * This class never returns -1 for the port: if no port is explicitly specified in the URL then the - * scheme's default is used. - * - * ### Path - * - * The path identifies a specific resource on the host. Paths have a hierarchical structure like - * "/square/okhttp/issues/1486" and decompose into a list of segments like `["square", "okhttp", - * "issues", "1486"]`. - * - * This class offers methods to compose and decompose paths by segment. It composes each path - * from a list of segments by alternating between "/" and the encoded segment. For example the - * segments `["a", "b"]` build "/a/b" and the segments `["a", "b", ""]` build "/a/b/". - * - * If a path's last segment is the empty string then the path ends with "/". This class always - * builds non-empty paths: if the path is omitted it defaults to "/". The default path's segment - * list is a single empty string: `[""]`. - * - * ### Query - * - * The query is optional: it can be null, empty, or non-empty. For many HTTP URLs the query string - * is subdivided into a collection of name-value parameters. This class offers methods to set the - * query as the single string, or as individual name-value parameters. With name-value parameters - * the values are optional and names may be repeated. - * - * ### Fragment - * - * The fragment is optional: it can be null, empty, or non-empty. Unlike host, port, path, and - * query the fragment is not sent to the webserver: it's private to the client. - * - * ## Encoding - * - * Each component must be encoded before it is embedded in the complete URL. As we saw above, the - * string `cute #puppies` is encoded as `cute%20%23puppies` when used as a query parameter value. - * - * ### Percent encoding - * - * Percent encoding replaces a character (like `\ud83c\udf69`) with its UTF-8 hex bytes (like - * `%F0%9F%8D%A9`). This approach works for whitespace characters, control characters, non-ASCII - * characters, and characters that already have another meaning in a particular context. - * - * Percent encoding is used in every URL component except for the hostname. But the set of - * characters that need to be encoded is different for each component. For example, the path - * component must escape all of its `?` characters, otherwise it could be interpreted as the - * start of the URL's query. But within the query and fragment components, the `?` character - * doesn't delimit anything and doesn't need to be escaped. - * - * ```java - * HttpUrl url = HttpUrl.parse("http://who-let-the-dogs.out").newBuilder() - * .addPathSegment("_Who?_") - * .query("_Who?_") - * .fragment("_Who?_") - * .build(); - * System.out.println(url); - * ``` - * - * This prints: - * - * ``` - * http://who-let-the-dogs.out/_Who%3F_?_Who?_#_Who?_ - * ``` - * - * When parsing URLs that lack percent encoding where it is required, this class will percent encode - * the offending characters. - * - * ### IDNA Mapping and Punycode encoding - * - * Hostnames have different requirements and use a different encoding scheme. It consists of IDNA - * mapping and Punycode encoding. - * - * In order to avoid confusion and discourage phishing attacks, [IDNA Mapping][idna] transforms - * names to avoid confusing characters. This includes basic case folding: transforming shouting - * `SQUARE.COM` into cool and casual `square.com`. It also handles more exotic characters. For - * example, the Unicode trademark sign (™) could be confused for the letters "TM" in - * `http://ho™ail.com`. To mitigate this, the single character (™) maps to the string (tm). There - * is similar policy for all of the 1.1 million Unicode code points. Note that some code points such - * as "\ud83c\udf69" are not mapped and cannot be used in a hostname. - * - * [Punycode](http://ietf.org/rfc/rfc3492.txt) converts a Unicode string to an ASCII string to make - * international domain names work everywhere. For example, "σ" encodes as "xn--4xa". The encoded - * string is not human readable, but can be used with classes like [InetAddress] to establish - * connections. - * - * ## Why another URL model? - * - * Java includes both [java.net.URL][URL] and [java.net.URI][URI]. We offer a new URL - * model to address problems that the others don't. - * - * ### Different URLs should be different - * - * Although they have different content, `java.net.URL` considers the following two URLs - * equal, and the [equals()][Object.equals] method between them returns true: - * - * * https://example.net/ - * - * * https://example.com/ - * - * This is because those two hosts share the same IP address. This is an old, bad design decision - * that makes `java.net.URL` unusable for many things. It shouldn't be used as a [Map] key or in a - * [Set]. Doing so is both inefficient because equality may require a DNS lookup, and incorrect - * because unequal URLs may be equal because of how they are hosted. - * - * ### Equal URLs should be equal - * - * These two URLs are semantically identical, but `java.net.URI` disagrees: - * - * * http://host:80/ - * - * * http://host - * - * Both the unnecessary port specification (`:80`) and the absent trailing slash (`/`) cause URI to - * bucket the two URLs separately. This harms URI's usefulness in collections. Any application that - * stores information-per-URL will need to either canonicalize manually, or suffer unnecessary - * redundancy for such URLs. - * - * Because they don't attempt canonical form, these classes are surprisingly difficult to use - * securely. Suppose you're building a webservice that checks that incoming paths are prefixed - * "/static/images/" before serving the corresponding assets from the filesystem. - * - * ```java - * String attack = "http://example.com/static/images/../../../../../etc/passwd"; - * System.out.println(new URL(attack).getPath()); - * System.out.println(new URI(attack).getPath()); - * System.out.println(HttpUrl.parse(attack).encodedPath()); - * ``` - * - * By canonicalizing the input paths, they are complicit in directory traversal attacks. Code that - * checks only the path prefix may suffer! - * - * ``` - * /static/images/../../../../../etc/passwd - * /static/images/../../../../../etc/passwd - * /etc/passwd - * ``` - * - * ### If it works on the web, it should work in your application - * - * The `java.net.URI` class is strict around what URLs it accepts. It rejects URLs like - * `http://example.com/abc|def` because the `|` character is unsupported. This class is more - * forgiving: it will automatically percent-encode the `|'` yielding `http://example.com/abc%7Cdef`. - * This kind behavior is consistent with web browsers. `HttpUrl` prefers consistency with major web - * browsers over consistency with obsolete specifications. - * - * ### Paths and Queries should decompose - * - * Neither of the built-in URL models offer direct access to path segments or query parameters. - * Manually using `StringBuilder` to assemble these components is cumbersome: do '+' characters get - * silently replaced with spaces? If a query parameter contains a '&', does that get escaped? - * By offering methods to read and write individual query parameters directly, application - * developers are saved from the hassles of encoding and decoding. - * - * ### Plus a modern API - * - * The URL (JDK1.0) and URI (Java 1.4) classes predate builders and instead use telescoping - * constructors. For example, there's no API to compose a URI with a custom port without also - * providing a query and fragment. - * - * Instances of [HttpUrl] are well-formed and always have a scheme, host, and path. With - * `java.net.URL` it's possible to create an awkward URL like `http:/` with scheme and path but no - * hostname. Building APIs that consume such malformed values is difficult! - * - * This class has a modern API. It avoids punitive checked exceptions: [toHttpUrl] throws - * [IllegalArgumentException] on invalid input or [toHttpUrlOrNull] returns null if the input is an - * invalid URL. You can even be explicit about whether each component has been encoded already. - * - * [idna]: http://www.unicode.org/reports/tr46/#ToASCII - */ -actual class HttpUrl internal actual constructor( - actual val scheme: String, - actual val username: String, - actual val password: String, - actual val host: String, - actual val port: Int, - actual val pathSegments: List, - internal actual val queryNamesAndValues: List?, - actual val fragment: String?, - internal actual val url: String -) { - - actual val isHttps: Boolean - get() = commonIsHttps - - actual val encodedUsername: String - get() = commonEncodedUsername - - actual val encodedPassword: String - get() = commonEncodedPassword - - actual val pathSize: Int - get() = commonPathSize - - actual val encodedPath: String - get() = commonEncodedPath - - actual val encodedPathSegments: List - get() = commonEncodedPathSegments - - actual val encodedQuery: String? - get() = commonEncodedQuery - - actual val query: String? - get() = commonQuery - - actual val querySize: Int - get() = commonQuerySize - - actual fun queryParameter(name: String): String? = commonQueryParameter(name) - - actual val queryParameterNames: Set - get() = commonQueryParameterNames - - actual fun queryParameterValues(name: String): List = commonQueryParameterValues(name) - - actual fun queryParameterName(index: Int): String = commonQueryParameterName(index) - - actual fun queryParameterValue(index: Int): String? = commonQueryParameterValue(index) - - actual val encodedFragment: String? - get() = commonEncodedFragment - - actual fun redact(): String = commonRedact() - - actual fun resolve(link: String): HttpUrl? = commonResolve(link) - - actual fun newBuilder(): HttpUrl.Builder = commonNewBuilder() - - actual fun newBuilder(link: String): Builder? = commonNewBuilder(link) - - override fun equals(other: Any?): Boolean = commonEquals(other) - - override fun hashCode(): Int = commonHashCode() - - override fun toString(): String = commonToString() - - actual companion object { - actual fun String.toHttpUrl(): HttpUrl = commonToHttpUrl() - - actual fun String.toHttpUrlOrNull(): HttpUrl? = commonToHttpUrlOrNull() - - actual fun defaultPort(scheme: String): Int = CommonHttpUrl.commonDefaultPort(scheme) - } - - actual class Builder { - internal actual var scheme: String? = null - internal actual var encodedUsername = "" - internal actual var encodedPassword = "" - internal actual var host: String? = null - internal actual var port = -1 - internal actual val encodedPathSegments = mutableListOf("") - internal actual var encodedQueryNamesAndValues: MutableList? = null - internal actual var encodedFragment: String? = null - - /** - * @param scheme either "http" or "https". - */ - actual fun scheme(scheme: String) = commonScheme(scheme) - - actual fun username(username: String) = commonUsername(username) - - actual fun encodedUsername(encodedUsername: String) = commonEncodedUsername(encodedUsername) - - actual fun password(password: String) = commonPassword(password) - - actual fun encodedPassword(encodedPassword: String) = commonEncodedPassword(encodedPassword) - - /** - * @param host either a regular hostname, International Domain Name, IPv4 address, or IPv6 - * address. - */ - actual fun host(host: String) = commonHost(host) - - actual fun port(port: Int) = commonPort(port) - - actual fun addPathSegment(pathSegment: String) = commonAddPathSegment(pathSegment) - - /** - * Adds a set of path segments separated by a slash (either `\` or `/`). If `pathSegments` - * starts with a slash, the resulting URL will have empty path segment. - */ - actual fun addPathSegments(pathSegments: String): Builder = commonAddPathSegments(pathSegments) - - actual fun addEncodedPathSegment(encodedPathSegment: String) = commonAddEncodedPathSegment(encodedPathSegment) - - /** - * Adds a set of encoded path segments separated by a slash (either `\` or `/`). If - * `encodedPathSegments` starts with a slash, the resulting URL will have empty path segment. - */ - actual fun addEncodedPathSegments(encodedPathSegments: String): Builder = - commonAddEncodedPathSegments(encodedPathSegments) - - - actual fun setPathSegment(index: Int, pathSegment: String) = commonSetPathSegment(index, pathSegment) - - actual fun setEncodedPathSegment(index: Int, encodedPathSegment: String) = - commonSetEncodedPathSegment(index, encodedPathSegment) - - actual fun removePathSegment(index: Int) = commonRemovePathSegment(index) - - actual fun encodedPath(encodedPath: String) = commonEncodedPath(encodedPath) - - actual fun query(query: String?) = commonQuery(query) - - actual fun encodedQuery(encodedQuery: String?) = commonEncodedQuery(encodedQuery) - - /** Encodes the query parameter using UTF-8 and adds it to this URL's query string. */ - actual fun addQueryParameter(name: String, value: String?) = commonAddQueryParameter(name, value) - - /** Adds the pre-encoded query parameter to this URL's query string. */ - actual fun addEncodedQueryParameter(encodedName: String, encodedValue: String?) = - commonAddEncodedQueryParameter(encodedName, encodedValue) - - actual fun setQueryParameter(name: String, value: String?) = commonSetQueryParameter(name, value) - - actual fun setEncodedQueryParameter(encodedName: String, encodedValue: String?) = - commonSetEncodedQueryParameter(encodedName, encodedValue) - - actual fun removeAllQueryParameters(name: String) = commonRemoveAllQueryParameters(name) - - actual fun removeAllEncodedQueryParameters(encodedName: String) = commonRemoveAllEncodedQueryParameters(encodedName) - - actual fun fragment(fragment: String?) = commonFragment(fragment) - - actual fun encodedFragment(encodedFragment: String?) = commonEncodedFragment(encodedFragment) - - actual fun build(): HttpUrl = commonBuild() - - override fun toString(): String = commonToString() - - internal actual fun parse(base: HttpUrl?, input: String): Builder = commonParse(base, input) - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/MediaType.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/MediaType.kt deleted file mode 100644 index c83bf078a674..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/MediaType.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2013 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 - -import okhttp3.internal.commonEquals -import okhttp3.internal.commonHashCode -import okhttp3.internal.commonParameter -import okhttp3.internal.commonToMediaType -import okhttp3.internal.commonToMediaTypeOrNull -import okhttp3.internal.commonToString - -actual class MediaType internal actual constructor( - internal actual val mediaType: String, - - actual val type: String, - - actual val subtype: String, - - internal actual val parameterNamesAndValues: Array -) { - actual fun parameter(name: String): String? = commonParameter(name) - - actual override fun toString(): String = commonToString() - - override fun equals(other: Any?): Boolean = commonEquals(other) - - override fun hashCode(): Int = commonHashCode() - - actual companion object { - actual fun String.toMediaType(): MediaType = commonToMediaType() - - actual fun String.toMediaTypeOrNull(): MediaType? = commonToMediaTypeOrNull() - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/Request.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/Request.kt deleted file mode 100644 index f9b1f9dcbfd1..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/Request.kt +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2013 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 - -import okhttp3.HttpUrl.Companion.toHttpUrl -import okhttp3.internal.canonicalUrl -import okhttp3.internal.commonAddHeader -import okhttp3.internal.commonCacheControl -import okhttp3.internal.commonDelete -import okhttp3.internal.commonGet -import okhttp3.internal.commonHead -import okhttp3.internal.commonHeader -import okhttp3.internal.commonHeaders -import okhttp3.internal.commonMethod -import okhttp3.internal.commonNewBuilder -import okhttp3.internal.commonPatch -import okhttp3.internal.commonPost -import okhttp3.internal.commonPut -import okhttp3.internal.commonRemoveHeader -import okhttp3.internal.commonTag -import okhttp3.internal.commonToString -import kotlin.reflect.KClass - -actual class Request internal actual constructor(builder: Builder) { - actual val url: HttpUrl = checkNotNull(builder.url) { "url == null" } - actual val method: String = builder.method - actual val headers: Headers = builder.headers.build() - actual val body: RequestBody? = builder.body - internal actual val tags: Map, Any> = builder.tags.toMap() - - internal actual var lazyCacheControl: CacheControl? = null - - actual val isHttps: Boolean - get() = url.isHttps - - /** - * Constructs a new request. - * - * Use [Builder] for more fluent construction, including helper methods for various HTTP methods. - * - * @param method defaults to "GET" if [body] is null, and "POST" otherwise. - */ - actual constructor( - url: HttpUrl, - headers: Headers, - method: String, - body: RequestBody?, - ) : this( - Builder() - .url(url) - .headers(headers) - .method( - when { - method != "\u0000" -> method - body != null -> "POST" - else -> "GET" - }, - body - ) - ) - - actual fun header(name: String): String? = commonHeader(name) - - actual fun headers(name: String): List = commonHeaders(name) - - actual fun newBuilder(): Builder = commonNewBuilder() - - actual val cacheControl: CacheControl - get() = commonCacheControl() - - actual inline fun tag(): T? = tag(T::class) - - actual fun tag(type: KClass): T? = tags[type] as T? - - override fun toString(): String = commonToString() - - actual open class Builder { - internal actual var url: HttpUrl? = null - internal actual var method: String - internal actual var headers: Headers.Builder - internal actual var body: RequestBody? = null - internal actual var tags = mapOf, Any>() - - // /** A mutable map of tags, or an immutable empty map if we don't have any. */ - // internal var tags: MutableMap, Any> = mutableMapOf() - - actual constructor() { - this.method = "GET" - this.headers = Headers.Builder() - } - - internal actual constructor(request: Request) { - this.url = request.url - this.method = request.method - this.body = request.body - this.tags = when { - request.tags.isEmpty() -> mapOf() - else -> request.tags.toMutableMap() - } - this.headers = request.headers.newBuilder() - } - - actual open fun url(url: HttpUrl): Builder = apply { - this.url = url - } - - actual open fun url(url: String): Builder = apply { - url(canonicalUrl(url).toHttpUrl()) - } - - actual open fun header(name: String, value: String) = commonHeader(name, value) - - actual open fun addHeader(name: String, value: String) = commonAddHeader(name, value) - - actual open fun removeHeader(name: String) = commonRemoveHeader(name) - - actual open fun headers(headers: Headers) = commonHeaders(headers) - - actual open fun cacheControl(cacheControl: CacheControl): Builder = commonCacheControl(cacheControl) - - actual open fun get(): Builder = commonGet() - - actual open fun head(): Builder = commonHead() - - actual open fun post(body: RequestBody): Builder = commonPost(body) - - actual open fun delete(body: RequestBody?): Builder = commonDelete(body) - - actual open fun put(body: RequestBody): Builder = commonPut(body) - - actual open fun patch(body: RequestBody): Builder = commonPatch(body) - - actual open fun method(method: String, body: RequestBody?): Builder = commonMethod(method, body) - - actual inline fun tag(tag: T?): Builder = tag(T::class, tag) - - actual fun tag(type: KClass, tag: T?): Builder = commonTag(type, tag) - - actual open fun build(): Request = Request(this) - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/RequestBody.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/RequestBody.kt deleted file mode 100644 index a3804f15ceb3..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/RequestBody.kt +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2014 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 - -import okhttp3.MediaType.Companion.toMediaTypeOrNull -import okhttp3.internal.commonContentLength -import okhttp3.internal.commonIsDuplex -import okhttp3.internal.commonIsOneShot -import okhttp3.internal.commonToRequestBody -import okio.BufferedSink -import okio.ByteString -import okio.internal.commonAsUtf8ToByteArray - -actual abstract class RequestBody { - actual abstract fun contentType(): MediaType? - - actual open fun contentLength(): Long = commonContentLength() - - actual abstract fun writeTo(sink: BufferedSink) - - actual open fun isDuplex(): Boolean = commonIsDuplex() - - actual open fun isOneShot(): Boolean = commonIsOneShot() - - actual companion object { - actual fun String.toRequestBody(contentType: MediaType?): RequestBody { - val bytes = commonAsUtf8ToByteArray() - - val resolvedContentType = if (contentType != null && contentType.parameter("charset") == null) { - "$contentType; charset=utf-8".toMediaTypeOrNull() - } else { - contentType - } - - return bytes.toRequestBody(resolvedContentType, 0, bytes.size) - } - - actual fun ByteString.toRequestBody(contentType: MediaType?): RequestBody = - commonToRequestBody(contentType) - - actual fun ByteArray.toRequestBody( - contentType: MediaType?, - offset: Int, - byteCount: Int - ): RequestBody = commonToRequestBody(contentType, offset, byteCount) - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/Response.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/Response.kt deleted file mode 100644 index a2175f61abcf..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/Response.kt +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (C) 2013 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 - -import okhttp3.internal.commonAddHeader -import okhttp3.internal.commonBody -import okhttp3.internal.commonCacheControl -import okhttp3.internal.commonCacheResponse -import okhttp3.internal.commonCode -import okhttp3.internal.commonEmptyResponse -import okhttp3.internal.commonHeader -import okhttp3.internal.commonHeaders -import okhttp3.internal.commonIsRedirect -import okhttp3.internal.commonIsSuccessful -import okhttp3.internal.commonMessage -import okhttp3.internal.commonNetworkResponse -import okhttp3.internal.commonNewBuilder -import okhttp3.internal.commonPeekBody -import okhttp3.internal.commonPriorResponse -import okhttp3.internal.commonProtocol -import okhttp3.internal.commonRemoveHeader -import okhttp3.internal.commonRequest -import okhttp3.internal.commonTrailers -import okio.Closeable - -/** - * An HTTP response. Instances of this class are not immutable: the response body is a one-shot - * value that may be consumed only once and then closed. All other properties are immutable. - * - * This class implements [Closeable]. Closing it simply closes its response body. See - * [ResponseBody] for an explanation and examples. - */ -actual class Response internal constructor( - /** - * The request that initiated this HTTP response. This is not necessarily the same request issued - * by the application: - * - * * It may be transformed by the user's interceptors. For example, an application interceptor - * may add headers like `User-Agent`. - * * It may be the request generated in response to an HTTP redirect or authentication - * challenge. In this case the request URL may be different than the initial request URL. - * - * Use the `request` of the [networkResponse] field to get the wire-level request that was - * transmitted. In the case of follow-ups and redirects, also look at the `request` of the - * [priorResponse] objects, which have its own [priorResponse]. - */ - actual val request: Request, - - /** Returns the HTTP protocol, such as [Protocol.HTTP_1_1] or [Protocol.HTTP_1_0]. */ - actual val protocol: Protocol, - - /** Returns the HTTP status message. */ - actual val message: String, - - /** Returns the HTTP status code. */ - actual val code: Int, - - /** Returns the HTTP headers. */ - actual val headers: Headers, - - /** - * Returns a non-null value if this response was passed to [Callback.onResponse] or returned - * from [Call.execute]. Response bodies must be [closed][ResponseBody] and may - * be consumed only once. - * - * This always returns null on responses returned from [cacheResponse], [networkResponse], - * and [priorResponse]. - */ - actual val body: ResponseBody, - - /** - * Returns the raw response received from the network. Will be null if this response didn't use - * the network, such as when the response is fully cached. The body of the returned response - * should not be read. - */ - actual val networkResponse: Response?, - - /** - * Returns the raw response received from the cache. Will be null if this response didn't use - * the cache. For conditional get requests the cache response and network response may both be - * non-null. The body of the returned response should not be read. - */ - actual val cacheResponse: Response?, - - /** - * Returns the response for the HTTP redirect or authorization challenge that triggered this - * response, or null if this response wasn't triggered by an automatic retry. The body of the - * returned response should not be read because it has already been consumed by the redirecting - * client. - */ - actual val priorResponse: Response?, - - private var trailersFn: (() -> Headers) = { Headers.headersOf() } -) : Closeable { - - internal actual var lazyCacheControl: CacheControl? = null - - /** - * Returns true if the code is in [200..300), which means the request was successfully received, - * understood, and accepted. - */ - actual val isSuccessful: Boolean = commonIsSuccessful - - actual fun headers(name: String): List = commonHeaders(name) - - actual fun header(name: String, defaultValue: String?): String? = commonHeader(name, defaultValue) - - actual fun trailers(): Headers = trailersFn.invoke() - - /** - * Peeks up to [byteCount] bytes from the response body and returns them as a new response - * body. If fewer than [byteCount] bytes are in the response body, the full response body is - * returned. If more than [byteCount] bytes are in the response body, the returned value - * will be truncated to [byteCount] bytes. - * - * It is an error to call this method after the body has been consumed. - * - * **Warning:** this method loads the requested bytes into memory. Most applications should set - * a modest limit on `byteCount`, such as 1 MiB. - */ - actual fun peekBody(byteCount: Long): ResponseBody = commonPeekBody(byteCount) - - actual fun newBuilder(): Builder = commonNewBuilder() - - /** Returns true if this response redirects to another resource. */ - actual val isRedirect: Boolean - get() = commonIsRedirect - - /** - * Returns the cache control directives for this response. This is never null, even if this - * response contains no `Cache-Control` header. - */ - actual val cacheControl: CacheControl - get() = commonCacheControl - - /** - * Closes the response body. Equivalent to `body().close()`. - * - * Prior to OkHttp 5.0, it was an error to close a response that is not eligible for a body. This - * includes the responses returned from [cacheResponse], [networkResponse], and [priorResponse]. - */ - actual override fun close() { - body.close() - } - - actual override fun toString(): String = - "Response{protocol=$protocol, code=$code, message=$message, url=${request.url}}" - - actual open class Builder { - internal actual var request: Request? = null - internal actual var protocol: Protocol? = null - internal actual var code = -1 - internal actual var message: String? = null - internal actual var headers: Headers.Builder - internal actual var body: ResponseBody = commonEmptyResponse - internal actual var networkResponse: Response? = null - internal actual var cacheResponse: Response? = null - internal actual var priorResponse: Response? = null - internal actual var trailersFn: (() -> Headers) = { Headers.headersOf() } - - actual constructor() { - headers = Headers.Builder() - } - - internal actual constructor(response: Response) { - this.request = response.request - this.protocol = response.protocol - this.code = response.code - this.message = response.message - this.headers = response.headers.newBuilder() - this.body = response.body - this.networkResponse = response.networkResponse - this.cacheResponse = response.cacheResponse - this.priorResponse = response.priorResponse - } - - actual open fun request(request: Request) = commonRequest(request) - - actual open fun protocol(protocol: Protocol) =commonProtocol(protocol) - - actual open fun code(code: Int) = commonCode(code) - - actual open fun message(message: String) = commonMessage(message) - - /** - * Sets the header named [name] to [value]. If this request already has any headers - * with that name, they are all replaced. - */ - actual open fun header(name: String, value: String) = commonHeader(name, value) - - /** - * Adds a header with [name] to [value]. Prefer this method for multiply-valued - * headers like "Set-Cookie". - */ - actual open fun addHeader(name: String, value: String) = commonAddHeader(name, value) - - /** Removes all headers named [name] on this builder. */ - actual open fun removeHeader(name: String) = commonRemoveHeader(name) - - /** Removes all headers on this builder and adds [headers]. */ - actual open fun headers(headers: Headers) = commonHeaders(headers) - - actual open fun trailers(trailersFn: (() -> Headers)): Builder = commonTrailers(trailersFn) - - actual open fun body(body: ResponseBody) = commonBody(body) - - actual open fun networkResponse(networkResponse: Response?) = commonNetworkResponse(networkResponse) - - actual open fun cacheResponse(cacheResponse: Response?) = commonCacheResponse(cacheResponse) - - actual open fun priorResponse(priorResponse: Response?) = commonPriorResponse(priorResponse) - - actual open fun build(): Response { - check(code >= 0) { "code < 0: $code" } - return Response( - checkNotNull(request) { "request == null" }, - checkNotNull(protocol) { "protocol == null" }, - checkNotNull(message) { "message == null" }, - code, - headers.build(), - body, - networkResponse, - cacheResponse, - priorResponse, - trailersFn - ) - } - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/ResponseBody.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/ResponseBody.kt deleted file mode 100644 index 10993d5b4646..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/ResponseBody.kt +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2014 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 - -import okhttp3.internal.commonAsResponseBody -import okhttp3.internal.commonByteString -import okhttp3.internal.commonBytes -import okhttp3.internal.commonClose -import okhttp3.internal.commonToResponseBody -import okio.Buffer -import okio.BufferedSource -import okio.ByteString -import okio.Closeable -import okio.IOException - -actual abstract class ResponseBody : Closeable { - actual abstract fun contentType(): MediaType? - - actual abstract fun contentLength(): Long - - actual abstract fun source(): BufferedSource - - actual fun bytes() = commonBytes() - - actual fun byteString() = commonByteString() - - actual fun string(): String { - val charset = contentType()?.parameter("charset") ?: "UTF-8" - if (!charset.equals("UTF-8", ignoreCase = true)) { - throw IOException("Unsupported encoding '$charset'") - } - return source().readUtf8() - } - - actual override fun close() = commonClose() - - actual companion object { - actual fun String.toResponseBody(contentType: MediaType?): ResponseBody { - val buffer = Buffer().writeUtf8(this) - // TODO ignore charset? fail on non utf-8? override? - return buffer.asResponseBody(contentType, buffer.size) - } - - actual fun ByteArray.toResponseBody(contentType: MediaType?): ResponseBody = commonToResponseBody(contentType) - - actual fun ByteString.toResponseBody(contentType: MediaType?): ResponseBody = commonToResponseBody(contentType) - - actual fun BufferedSource.asResponseBody( - contentType: MediaType?, - contentLength: Long - ): ResponseBody = commonAsResponseBody(contentType, contentLength) - } -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/TlsVersion.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/TlsVersion.kt deleted file mode 100644 index 8178f9de18bb..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/TlsVersion.kt +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2021 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 - -actual enum class TlsVersion { - TLS_1_3, // 2016. - TLS_1_2, // 2008. - TLS_1_1, // 2006. - TLS_1_0, // 1999. - SSL_3_0; // 1996. -} diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/internal/-HttpUrlNonJvm.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/internal/-HttpUrlNonJvm.kt deleted file mode 100644 index 510dcf56b62b..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/internal/-HttpUrlNonJvm.kt +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2022 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 - -import okhttp3.internal.CommonHttpUrl.isPercentEncoded -import okhttp3.internal.NonJvmHttpUrl.writeCanonicalized -import okio.Buffer - -internal object NonJvmHttpUrl { - internal fun Buffer.writeCanonicalized( - input: String, - pos: Int, - limit: Int, - encodeSet: String, - alreadyEncoded: Boolean, - strict: Boolean, - plusIsSpace: Boolean, - unicodeAllowed: Boolean, - ) { - var encodedCharBuffer: Buffer? = null // Lazily allocated. - var codePoint: Int - var i = pos - while (i < limit) { - codePoint = input[i].code - if (alreadyEncoded && (codePoint == '\t'.code || codePoint == '\n'.code || - codePoint == '\u000c'.code || codePoint == '\r'.code)) { - // Skip this character. - } else if (codePoint == ' '.code && encodeSet === CommonHttpUrl.FORM_ENCODE_SET) { - // Encode ' ' as '+'. - writeUtf8("+") - } else if (codePoint == '+'.code && plusIsSpace) { - // Encode '+' as '%2B' since we permit ' ' to be encoded as either '+' or '%20'. - writeUtf8(if (alreadyEncoded) "+" else "%2B") - } else if (codePoint < 0x20 || - codePoint == 0x7f || - codePoint >= 0x80 && !unicodeAllowed || - codePoint.toChar() in encodeSet || - codePoint == '%'.code && - (!alreadyEncoded || strict && !input.isPercentEncoded(i, limit))) { - // Percent encode this character. - if (encodedCharBuffer == null) { - encodedCharBuffer = Buffer() - } - - encodedCharBuffer.writeUtf8CodePoint(codePoint) - - while (!encodedCharBuffer.exhausted()) { - val b = encodedCharBuffer.readByte().toInt() and 0xff - writeByte('%'.code) - writeByte(CommonHttpUrl.HEX_DIGITS[b shr 4 and 0xf].code) - writeByte(CommonHttpUrl.HEX_DIGITS[b and 0xf].code) - } - } else { - // This character doesn't need encoding. Just copy it over. - writeUtf8CodePoint(codePoint) - } - i += 1 - } - } -} - -internal actual object HttpUrlCommon { - internal actual fun Buffer.writePercentDecoded( - encoded: String, - pos: Int, - limit: Int, - plusIsSpace: Boolean - ) { - var codePoint: Int - var i = pos - while (i < limit) { - codePoint = encoded.get(i).code - if (codePoint == '%'.code && i + 2 < limit) { - val d1 = encoded[i + 1].parseHexDigit() - val d2 = encoded[i + 2].parseHexDigit() - if (d1 != -1 && d2 != -1) { - writeByte((d1 shl 4) + d2) - i += 2 - i += 1 - continue - } - } else if (codePoint == '+'.code && plusIsSpace) { - writeByte(' '.code) - i++ - continue - } - writeUtf8CodePoint(codePoint) - i += 1 - } - } - - internal actual fun String.canonicalize( - pos: Int, - limit: Int, - encodeSet: String, - alreadyEncoded: Boolean, - strict: Boolean, - plusIsSpace: Boolean, - unicodeAllowed: Boolean, - ): String { - var codePoint: Int - var i = pos - while (i < limit) { - codePoint = this[i].code - if (codePoint < 0x20 || - codePoint == 0x7f || - codePoint >= 0x80 && !unicodeAllowed || - codePoint.toChar() in encodeSet || - codePoint == '%'.code && - (!alreadyEncoded || strict && !isPercentEncoded(i, limit)) || - codePoint == '+'.code && plusIsSpace - ) { - // Slow path: the character at i requires encoding! - val out = Buffer() - out.writeUtf8(this, pos, i) - out.writeCanonicalized( - input = this, - pos = i, - limit = limit, - encodeSet = encodeSet, - alreadyEncoded = alreadyEncoded, - strict = strict, - plusIsSpace = plusIsSpace, - unicodeAllowed = unicodeAllowed, - ) - return out.readUtf8() - } - i += 1 - } - - // Fast path: no characters in [pos..limit) required encoding. - return substring(pos, limit) - } -} - diff --git a/okhttp/src/nonJvmMain/kotlin/okhttp3/internal/-NormalizeNonJvm.kt b/okhttp/src/nonJvmMain/kotlin/okhttp3/internal/-NormalizeNonJvm.kt deleted file mode 100644 index 6768ecec2bf6..000000000000 --- a/okhttp/src/nonJvmMain/kotlin/okhttp3/internal/-NormalizeNonJvm.kt +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2022 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 - -import com.squareup.okhttpicu.SYSTEM_NORMALIZER - -internal actual fun normalizeNfc(string: String): String = - SYSTEM_NORMALIZER.normalizeNfc(string) diff --git a/okhttp/src/nonJvmTest/kotlin/okhttp3/ResponseBodyNonJvmTest.kt b/okhttp/src/nonJvmTest/kotlin/okhttp3/ResponseBodyNonJvmTest.kt deleted file mode 100644 index a0e3c34fb284..000000000000 --- a/okhttp/src/nonJvmTest/kotlin/okhttp3/ResponseBodyNonJvmTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2016 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 - -import assertk.assertThat -import assertk.assertions.isEqualTo -import kotlin.test.Test -import kotlin.test.fail -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.ResponseBody.Companion.toResponseBody -import okio.IOException - -class ResponseBodyNonJvmTest { - @Test - fun unicodeTextWithUnsupportedEncoding() { - val text = "eile oli oliiviõli" - val body = text.toResponseBody("text/plain; charset=EBCDIC".toMediaType()) - try { - assertThat(body.string()).isEqualTo(text) - fail() - } catch (ioe: IOException) { - assertThat(ioe.message).isEqualTo("Unsupported encoding 'EBCDIC'") - } - } -} diff --git a/okhttp/src/nonJvmTest/kotlin/okhttp3/ResponseNonJvmTest.kt b/okhttp/src/nonJvmTest/kotlin/okhttp3/ResponseNonJvmTest.kt deleted file mode 100644 index 9bce9452633b..000000000000 --- a/okhttp/src/nonJvmTest/kotlin/okhttp3/ResponseNonJvmTest.kt +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2016 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 - -import assertk.assertThat -import assertk.assertions.isEmpty -import assertk.assertions.isEqualTo -import kotlin.test.Test -import okhttp3.ResponseBody.Companion.toResponseBody - -class ResponseNonJvmTest { - @Test - fun testEmptyIfTrailersNotSet() { - val response = newResponse("".toResponseBody()) - - assertThat(response.trailers()).isEmpty() - } - - @Test - fun worksIfTrailersSet() { - val response = newResponse("".toResponseBody()) { - trailers { - Headers.headersOf("a", "b") - } - } - - assertThat(response.trailers()["a"]).isEqualTo("b") - } - - private fun newResponse( - responseBody: ResponseBody, - code: Int = 200, - fn: Response.Builder.() -> Unit = {} - ): Response { - return Response.Builder() - .request( - Request.Builder() - .url("https://example.com/") - .build() - ) - .protocol(Protocol.HTTP_1_1) - .code(code) - .message("OK") - .body(responseBody) - .apply { fn() } - .build() - } -}